-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathRakefile
More file actions
102 lines (90 loc) · 2.77 KB
/
Rakefile
File metadata and controls
102 lines (90 loc) · 2.77 KB
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
require 'rspec/core/rake_task'
RSpec::Core::RakeTask.new(:spec)
task :default => :spec
require 'json'
require 'fileutils'
desc 'Rewrite JSON files with consistent formatting'
task :format_json do
[
['schemas'],
['schemas', 'includes'],
['spec', '**'],
].each do |parts|
Dir.glob(File.join(*parts, '*.json')).each do |path|
data = JSON.parse(File.read(path))
File.open(path, 'w') do |f|
f.puts(JSON.pretty_generate(data))
end
end
end
end
desc 'Write schema files with embedded references'
task :build do
# @see https://github.com/influencemapping/whos_got_dirt-gem/blob/master/Rakefile
def define(name, path, definitions)
unless definitions.key?(name)
definitions[name] = {} # to avoid recursion
definitions[name] = process_schema(path, definitions)
end
end
def process_value(value, path, definitions)
if value.key?('$ref')
ref = value['$ref']
unless ref.start_with?('#/definitions/')
name = File.basename(ref).chomp('.json')
value['$ref'] = "#/definitions/#{name}"
define(name, File.expand_path(ref, File.dirname(path)), definitions)
end
end
value
end
def process_object(value, path, definitions)
if value.key?('properties')
process_properties(value['properties'], path, definitions)
else
keyword = (value.keys & ['allOf', 'anyOf', 'oneOf']).first
if keyword
value[keyword].each do |subschema|
process_object(subschema, path, definitions)
end
else
process_value(value, path, definitions)
end
end
value
end
def process_properties(properties, path, definitions)
properties.each do |_,value|
if value.key?('items')
process_object(value['items'], path, definitions)
else
process_object(value, path, definitions)
end
end
properties
end
def process_schema(path, definitions)
schema = JSON.load(File.read(path))
if schema.key?('definitions')
schema['definitions'].each do |_,definition|
process_object(definition, path, definitions)
end
definitions.merge!(schema['definitions'])
end
process_object(schema, path, definitions)
end
all_definitions = {}
generated = []
Dir[File.join('schemas', '*.json')].each do |path|
definitions = {} # passed by reference
schema = process_schema(path, definitions).merge('definitions' => definitions)
all_definitions.merge!(definitions) # cache definitions across schema
File.open(File.join('build', File.basename(path)), 'w') do |f|
f.write(JSON.pretty_generate(schema))
end
generated << File.basename(path)
end
Dir[File.join('build', '*.json')].each do |path|
FileUtils.rm(path) unless generated.include?(File.basename(path))
end
end