shipnotes 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.
Files changed (44) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +10 -0
  3. data/LICENSE.txt +21 -0
  4. data/README.md +265 -0
  5. data/app/controllers/shipnotes/releases_controller.rb +61 -0
  6. data/app/helpers/shipnotes/releases_helper.rb +38 -0
  7. data/app/views/layouts/shipnotes/application.html.erb +24 -0
  8. data/app/views/shipnotes/releases/index.atom.builder +20 -0
  9. data/app/views/shipnotes/releases/index.html.erb +51 -0
  10. data/config/routes.rb +7 -0
  11. data/exe/shipnotes +7 -0
  12. data/lib/shipnotes/check.rb +218 -0
  13. data/lib/shipnotes/cli.rb +312 -0
  14. data/lib/shipnotes/config.rb +278 -0
  15. data/lib/shipnotes/differs/json_schema.rb +45 -0
  16. data/lib/shipnotes/differs/mcp_tools.rb +50 -0
  17. data/lib/shipnotes/differs/openapi.rb +55 -0
  18. data/lib/shipnotes/differs.rb +33 -0
  19. data/lib/shipnotes/engine.rb +44 -0
  20. data/lib/shipnotes/engine_configuration.rb +21 -0
  21. data/lib/shipnotes/entry.rb +18 -0
  22. data/lib/shipnotes/entry_writer.rb +116 -0
  23. data/lib/shipnotes/field.rb +55 -0
  24. data/lib/shipnotes/finding.rb +7 -0
  25. data/lib/shipnotes/git_diff.rb +65 -0
  26. data/lib/shipnotes/github_labels.rb +28 -0
  27. data/lib/shipnotes/init.rb +69 -0
  28. data/lib/shipnotes/publication.rb +46 -0
  29. data/lib/shipnotes/release.rb +32 -0
  30. data/lib/shipnotes/releaser.rb +128 -0
  31. data/lib/shipnotes/renderer.rb +92 -0
  32. data/lib/shipnotes/repository.rb +100 -0
  33. data/lib/shipnotes/schema.rb +82 -0
  34. data/lib/shipnotes/semver.rb +83 -0
  35. data/lib/shipnotes/source.rb +47 -0
  36. data/lib/shipnotes/surface.rb +32 -0
  37. data/lib/shipnotes/templates/changelog.md.erb +11 -0
  38. data/lib/shipnotes/templates/release_notes.md.erb +1 -0
  39. data/lib/shipnotes/version.rb +5 -0
  40. data/lib/shipnotes/version_bump.rb +34 -0
  41. data/lib/shipnotes/version_targets.rb +70 -0
  42. data/lib/shipnotes/yaml_file.rb +22 -0
  43. data/lib/shipnotes.rb +52 -0
  44. metadata +91 -0
@@ -0,0 +1,278 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Shipnotes
4
+ class Config
5
+ Error = Class.new(Shipnotes::Error)
6
+ FILE = ".shipnotes.yml"
7
+ KEYS = %w[directory fields rules surfaces triggers check versioning render publication require].freeze
8
+ RESERVED_FIELDS = %w[id surfaces bump].freeze
9
+ BUMP_VALUES = %w[major minor patch none].freeze
10
+
11
+ Versioning = Data.define(:scheme, :release_id, :initial, :bump_field, :levels, :bump_surfaces, :files) do
12
+ def semver? = scheme == "semver"
13
+ def version_ids? = release_id == "version"
14
+ end
15
+ VersionFile = Data.define(:path, :pattern, :json) do
16
+ def label = json ? "#{path} (#{json.join('.')})" : path
17
+ end
18
+ Rule = Data.define(:when, :require, :reject, :message)
19
+ Render = Data.define(:output, :template, :title, :group_by, :headings, :details)
20
+ Publication = Data.define(:audience_field, :public_values, :flag_field)
21
+ CheckRules = Data.define(:require_entry, :ignore)
22
+
23
+ DEFAULTS = {
24
+ "directory" => "changelog",
25
+ "fields" => {
26
+ "title" => { "type" => "string", "required" => true, "description" => "One line that names the change" },
27
+ "kind" => { "type" => "enum", "required" => true, "values" => %w[added changed deprecated removed fixed security] },
28
+ "body" => { "type" => "text", "description" => "Details for the reader" }
29
+ },
30
+ "rules" => [],
31
+ "surfaces" => {},
32
+ "triggers" => [],
33
+ "check" => { "require_entry" => "auto", "ignore" => [] },
34
+ "versioning" => {
35
+ "scheme" => "semver",
36
+ "release_id" => "version",
37
+ "initial" => "0.0.0",
38
+ "bump" => {
39
+ "field" => "kind",
40
+ "levels" => { "removed" => "major", "added" => "minor", "changed" => "minor", "deprecated" => "minor",
41
+ "fixed" => "patch", "security" => "patch" }
42
+ },
43
+ "files" => []
44
+ },
45
+ "render" => { "output" => "CHANGELOG.md", "template" => nil, "title" => "Changelog", "group_by" => "kind",
46
+ "headings" => {}, "details" => [ "body" ] },
47
+ "publication" => { "audience_field" => nil, "public_values" => [ "public" ], "flag_field" => nil },
48
+ "require" => []
49
+ }.freeze
50
+
51
+ def self.load(root, path: nil)
52
+ root = File.expand_path(root.to_s)
53
+ path = File.expand_path(path || FILE, root)
54
+ data = File.exist?(path) ? YamlFile.parse(File.read(path)) : {}
55
+ raise Error, "#{FILE} must be a mapping" unless data.is_a?(Hash)
56
+
57
+ new(root: root, data: data)
58
+ rescue Psych::Exception => error
59
+ raise Error, "#{FILE} is not valid YAML: #{error.message}"
60
+ end
61
+
62
+ attr_reader :root, :directory, :fields, :rules, :surfaces, :triggers, :check, :versioning, :render, :publication, :requires
63
+
64
+ def initialize(root:, data: {})
65
+ @root = File.expand_path(root.to_s)
66
+ unknown = data.keys - KEYS
67
+ raise Error, "unknown keys in #{FILE}: #{unknown.join(', ')}" if unknown.any?
68
+
69
+ merged = merge(data)
70
+ @directory = string!(merged["directory"], "directory").delete_suffix("/")
71
+ @surfaces = build_surfaces(merged["surfaces"])
72
+ @fields = build_fields(merged["fields"])
73
+ @rules = build_rules(merged["rules"])
74
+ @triggers = build_triggers(merged["triggers"])
75
+ @check = build_check(merged["check"])
76
+ @versioning = build_versioning(merged["versioning"], explicit_bump: data.dig("versioning", "bump").is_a?(Hash))
77
+ @render = build_render(merged["render"], explicit_group: data["render"].is_a?(Hash) && data["render"].key?("group_by"))
78
+ @publication = build_publication(merged["publication"])
79
+ @requires = Array(merged["require"]).map { |item| string!(item, "require") }
80
+ end
81
+
82
+ def unreleased_dir = File.join(directory, "unreleased")
83
+ def releases_dir = File.join(directory, "releases")
84
+ def field(name) = fields[name.to_s]
85
+ def surface(key) = surfaces[key.to_s]
86
+ def surfaces? = surfaces.any?
87
+ def contract_surfaces = surfaces.values.select(&:contract)
88
+
89
+ private
90
+
91
+ def merge(data)
92
+ merged = DEFAULTS.merge(data)
93
+ %w[check versioning render publication].each do |key|
94
+ next unless data.key?(key)
95
+ raise Error, "#{key} must be a mapping" unless data[key].is_a?(Hash)
96
+
97
+ merged[key] = DEFAULTS[key].merge(data[key])
98
+ end
99
+ merged
100
+ end
101
+
102
+ def build_fields(data)
103
+ raise Error, "fields must be a mapping" unless data.is_a?(Hash) && data.any?
104
+
105
+ fields = data.to_h do |name, spec|
106
+ raise Error, "field #{name} is reserved" if RESERVED_FIELDS.include?(name)
107
+
108
+ [ name, build_field(name, spec) ]
109
+ end
110
+ if surfaces?
111
+ fields["surfaces"] = Field.new(name: "surfaces", type: "list", required: true, values: surfaces.keys, default: nil,
112
+ description: "Which surfaces the change touches")
113
+ end
114
+ fields["bump"] = Field.new(name: "bump", type: "enum", required: false, values: BUMP_VALUES, default: nil,
115
+ description: "Override the version bump")
116
+ fields
117
+ end
118
+
119
+ def build_field(name, spec)
120
+ raise Error, "field #{name} must be a mapping" unless spec.is_a?(Hash)
121
+ raise Error, "field #{name} has a bad name; use lowercase letters, digits and _" unless name.match?(/\A[a-z][a-z0-9_]*\z/)
122
+
123
+ unknown = spec.keys - %w[type required values default description]
124
+ raise Error, "field #{name} has unknown options: #{unknown.join(', ')}" if unknown.any?
125
+
126
+ type = spec.fetch("type", "string")
127
+ raise Error, "field #{name} type must be one of #{Field::TYPES.join(', ')}" unless Field::TYPES.include?(type)
128
+
129
+ values = Array(spec["values"]).map(&:to_s)
130
+ raise Error, "field #{name} is an enum and needs values" if type == "enum" && values.empty?
131
+
132
+ Field.new(name: name, type: type, required: spec["required"] == true, values: values,
133
+ default: spec["default"], description: spec["description"])
134
+ end
135
+
136
+ def build_rules(data)
137
+ raise Error, "rules must be a list" unless data.is_a?(Array)
138
+
139
+ data.each_with_index.map do |rule, index|
140
+ raise Error, "rules[#{index}] must be a mapping" unless rule.is_a?(Hash)
141
+
142
+ unknown = rule.keys - %w[when require reject message]
143
+ raise Error, "rules[#{index}] has unknown keys: #{unknown.join(', ')}" if unknown.any?
144
+
145
+ condition = rule.fetch("when", {})
146
+ reject = rule.fetch("reject", {})
147
+ raise Error, "rules[#{index}].when must be a mapping" unless condition.is_a?(Hash)
148
+ raise Error, "rules[#{index}].reject must be a mapping" unless reject.is_a?(Hash)
149
+
150
+ names = condition.keys + Array(rule["require"]) + reject.keys
151
+ missing = names.reject { |name| fields.key?(name) }
152
+ raise Error, "rules[#{index}] names unknown fields: #{missing.join(', ')}" if missing.any?
153
+
154
+ Rule.new(when: condition.transform_values { |value| Array(value).map(&:to_s) }, require: Array(rule["require"]),
155
+ reject: reject.transform_values { |value| Array(value).map(&:to_s) }, message: rule["message"])
156
+ end
157
+ end
158
+
159
+ def build_surfaces(data)
160
+ raise Error, "surfaces must be a mapping" unless data.is_a?(Hash)
161
+
162
+ data.to_h do |key, spec|
163
+ raise Error, "surface #{key} needs a lowercase slug key" unless key.match?(/\A[a-z0-9][a-z0-9_-]*\z/)
164
+ raise Error, "surface key all is reserved" if key == "all"
165
+
166
+ spec ||= {}
167
+ raise Error, "surface #{key} must be a mapping" unless spec.is_a?(Hash)
168
+
169
+ unknown = spec.keys - %w[title description paths exclude contract]
170
+ raise Error, "surface #{key} has unknown keys: #{unknown.join(', ')}" if unknown.any?
171
+
172
+ [ key, Surface.new(key: key, title: spec["title"] || key.tr("_-", " ").capitalize, description: spec["description"],
173
+ paths: Array(spec["paths"]), exclude: Array(spec["exclude"]), contract: build_contract(key, spec["contract"])) ]
174
+ end
175
+ end
176
+
177
+ def build_contract(key, spec)
178
+ return nil if spec.nil?
179
+ raise Error, "surface #{key} contract needs file and differ" unless spec.is_a?(Hash) && spec["file"] && spec["differ"]
180
+
181
+ Surface::Contract.new(file: spec["file"].to_s, differ: spec["differ"].to_s)
182
+ end
183
+
184
+ def build_triggers(data)
185
+ raise Error, "triggers must be a list" unless data.is_a?(Array)
186
+
187
+ data.each_with_index.map do |trigger, index|
188
+ raise Error, "triggers[#{index}] needs a pattern" unless trigger.is_a?(Hash) && trigger["pattern"]
189
+
190
+ surface = trigger["surface"]
191
+ raise Error, "triggers[#{index}] names unknown surface #{surface}" if surface && !surfaces.key?(surface)
192
+
193
+ Trigger.new(name: trigger["name"] || "trigger #{index + 1}", pattern: regexp!(trigger["pattern"], "triggers[#{index}].pattern"),
194
+ paths: Array(trigger["paths"]), surface: surface)
195
+ end
196
+ end
197
+
198
+ def build_check(data)
199
+ mode = data["require_entry"]
200
+ raise Error, "check.require_entry must be auto, always or surfaces" unless %w[auto always surfaces].include?(mode)
201
+ raise Error, "check.require_entry is surfaces, but no surfaces are configured" if mode == "surfaces" && surfaces.empty?
202
+
203
+ mode = surfaces.any? ? "surfaces" : "always" if mode == "auto"
204
+ CheckRules.new(require_entry: mode, ignore: Array(data["ignore"]).map(&:to_s))
205
+ end
206
+
207
+ # The defaults point the bump and the grouping at `kind`. A project whose
208
+ # own fields have no `kind` keeps working: only an explicit setting that
209
+ # names a missing field is an error.
210
+ def build_versioning(data, explicit_bump:)
211
+ scheme = data["scheme"]
212
+ release_id = data["release_id"]
213
+ raise Error, "versioning.scheme must be semver or none" unless %w[semver none].include?(scheme)
214
+ raise Error, "versioning.release_id must be version or date" unless %w[version date].include?(release_id)
215
+ raise Error, "versioning.release_id must be date when scheme is none" if scheme == "none" && release_id == "version"
216
+ raise Error, "versioning.initial must be a MAJOR.MINOR.PATCH version" unless Semver.valid?(data["initial"])
217
+
218
+ bump = data["bump"] || {}
219
+ levels = (bump["levels"] || {}).transform_values(&:to_s)
220
+ bad = levels.values - Semver::LEVELS.map(&:to_s) - [ "none" ]
221
+ raise Error, "versioning.bump.levels must map values to major, minor, patch or none" if bad.any?
222
+
223
+ bump_field = bump["field"]
224
+ bump_field = nil if !explicit_bump && !fields.key?(bump_field)
225
+ raise Error, "versioning.bump.field names unknown field #{bump_field}" if bump_field && !fields.key?(bump_field)
226
+
227
+ bump_surfaces = bump["surfaces"] && Array(bump["surfaces"])
228
+ unknown = Array(bump_surfaces) - surfaces.keys
229
+ raise Error, "versioning.bump.surfaces names unknown surfaces: #{unknown.join(', ')}" if unknown.any?
230
+
231
+ Versioning.new(scheme: scheme, release_id: release_id, initial: data["initial"], bump_field: bump_field,
232
+ levels: levels, bump_surfaces: bump_surfaces, files: Array(data["files"]).each_with_index.map { |spec, index| build_version_file(spec, index) })
233
+ end
234
+
235
+ def build_version_file(spec, index)
236
+ raise Error, "versioning.files[#{index}] needs a path" unless spec.is_a?(Hash) && spec["path"]
237
+ raise Error, "versioning.files[#{index}] needs exactly one of pattern or json" unless spec.key?("pattern") ^ spec.key?("json")
238
+
239
+ pattern = spec["pattern"] && regexp!(spec["pattern"], "versioning.files[#{index}].pattern")
240
+ if pattern && !pattern.names.include?("version") && pattern.source !~ /\((?!\?)/
241
+ raise Error, "versioning.files[#{index}].pattern needs a (?<version>...) group"
242
+ end
243
+
244
+ VersionFile.new(path: spec["path"].to_s, pattern: pattern, json: spec["json"]&.to_s&.split("."))
245
+ end
246
+
247
+ def build_render(data, explicit_group:)
248
+ group_by = data["group_by"]
249
+ group_by = nil if !explicit_group && !fields.key?(group_by)
250
+ raise Error, "render.group_by names unknown field #{group_by}" if group_by && !fields.key?(group_by)
251
+
252
+ details = Array(data["details"]).select { |name| fields.key?(name) }
253
+ Render.new(output: data["output"], template: data["template"], title: data["title"].to_s, group_by: group_by,
254
+ headings: (data["headings"] || {}).transform_keys(&:to_s), details: details)
255
+ end
256
+
257
+ def build_publication(data)
258
+ audience = data["audience_field"]
259
+ flag = data["flag_field"]
260
+ raise Error, "publication.audience_field names unknown field #{audience}" if audience && !fields.key?(audience)
261
+ raise Error, "publication.flag_field names unknown field #{flag}" if flag && !fields.key?(flag)
262
+
263
+ Publication.new(audience_field: audience, public_values: Array(data["public_values"]).map(&:to_s), flag_field: flag)
264
+ end
265
+
266
+ def regexp!(source, label)
267
+ Regexp.new(source.to_s)
268
+ rescue RegexpError => error
269
+ raise Error, "#{label} is not a valid regular expression: #{error.message}"
270
+ end
271
+
272
+ def string!(value, label)
273
+ raise Error, "#{label} must be a string" unless value.is_a?(String) && !value.strip.empty?
274
+
275
+ value
276
+ end
277
+ end
278
+ end
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Shipnotes
4
+ module Differs
5
+ # Compares two JSON Schemas from a caller's side. An input schema breaks
6
+ # when a call that was valid becomes invalid; an output schema breaks when
7
+ # a field a caller reads disappears or changes type.
8
+ module JsonSchema
9
+ module_function
10
+
11
+ def call(subject, old, new, input:, path:, internal: false)
12
+ old ||= {}
13
+ new ||= {}
14
+ findings = []
15
+ add = ->(breaking, message) { findings << Finding.new(subject: subject, breaking: breaking, internal: internal, message: message) }
16
+ # An output with no declared type promised nothing, so declaring one breaks no caller.
17
+ if old["type"] != new["type"] && (input || old.key?("type"))
18
+ add.call(true, "#{path} type changed from #{old['type'].inspect} to #{new['type'].inspect}")
19
+ end
20
+ if input
21
+ (Array(new["required"]) - Array(old["required"])).each { |name| add.call(true, "#{path}.#{name} is now required") }
22
+ (Array(old["enum"]) - Array(new["enum"])).each { |value| add.call(true, "#{path} no longer accepts #{value.inspect}") } if old["enum"]
23
+ add.call(true, "#{path} now restricts values to an enum") if new["enum"] && !old["enum"]
24
+ else
25
+ (Array(old["required"]) - Array(new["required"])).each { |name| add.call(true, "#{path}.#{name} is no longer always present") }
26
+ (Array(new["enum"]) - Array(old["enum"])).each { |value| add.call(true, "#{path} may return #{value.inspect}") } if old["enum"]
27
+ end
28
+ old_properties = old["properties"] || {}
29
+ new_properties = new["properties"] || {}
30
+ (old_properties.keys - new_properties.keys).each { |name| add.call(true, "#{path}.#{name} removed") }
31
+ (new_properties.keys - old_properties.keys).each do |name|
32
+ add.call(false, "#{path}.#{name} added") unless input && Array(new["required"]).include?(name)
33
+ end
34
+ (old_properties.keys & new_properties.keys).each do |name|
35
+ findings.concat(call(subject, old_properties[name], new_properties[name], input: input, path: "#{path}.#{name}", internal: internal))
36
+ end
37
+ if old["items"].is_a?(Hash) || new["items"].is_a?(Hash)
38
+ findings.concat(call(subject, old["items"], new["items"], input: input, path: "#{path}[]", internal: internal))
39
+ end
40
+ add.call(false, "#{path} documentation changed") if findings.empty? && old != new
41
+ findings
42
+ end
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Shipnotes
4
+ module Differs
5
+ # Reads the MCP `tools/list` shape: {"tools": [{name, inputSchema, outputSchema, ...}]}
6
+ # or a bare list of tools.
7
+ module McpTools
8
+ DOCUMENTATION = %w[title description annotations].freeze
9
+
10
+ module_function
11
+
12
+ def call(base, head, _options = {})
13
+ base_tools = index(parse(base, "base"))
14
+ head_tools = index(parse(head, "head"))
15
+ findings = []
16
+ (base_tools.keys - head_tools.keys).each { |name| findings << finding(name, true, "tool removed") }
17
+ (head_tools.keys - base_tools.keys).each { |name| findings << finding(name, false, "tool added") }
18
+ (base_tools.keys & head_tools.keys).each { |name| findings.concat(tool_findings(name, base_tools[name], head_tools[name])) }
19
+ findings.sort_by { |item| [ item.breaking ? 0 : 1, item.subject, item.message ] }
20
+ end
21
+
22
+ def parse(text, side)
23
+ JSON.parse(text)
24
+ rescue JSON::ParserError => error
25
+ raise Error, "the #{side} MCP tool catalog is not valid JSON: #{error.message}"
26
+ end
27
+
28
+ def index(catalog)
29
+ tools = catalog.is_a?(Hash) ? catalog.fetch("tools", []) : catalog
30
+ raise Error, "an MCP tool catalog must be a list of tools or {\"tools\": [...]}" unless tools.is_a?(Array)
31
+
32
+ tools.to_h do |tool|
33
+ raise Error, "every MCP tool needs a name: #{tool.inspect[0, 80]}" unless tool.is_a?(Hash) && tool["name"].is_a?(String)
34
+
35
+ [ tool["name"], tool ]
36
+ end
37
+ end
38
+
39
+ def tool_findings(name, old, new)
40
+ findings = JsonSchema.call(name, old["inputSchema"], new["inputSchema"], input: true, path: "input") +
41
+ JsonSchema.call(name, old["outputSchema"], new["outputSchema"], input: false, path: "output")
42
+ changed = DOCUMENTATION.select { |key| old[key] != new[key] }
43
+ findings << finding(name, false, "#{changed.join(', ')} changed") if changed.any?
44
+ findings
45
+ end
46
+
47
+ def finding(name, breaking, message) = Finding.new(subject: name, breaking: breaking, internal: false, message: message)
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "tmpdir"
4
+
5
+ module Shipnotes
6
+ module Differs
7
+ # Runs oasdiff (https://github.com/oasdiff/oasdiff). Operations marked
8
+ # `x-internal: true` are still reported, labelled internal.
9
+ module Openapi
10
+ module_function
11
+
12
+ def call(base, head, options = {})
13
+ oasdiff = options[:oasdiff] || ENV["OASDIFF"] || executable("oasdiff")
14
+ raise Skipped, "oasdiff not found (install it, set OASDIFF or pass --oasdiff)" unless oasdiff
15
+
16
+ Dir.mktmpdir("shipnotes-oasdiff") do |dir|
17
+ File.write(File.join(dir, "base.json"), base)
18
+ File.write(File.join(dir, "head.json"), head)
19
+ output, error, status = begin
20
+ Open3.capture3(oasdiff, "breaking", "base.json", "head.json", "--format", "json", chdir: dir)
21
+ rescue SystemCallError => failure
22
+ raise Error, "oasdiff could not run (#{oasdiff}): #{failure.message}"
23
+ end
24
+ raise Error, "oasdiff failed: #{error.strip}" unless status.success?
25
+
26
+ internal = internal_operation_ids(base) | internal_operation_ids(head)
27
+ JSON.parse(output.strip.empty? ? "[]" : output).map do |item|
28
+ Finding.new(subject: "#{item['operation']} #{item['path']}", breaking: item["level"].to_i >= 3,
29
+ internal: internal.include?(item["operationId"]), message: item["text"].to_s)
30
+ end
31
+ end
32
+ end
33
+
34
+ def internal_operation_ids(text)
35
+ document = begin
36
+ JSON.parse(text)
37
+ rescue JSON::ParserError
38
+ YAML.safe_load(text)
39
+ end
40
+ return [] unless document.is_a?(Hash)
41
+
42
+ document.fetch("paths", {}).values.flat_map { |item| item.is_a?(Hash) ? item.values : [] }
43
+ .select { |operation| operation.is_a?(Hash) && operation["x-internal"] }
44
+ .map { |operation| operation["operationId"] }
45
+ rescue Psych::Exception
46
+ []
47
+ end
48
+
49
+ def executable(name)
50
+ ENV.fetch("PATH", "").split(File::PATH_SEPARATOR).map { |dir| File.join(dir, name) }
51
+ .find { |path| File.file?(path) && File.executable?(path) }
52
+ end
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Shipnotes
4
+ # A differ compares two versions of a contract file. It responds to
5
+ # `call(base_text, head_text, options)` and returns Shipnotes::Finding values;
6
+ # it raises Differs::Skipped when it cannot run here.
7
+ module Differs
8
+ Skipped = Class.new(Shipnotes::Error)
9
+ BUILT_IN = { "openapi" => Openapi, "mcp_tools" => McpTools }.freeze
10
+
11
+ module_function
12
+
13
+ def resolve(name, config)
14
+ return BUILT_IN.fetch(name) if BUILT_IN.key?(name)
15
+
16
+ config.requires.each do |path|
17
+ require File.expand_path(path, config.root)
18
+ rescue ScriptError, StandardError => error
19
+ raise Error, "could not load #{path} from `require`: #{error.class}: #{error.message}"
20
+ end
21
+ differ = lookup(name)
22
+ raise Error, "differ #{name} must respond to call(base, head, options)" unless differ.respond_to?(:call)
23
+
24
+ differ
25
+ end
26
+
27
+ def lookup(name)
28
+ Object.const_get(name)
29
+ rescue NameError
30
+ raise Error, "unknown differ #{name}; use #{BUILT_IN.keys.join(' or ')}, or a class loaded through `require`"
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "shipnotes"
4
+
5
+ module Shipnotes
6
+ class Engine < ::Rails::Engine
7
+ isolate_namespace Shipnotes
8
+
9
+ class << self
10
+ # The project's .shipnotes.yml, read once when caching is on (the
11
+ # default wherever the app eager-loads, so production reads it once).
12
+ def project_config
13
+ settings = Shipnotes.configuration
14
+ return load_project_config(settings) unless cache?(settings)
15
+
16
+ @project_config_mutex.synchronize { @project_config ||= load_project_config(settings) }
17
+ end
18
+
19
+ def publication(config = project_config)
20
+ settings = Shipnotes.configuration
21
+ return Publication.new(config, flag_enabled: settings.flag_enabled) unless cache?(settings)
22
+
23
+ @project_config_mutex.synchronize do
24
+ @repository ||= Repository.new(config).tap { |repository| repository.releases && repository.entries }
25
+ end
26
+ Publication.new(config, repository: @repository, flag_enabled: settings.flag_enabled)
27
+ end
28
+
29
+ def reset!
30
+ @project_config_mutex.synchronize { @project_config = @repository = nil }
31
+ end
32
+
33
+ private
34
+
35
+ def cache?(settings) = settings.cache.nil? ? ::Rails.application.config.eager_load : settings.cache
36
+
37
+ def load_project_config(settings)
38
+ Config.load(settings.root || ::Rails.root, path: settings.config_path)
39
+ end
40
+ end
41
+
42
+ @project_config_mutex = Mutex.new
43
+ end
44
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Shipnotes
4
+ # Settings for the Rails engine. Set them in an initializer with
5
+ # `Shipnotes.configure { |config| ... }`.
6
+ class EngineConfiguration
7
+ attr_accessor :root, :config_path, :title, :description, :per_page, :layout, :parent_controller, :flag_enabled, :cache
8
+
9
+ def initialize
10
+ @root = nil
11
+ @config_path = nil
12
+ @title = "Changelog"
13
+ @description = nil
14
+ @per_page = 10
15
+ @layout = "shipnotes/application"
16
+ @parent_controller = "ActionController::Base"
17
+ @flag_enabled = nil
18
+ @cache = nil
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Shipnotes
4
+ Entry = Data.define(:id, :data)
5
+
6
+ class Entry
7
+ SLUG = /\A[a-z0-9][a-z0-9-]*\z/
8
+
9
+ def self.from_h(hash)
10
+ new(id: hash.fetch("id").to_s, data: hash.except("id"))
11
+ end
12
+
13
+ def [](name) = data[name.to_s]
14
+ def title = data["title"].to_s
15
+ def surfaces = Array(data["surfaces"])
16
+ def to_h = { "id" => id }.merge(data)
17
+ end
18
+ end
@@ -0,0 +1,116 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Shipnotes
4
+ # Creates one unreleased entry. On a terminal it asks for each field the
5
+ # flags left out; elsewhere it fails with the flags it still needs.
6
+ class EntryWriter
7
+ Error = Class.new(Shipnotes::Error)
8
+ MAX_SLUG = 60
9
+
10
+ def initialize(config, input: $stdin, output: $stdout, interactive: input.respond_to?(:tty?) && input.tty?)
11
+ @config = config
12
+ @input = input
13
+ @output = output
14
+ @interactive = interactive
15
+ end
16
+
17
+ def call(values: {}, slug: nil)
18
+ data = collect(values.transform_keys(&:to_s))
19
+ errors = Schema.new(@config).entry_errors(data)
20
+ raise Error, "the entry is not valid:\n#{errors.map { |error| " #{error}" }.join("\n")}" if errors.any?
21
+
22
+ slug = slug ? check_slug(slug) : unique_slug(slugify(data["title"].to_s))
23
+ relative = File.join(@config.unreleased_dir, "#{slug}.yml")
24
+ path = File.join(@config.root, relative)
25
+ raise Error, "#{relative} already exists" if File.exist?(path)
26
+
27
+ FileUtils.mkdir_p(File.dirname(path))
28
+ File.write(path, YamlFile.dump(data))
29
+ relative
30
+ end
31
+
32
+ def slugify(text)
33
+ slug = text.downcase.gsub(/[^a-z0-9]+/, "-").gsub(/\A-+|-+\z/, "")[0, MAX_SLUG].to_s.sub(/-+\z/, "")
34
+ slug.empty? ? "change" : slug
35
+ end
36
+
37
+ private
38
+
39
+ def collect(values)
40
+ unknown = values.keys - @config.fields.keys
41
+ raise Error, "unknown fields: #{unknown.join(', ')}" if unknown.any?
42
+
43
+ data = {}
44
+ missing = []
45
+ @config.fields.each_value do |field|
46
+ raw = values[field.name]
47
+ value = if raw.is_a?(String)
48
+ field.coerce(raw)
49
+ elsif !raw.nil?
50
+ raw
51
+ elsif @interactive && field.name != "bump"
52
+ ask(field)
53
+ else
54
+ field.default
55
+ end
56
+ if Field.blank?(value)
57
+ missing << field if field.required
58
+ else
59
+ data[field.name] = value
60
+ end
61
+ end
62
+ return data if missing.empty?
63
+
64
+ flags = missing.map { |field| "--#{field.name.tr('_', '-')} #{placeholder(field)}" }
65
+ raise Error, "missing required fields: #{missing.map(&:name).join(', ')}\n pass #{flags.join(' ')}"
66
+ end
67
+
68
+ def ask(field)
69
+ label = field.description ? "#{field.name} (#{field.description})" : field.name
70
+ label += " [#{field.values.join(', ')}]" if field.values.any?
71
+ label += " (comma separated)" if field.type == "list"
72
+ label += " (optional)" unless field.required
73
+ label += " [#{field.default}]" if field.default
74
+ loop do
75
+ @output.print("#{label}: ")
76
+ line = @input.gets
77
+ return field.default if line.nil?
78
+
79
+ text = line.strip
80
+ return field.default if text.empty? && !field.required
81
+ next @output.puts(" #{field.name} is required") if text.empty?
82
+
83
+ text = field.values[text.to_i - 1] if field.type == "enum" && text.match?(/\A\d+\z/) && text.to_i.between?(1, field.values.size)
84
+ value = field.coerce(text)
85
+ errors = field.errors(value)
86
+ return value if errors.empty?
87
+
88
+ @output.puts(" #{errors.join('; ')}")
89
+ end
90
+ end
91
+
92
+ def placeholder(field)
93
+ case field.type
94
+ when "enum" then field.values.join("|")
95
+ when "list" then field.values.any? ? field.values.join(",") : "a,b"
96
+ when "date" then "YYYY-MM-DD"
97
+ when "boolean" then "true|false"
98
+ else "TEXT"
99
+ end
100
+ end
101
+
102
+ def check_slug(slug)
103
+ raise Error, "slug #{slug.inspect} must be lowercase letters, digits and -" unless slug.match?(Entry::SLUG)
104
+
105
+ slug
106
+ end
107
+
108
+ def unique_slug(base)
109
+ taken = Repository.new(@config).then { |repository| repository.entries.map(&:id) + repository.released_entries.keys }
110
+ taken += Dir.glob(File.join(@config.root, @config.unreleased_dir, "*.yml")).map { |path| File.basename(path, ".yml") }
111
+ return base unless taken.include?(base)
112
+
113
+ (2..).lazy.map { |number| "#{base}-#{number}" }.find { |candidate| !taken.include?(candidate) }
114
+ end
115
+ end
116
+ end