openapi-arrangement 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 0d131667f320634f4b75da00e14571872d65b4d05d4094c894dab7c4f2d6aadd
4
+ data.tar.gz: c95734699bbc4530c9632d8231d1ba84110d77bcfaf2cc3476e03066c2942474
5
+ SHA512:
6
+ metadata.gz: 62b1a16559f5e48cdadbcdd3a7630c1b1c4aaabb97acf7337462f8a2760aa28aa8463fec341dd4a65459f78ea7b292e5faa116402d8717fc6ed04425e26531ce
7
+ data.tar.gz: 04bddf3ba5882d5f5d2d483f10148b61e6331fd75c478ca0c6c729bb3aec83b97094f7d4e26aa0da984de652f4ac140d16c787a6122751f7d12026041bc66f0b
data/LICENSE.txt ADDED
@@ -0,0 +1,17 @@
1
+ Copyright (c) 2024-2025 Ismo Kärkkäinen
2
+
3
+ The Universal Permissive License (UPL), Version 1.0
4
+
5
+ Subject to the condition set forth below, permission is hereby granted to any person obtaining a copy of this software, associated documentation and/or data (collectively the "Software"), free of charge and under any and all copyright rights in the Software, and any and all patent rights owned or freely licensable by each licensor hereunder covering either (i) the unmodified Software as contributed to or provided by such licensor, or (ii) the Larger Works (as defined below), to deal in both
6
+
7
+ (a) the Software, and
8
+
9
+ (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if one is included with the Software (each a "Larger Work" to which the Software is contributed by such licensors),
10
+
11
+ without restriction, including without limitation the rights to copy, create derivative works of, display, perform, and distribute the Software and make, use, sell, offer for sale, import, export, have made, and have sold the Software and the Larger Work(s), and to sublicense the foregoing rights on either these or other terms.
12
+
13
+ This license is subject to the following condition:
14
+
15
+ The above copyright notice and either this complete permission notice or at a minimum a reference to the UPL must be included in all copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,205 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Copyright © 2024-2025 Ismo Kärkkäinen
4
+ # Licensed under Universal Permissive License. See LICENSE.txt.
5
+
6
+ module OpenAPIArrangement
7
+ # Schema ordering.
8
+ module Schema
9
+ # Convenience methods to simplify using Orderer.
10
+ # All return a sorted array of Schema::Info instances.
11
+
12
+ # Arranges schemas in alphabetical order.
13
+ def self.alphabetical(doc, path = nil)
14
+ cands = path_candidates(path)
15
+ schemas, path = get_schemas(doc, cands)
16
+ return nil if schemas.nil?
17
+ ord = Orderer.new(path, schemas)
18
+ ord.sort!('@name')
19
+ end
20
+
21
+ # Arranges schemas to minimize forward declarations.
22
+ def self.dependencies_first(doc, path = nil)
23
+ cands = path_candidates(path)
24
+ schemas, path = get_schemas(doc, cands)
25
+ return nil if schemas.nil?
26
+ ord = Orderer.new(path, schemas)
27
+ ord.sort!
28
+ end
29
+
30
+ def self.path_candidates(path = nil)
31
+ if path.nil?
32
+ return {
33
+ '#/components/schemas/' => %w[components schemas],
34
+ '#/$defs/' => %w[$defs] # Supposing someone wants to use JSON schema doc.
35
+ }
36
+ end
37
+ pieces = path.split('/')
38
+ pieces.reject!(&:empty?)
39
+ pieces.shift if '#' == pieces.first
40
+ { path => pieces }
41
+ end
42
+ private_class_method :path_candidates
43
+
44
+ def self.get_schemas(doc, cands)
45
+ cands.each do |path, pieces|
46
+ schemas = doc.dig(*pieces)
47
+ return [ schemas, path ] unless schemas.nil?
48
+ end
49
+ [ nil, nil ]
50
+ end
51
+ private_class_method :get_schemas
52
+
53
+ # Schema, reference to it, name, and what it refers to.
54
+ class Info
55
+ attr_reader :ref, :schema, :direct_refs, :name, :unseen_refs
56
+
57
+ def initialize(ref, name, schema)
58
+ @ref = ref
59
+ @name = name
60
+ @schema = schema
61
+ @direct_refs = {}
62
+ self.class.gather_refs(@direct_refs, schema)
63
+ end
64
+
65
+ # Sets references that require forward declaration to be used.
66
+ def mark_as_seen(seen)
67
+ @unseen_refs = Set.new(@direct_refs.keys) - seen
68
+ end
69
+
70
+ def to_s
71
+ v = @direct_refs.keys.sort.map { |k| "#{k}:#{@direct_refs[k] ? 'req' : 'opt'}" }
72
+ "#{@ref}: #{v.join(' ')}"
73
+ end
74
+
75
+ # Adds all refs found in the array to refs with given required state.
76
+ def self.gather_array_refs(refs, items, required)
77
+ items.each do |s|
78
+ r = s['$ref']
79
+ next if r.nil?
80
+ refs[r] = required || refs.fetch(r, false)
81
+ end
82
+ end
83
+
84
+ # For any key '$ref' adds to refs whether referred type is required.
85
+ # Requires that there are no in-lined schemas, openapi-addschemas has been run.
86
+ def self.gather_refs(refs, schema)
87
+ # This implies types mixed together according to examples. Needs mixed type.
88
+ # AND. Also, mixing may fail. Adds a new schema, do in openapi-oftypes.
89
+ items = schema['allOf']
90
+ return gather_array_refs(refs, items, true) unless items.nil?
91
+ # As long as one schema is fulfilled, it is ok. OR, first that fits.
92
+ items = schema['anyOf'] if items.nil?
93
+ # oneOf implies selection between different types. No multiple matches. XOR.
94
+ # Needs to ensure that later types do not match.
95
+ # Should check if there is enough difference to ensure single match.
96
+ # Use separate program run after addschemas to create allOf mixed schema
97
+ # and verify the others can be dealt with.
98
+ items = schema['oneOf'] if items.nil?
99
+ return gather_array_refs(refs, items, false) unless items.nil?
100
+ # Defaults below handle it if "type" is not "object".
101
+ reqs = schema.fetch('required', [])
102
+ schema.fetch('properties', {}).each do |name, spec|
103
+ r = spec['$ref']
104
+ next if r.nil?
105
+ refs[r] = reqs.include?(name) || refs.fetch(r, false)
106
+ end
107
+ end
108
+ end
109
+
110
+ # Orders schemas according to given orderer.
111
+ # There is only one actual ordering method now.
112
+ class Orderer
113
+ attr_accessor :schemas, :order, :orderer
114
+
115
+ def initialize(path, schema_specs)
116
+ @schemas = {}
117
+ schema_specs.each do |name, schema|
118
+ r = "#{path}#{name}"
119
+ @schemas[r] = Info.new(r, name, schema)
120
+ end
121
+ end
122
+
123
+ def sort!(orderer = 'greedy_required_first')
124
+ @orderer = orderer
125
+ case orderer
126
+ when 'greedy_required_first' then @order = greedy_required_first
127
+ when '<=>' then @order = @schemas.values.sort { |a, b| a <=> b }
128
+ else
129
+ @order = @schemas.values.sort do |a, b|
130
+ va = self.class.var_or_method_value(a, orderer)
131
+ vb = self.class.var_or_method_value(b, orderer)
132
+ va <=> vb
133
+ end
134
+ end
135
+ seen = Set.new
136
+ @order.each do |si|
137
+ si.mark_as_seen(seen)
138
+ seen.add(si.name)
139
+ end
140
+ @order
141
+ end
142
+
143
+ def count_comparison(optfwd, manfwd, optrem, manrem, si, best)
144
+ # Fewer mandatory forwards is good because it leaves more room for implementation.
145
+ return true if manfwd < best[1]
146
+ if manfwd == best[1]
147
+ return true if manrem < best[3]
148
+ if manrem == best[3]
149
+ return true if optfwd < best[0]
150
+ if optfwd == best[0]
151
+ return true if optrem < best[2]
152
+ if optrem == best[2]
153
+ best_req_si = best.last.direct_refs.fetch(si.ref, false)
154
+ si_req_best = si.direct_refs.fetch(best.last.ref, false)
155
+ return nil if best_req_si == si_req_best
156
+ return !si_req_best
157
+ end
158
+ end
159
+ end
160
+ end
161
+ false
162
+ end
163
+
164
+ def greedy_required_first
165
+ chosen = []
166
+ until chosen.size == @schemas.size
167
+ used = Set.new(chosen.map(&:ref))
168
+ available = @schemas.values.reject { |si| used.member?(si.ref) }
169
+ best = nil
170
+ available.each do |si|
171
+ # Optional forwards from chosen.
172
+ optfwd = chosen.count { |x| !x.direct_refs.fetch(si.ref, false) && x.direct_refs.key?(si.ref) }
173
+ # Mandatory forwards from chosen.
174
+ manfwd = chosen.count { |x| x.direct_refs.fetch(si.ref, false) && x.direct_refs.key?(si.ref) }
175
+ # Optional and mandatory references from si.
176
+ opts = Set.new(si.direct_refs.keys.reject { |n| si.direct_refs[n] })
177
+ mans = Set.new(si.direct_refs.keys.select { |n| si.direct_refs[n] })
178
+ # Optional forwards to be added for si.
179
+ optrem = (opts - used).size
180
+ # Mandatory forwards to be added for si.
181
+ manrem = (mans - used).size
182
+ better = false
183
+ if best.nil?
184
+ better = true
185
+ else
186
+ better = count_comparison(optfwd, manfwd, optrem, manrem, si, best)
187
+ # Order by name if equally good otherwise.
188
+ better = si.name < best.last.name if better.nil?
189
+ end
190
+ best = [ optfwd, manfwd, optrem, manrem, si ] if better
191
+ end
192
+ chosen.push(best.last)
193
+ end
194
+ chosen
195
+ end
196
+
197
+ def self.var_or_method_value(x, name)
198
+ n = name.start_with?('@') ? name : "@#{name}"
199
+ return x.instance_variable_get(n) if x.instance_variable_defined?(n)
200
+ return x.public_send(name) if x.respond_to?(name)
201
+ raise ArgumentError, "#{name} is not #{x.class} instance variable nor public method"
202
+ end
203
+ end
204
+ end
205
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Copyright © 2025 Ismo Kärkkäinen
4
+ # Licensed under Universal Permissive License. See LICENSE.txt.
5
+
6
+ # Name and version.
7
+ module OpenAPIArrangement
8
+ NAME = 'openapi-arrangement'
9
+ VERSION = '0.1.0'
10
+
11
+ def self.info(separator = ': ')
12
+ "#{NAME}#{separator}#{VERSION}"
13
+ end
14
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Copyright © 2024-2025 Ismo Kärkkäinen
4
+ # Licensed under Universal Permissive License. See LICENSE.txt.
5
+
6
+ require_relative 'arrangement/schema'
7
+ require_relative 'arrangement/version'
metadata ADDED
@@ -0,0 +1,55 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: openapi-arrangement
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Ismo Kärkkäinen
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2025-01-21 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: |-
14
+ Code for arranging schemas in OpenAPI format specifications.
15
+
16
+ Intended to be used in gems that are invoked from openapi-generate tool from
17
+ openapi-sourcetools gem.
18
+
19
+ Provides functionality for ordering schemas:
20
+ - Based on mutual dependencies to minimize the need for forward declarations.
21
+ - Alphabetical order.
22
+ email: ismokarkkainen@icloud.com
23
+ executables: []
24
+ extensions: []
25
+ extra_rdoc_files: []
26
+ files:
27
+ - LICENSE.txt
28
+ - lib/openapi/arrangement.rb
29
+ - lib/openapi/arrangement/schema.rb
30
+ - lib/openapi/arrangement/version.rb
31
+ homepage: https://xn--ismo-krkkinen-gfbd.fi/openapi-arrangement/index.html
32
+ licenses:
33
+ - UPL-1.0
34
+ metadata:
35
+ rubygems_mfa_required: 'true'
36
+ post_install_message:
37
+ rdoc_options: []
38
+ require_paths:
39
+ - lib
40
+ required_ruby_version: !ruby/object:Gem::Requirement
41
+ requirements:
42
+ - - ">="
43
+ - !ruby/object:Gem::Version
44
+ version: 3.2.5
45
+ required_rubygems_version: !ruby/object:Gem::Requirement
46
+ requirements:
47
+ - - ">="
48
+ - !ruby/object:Gem::Version
49
+ version: '0'
50
+ requirements: []
51
+ rubygems_version: 3.4.19
52
+ signing_key:
53
+ specification_version: 4
54
+ summary: Schema arrangement code for OpenAPI specifications.
55
+ test_files: []