-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathparse.rb
108 lines (93 loc) · 2.24 KB
/
parse.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
require 'json'
require 'faraday'
class Parser
attr_reader :name
def initialize(name)
@name = name
end
def schema
{
"$schema": "http://json-schema.org/draft-04/schema#",
"@type": type,
"@context": "http://schema.org/",
"description": "Schema.org #{type}",
"type": "object",
"definitions": parsed_definitions,
"allOf": definitions.keys.map { |name| "#definitions/#{name}" }
}
end
def data
@data ||= JSON.parse source
end
def type
data['type']
end
def source
path = File.expand_path("./sources/#{name}.json")
File.read path
end
def definitions
@definitions ||= begin
defs = data['bases'] || {}
defs[type] = data['properties'] if data['properties']
defs
end
end
def parsed_definitions
@parsed_definitions ||= begin
defs = {}
definitions.each do |name, props|
defs[name] = {
'@type': name,
type: 'object',
properties: parsed_properties(props)
}
end
defs
end
end
def parsed_properties(properties)
props_arr = properties.map do |prop|
attrs = {}
attrs['description'] = prop['description']
case prop['type']
when 'Text'
attrs['type'] = 'string'
when 'URL'
attrs['type'] = 'string'
attrs['format'] = 'uri'
when 'Date', 'Datetime'
attrs['type'] = 'string'
attrs['format'] = 'date'
when 'Number', 'Float', 'Integer'
attrs['type'] = 'number'
when 'Boolean'
attrs['type'] == 'boolean'
else
if prop['type'].is_a? Array
attrs['anyOf'] = prop['type'].map {|t| {'$ref': "#{t}.json"} }
else
attrs['$ref'] = "#{prop['type']}.json"
end
end
[prop['name'], attrs]
end
Hash[ *props_arr.flatten ]
end
end
def parse_all
folder = File.expand_path './sources'
Dir.foreach(folder) do |filename|
next if filename.start_with?('.')
name = filename.gsub '.json', ''
parser = Parser.new(name)
output_file = "./schemas/#{parser.type}.json"
File.open output_file, 'w' do |f|
f.write JSON.pretty_unparse(parser.schema)
puts ">> #{output_file}"
end
end
end
if __FILE__ == $0
parse_all
end