nukadoko 0.1.0 → 0.3.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 (159) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +417 -0
  3. data/README.ja.md +62 -7
  4. data/README.md +19 -5
  5. data/exe/nuka +8 -0
  6. data/lib/nukadoko/aria_snapshot.rb +1008 -0
  7. data/lib/nukadoko/aria_tree.rb +150 -0
  8. data/lib/nukadoko/base.rb +294 -0
  9. data/lib/nukadoko/check.rb +669 -22
  10. data/lib/nukadoko/claim_check.rb +177 -0
  11. data/lib/nukadoko/claim_check_run.rb +293 -0
  12. data/lib/nukadoko/claim_line.rb +381 -0
  13. data/lib/nukadoko/claim_rules.rb +519 -0
  14. data/lib/nukadoko/claim_sides.rb +469 -0
  15. data/lib/nukadoko/claims.rb +576 -37
  16. data/lib/nukadoko/cli.rb +814 -22
  17. data/lib/nukadoko/codes.json +947 -0
  18. data/lib/nukadoko/codes.rb +19 -0
  19. data/lib/nukadoko/command.rb +214 -12
  20. data/lib/nukadoko/criteria.rb +172 -0
  21. data/lib/nukadoko/definition.rb +33 -41
  22. data/lib/nukadoko/env_check.rb +88 -0
  23. data/lib/nukadoko/features.rb +80 -10
  24. data/lib/nukadoko/fixtures.rb +329 -11
  25. data/lib/nukadoko/http_recording.rb +68 -0
  26. data/lib/nukadoko/init.rb +129 -0
  27. data/lib/nukadoko/js_json.rb +274 -0
  28. data/lib/nukadoko/js_pattern.rb +531 -0
  29. data/lib/nukadoko/judge.rb +221 -0
  30. data/lib/nukadoko/judgment_file.rb +78 -0
  31. data/lib/nukadoko/judgments.rb +256 -0
  32. data/lib/nukadoko/literal.rb +129 -0
  33. data/lib/nukadoko/measured.rb +105 -0
  34. data/lib/nukadoko/order.rb +84 -0
  35. data/lib/nukadoko/parts.rb +43 -22
  36. data/lib/nukadoko/pattern.rb +73 -3
  37. data/lib/nukadoko/poll.rb +21 -8
  38. data/lib/nukadoko/program.rb +105 -17
  39. data/lib/nukadoko/project_files.rb +17 -0
  40. data/lib/nukadoko/project_fixtures.rb +17 -2
  41. data/lib/nukadoko/project_program.rb +119 -0
  42. data/lib/nukadoko/report_allure.rb +751 -0
  43. data/lib/nukadoko/report_messages.rb +167 -0
  44. data/lib/nukadoko/report_run.rb +169 -0
  45. data/lib/nukadoko/run.rb +898 -91
  46. data/lib/nukadoko/run_record.rb +535 -0
  47. data/lib/nukadoko/scaffold.rb +1015 -0
  48. data/lib/nukadoko/schema.rb +120 -21
  49. data/lib/nukadoko/secrets.rb +375 -0
  50. data/lib/nukadoko/selection.rb +163 -0
  51. data/lib/nukadoko/signature.rb +4 -1
  52. data/lib/nukadoko/skill.rb +36 -0
  53. data/lib/nukadoko/spaces.rb +28 -0
  54. data/lib/nukadoko/step.rb +68 -21
  55. data/lib/nukadoko/summary.rb +662 -0
  56. data/lib/nukadoko/table.rb +34 -2
  57. data/lib/nukadoko/text_fit.rb +179 -0
  58. data/lib/nukadoko/trace.rb +244 -0
  59. data/lib/nukadoko/trace_actions.rb +116 -0
  60. data/lib/nukadoko/tree_passes.rb +122 -0
  61. data/lib/nukadoko/verdict.rb +128 -0
  62. data/lib/nukadoko/version.rb +2 -1
  63. data/lib/nukadoko/vocabulary.rb +6 -0
  64. data/lib/nukadoko/walk.rb +305 -0
  65. data/lib/nukadoko/walk_files.rb +473 -0
  66. data/lib/nukadoko/walk_step.rb +149 -0
  67. data/lib/nukadoko.rb +60 -2
  68. data/llms.txt +297 -0
  69. data/sig/generated/nukadoko/aria_snapshot.rbs +331 -0
  70. data/sig/generated/nukadoko/aria_tree.rbs +142 -0
  71. data/sig/generated/nukadoko/base.rbs +142 -0
  72. data/sig/generated/nukadoko/check.rbs +255 -0
  73. data/sig/generated/nukadoko/claim_check.rbs +118 -0
  74. data/sig/generated/nukadoko/claim_check_run.rbs +88 -0
  75. data/sig/generated/nukadoko/claim_line.rbs +158 -0
  76. data/sig/generated/nukadoko/claim_rules.rbs +172 -0
  77. data/sig/generated/nukadoko/claim_sides.rbs +207 -0
  78. data/sig/generated/nukadoko/claims.rbs +208 -0
  79. data/sig/generated/nukadoko/cli.rbs +182 -0
  80. data/sig/generated/nukadoko/codes.rbs +16 -0
  81. data/sig/generated/nukadoko/command.rbs +109 -0
  82. data/sig/generated/nukadoko/criteria.rbs +83 -0
  83. data/sig/generated/nukadoko/definition.rbs +30 -0
  84. data/sig/generated/nukadoko/env_check.rbs +34 -0
  85. data/sig/generated/nukadoko/features.rbs +101 -0
  86. data/sig/generated/nukadoko/fixtures.rbs +175 -0
  87. data/sig/generated/nukadoko/http_recording.rbs +29 -0
  88. data/sig/generated/nukadoko/init.rbs +64 -0
  89. data/sig/generated/nukadoko/js_json.rbs +109 -0
  90. data/sig/generated/nukadoko/js_pattern.rbs +194 -0
  91. data/sig/generated/nukadoko/judge.rbs +64 -0
  92. data/sig/generated/nukadoko/judgment_file.rbs +39 -0
  93. data/sig/generated/nukadoko/judgments.rbs +120 -0
  94. data/sig/generated/nukadoko/literal.rbs +71 -0
  95. data/sig/generated/nukadoko/measured.rbs +42 -0
  96. data/sig/generated/nukadoko/order.rbs +54 -0
  97. data/sig/generated/nukadoko/parts.rbs +35 -0
  98. data/sig/generated/nukadoko/pattern.rbs +62 -0
  99. data/sig/generated/nukadoko/poll.rbs +41 -0
  100. data/sig/generated/nukadoko/program.rbs +101 -0
  101. data/sig/generated/nukadoko/project_files.rbs +19 -0
  102. data/sig/generated/nukadoko/project_fixtures.rbs +57 -0
  103. data/sig/generated/nukadoko/project_program.rbs +55 -0
  104. data/sig/generated/nukadoko/report_allure.rbs +268 -0
  105. data/sig/generated/nukadoko/report_messages.rbs +68 -0
  106. data/sig/generated/nukadoko/report_run.rbs +102 -0
  107. data/sig/generated/nukadoko/run.rbs +264 -0
  108. data/sig/generated/nukadoko/run_record.rbs +175 -0
  109. data/sig/generated/nukadoko/scaffold.rbs +328 -0
  110. data/sig/generated/nukadoko/schema.rbs +155 -0
  111. data/sig/generated/nukadoko/secrets.rbs +172 -0
  112. data/sig/generated/nukadoko/selection.rbs +73 -0
  113. data/sig/generated/nukadoko/signature.rbs +17 -0
  114. data/sig/generated/nukadoko/skill.rbs +20 -0
  115. data/sig/generated/nukadoko/spaces.rbs +31 -0
  116. data/sig/generated/nukadoko/step.rbs +115 -0
  117. data/sig/generated/nukadoko/summary.rbs +204 -0
  118. data/sig/generated/nukadoko/table.rbs +43 -0
  119. data/sig/generated/nukadoko/text_fit.rbs +70 -0
  120. data/sig/generated/nukadoko/trace.rbs +127 -0
  121. data/sig/generated/nukadoko/trace_actions.rbs +40 -0
  122. data/sig/generated/nukadoko/tree_passes.rbs +48 -0
  123. data/sig/generated/nukadoko/verdict.rbs +56 -0
  124. data/sig/generated/nukadoko/version.rbs +5 -0
  125. data/sig/generated/nukadoko/vocabulary.rbs +25 -0
  126. data/sig/generated/nukadoko/walk.rbs +139 -0
  127. data/sig/generated/nukadoko/walk_files.rbs +189 -0
  128. data/sig/generated/nukadoko/walk_step.rbs +50 -0
  129. data/sig/generated/nukadoko.rbs +26 -0
  130. data/sig/nukadoko.rbs +5 -48
  131. data/skills/nukadoko/SKILL.md +120 -0
  132. data/skills/nukadoko/references/checking-steps.md +200 -0
  133. data/skills/nukadoko/references/diagnosing.md +200 -0
  134. data/skills/nukadoko/references/done.md +99 -0
  135. data/skills/nukadoko/references/evidence.md +124 -0
  136. data/skills/nukadoko/references/examples/cli.md +230 -0
  137. data/skills/nukadoko/references/examples/http-api.md +342 -0
  138. data/skills/nukadoko/references/examples/workflow.md +173 -0
  139. data/skills/nukadoko/references/exploring.md +184 -0
  140. data/skills/nukadoko/references/fixtures.md +198 -0
  141. data/skills/nukadoko/references/from-prose.md +51 -0
  142. data/skills/nukadoko/references/judgments.md +95 -0
  143. data/skills/nukadoko/references/maintenance.md +97 -0
  144. data/skills/nukadoko/references/merge-risk.md +74 -0
  145. data/skills/nukadoko/references/parts.md +152 -0
  146. data/skills/nukadoko/references/perturbed-worlds.md +109 -0
  147. data/skills/nukadoko/references/program.md +200 -0
  148. data/skills/nukadoko/references/reviewing.md +200 -0
  149. data/skills/nukadoko/references/running.md +200 -0
  150. data/skills/nukadoko/references/scenario-rules.md +188 -0
  151. data/skills/nukadoko/references/states.md +66 -0
  152. data/skills/nukadoko/references/step-files.md +200 -0
  153. data/skills/nukadoko/references/verdicts.md +200 -0
  154. data/skills/nukadoko/references/writing-steps.md +200 -0
  155. data/skills/nukadoko/references/writing-the-feature.md +165 -0
  156. data/skills/nukadoko/scripts/claude-code-verdict-hook.mjs +99 -0
  157. data/skills/nukadoko/scripts/merge-risk.jq +56 -0
  158. data/skills/nukadoko-verification/SKILL.md +263 -0
  159. metadata +133 -1
@@ -1,4 +1,5 @@
1
1
  # frozen_string_literal: true
2
+ # rbs_inline: enabled
2
3
 
3
4
  # One declaration of a step's args or returns gives three things: the check
4
5
  # a value must pass at run time, the RBS a Steep user checks the step body
@@ -6,67 +7,99 @@
6
7
  # scalar, `[:array, type]` for a list, or a nested Schema for an object.
7
8
  module Nukadoko
8
9
  class Schema
9
- Field = Data.define(:name, :type, :description)
10
+ Field = Data.define(
11
+ :name, #: Symbol
12
+ :type, #: untyped
13
+ :description, #: String?
14
+ )
10
15
 
16
+ #: () ?{ () [self: Schema] -> void } -> Schema
11
17
  def self.build(&block)
12
18
  schema = new
13
- schema.instance_eval(&block) if block
19
+ schema.instance_exec(&block) if block
14
20
  schema
15
21
  end
16
22
 
17
- attr_reader :fields
23
+ attr_reader :fields #: Array[Field]
18
24
 
25
+ #: (?Array[Field]) -> void
19
26
  def initialize(fields = [])
20
27
  @fields = fields
21
28
  end
22
29
 
23
30
  # `null: true` lets the value be nil as well, as zod's `.nullable()` does.
31
+ #: (Symbol, ?String?, ?null: bool) -> void
24
32
  def string(name, description = nil, null: false) = add(name, :string, description, null)
33
+ #: (Symbol, ?String?, ?null: bool) -> void
25
34
  def boolean(name, description = nil, null: false) = add(name, :boolean, description, null)
35
+ #: (Symbol, ?String?, ?null: bool) -> void
26
36
  def integer(name, description = nil, null: false) = add(name, :integer, description, null)
37
+ #: (Symbol, ?String?, ?null: bool) -> void
27
38
  def number(name, description = nil, null: false) = add(name, :number, description, null)
39
+ #: (Symbol, ?String?) -> void
28
40
  def unknown(name, description = nil) = add(name, :unknown, description)
41
+ #: (Symbol, Array[String | Symbol], ?String?, ?null: bool) -> void
29
42
  def enum(name, values, description = nil, null: false) = add(name, [:enum, values.map(&:to_s)], description, null)
43
+ #: (Symbol, ?String?, ?null: bool) -> void
30
44
  def strings(name, description = nil, null: false) = add(name, [:array, :string], description, null)
45
+ #: (Symbol, ?String?, ?null: bool) -> void
31
46
  def table(name, description = nil, null: false) = add(name, [:array, [:array, :string]], description, null)
47
+ #: (Symbol, ?String?, ?null: bool) { () [self: Schema] -> void } -> void
32
48
  def object(name, description = nil, null: false, &block) = add(name, Schema.build(&block), description, null)
33
49
 
34
50
  # Reuses a field another step declared, so two contracts that must agree
35
51
  # on one shape are written once: `field :created, AnItemExists.returns[:body]`.
52
+ #: (Symbol, Field, ?String?) -> void
36
53
  def field(name, other, description = nil) = add(name, other.type, description || other.description)
37
54
 
55
+ #: (Symbol | String) -> Field?
38
56
  def [](name) = fields.find { _1.name == name.to_sym }
39
57
 
58
+ #: (Array[String]) -> Schema
40
59
  def without(names) = Schema.new(fields.reject { names.include?(_1.name.to_s) })
41
60
 
61
+ #: () -> untyped
42
62
  def data_class
43
63
  @data_class ||= fields.empty? ? Data.define : Data.define(*fields.map(&:name))
44
64
  end
45
65
 
66
+ #: (Hash[String, untyped]) -> untyped
46
67
  def load(hash)
47
68
  data_class.new(**fields.to_h { [_1.name, hash.fetch(_1.name.to_s)] })
48
69
  end
49
70
 
50
- # Every way `value` departs from the schema, as `path: problem` lines.
71
+ # Every way `value` departs from the schema, as `path: problem` lines in
72
+ # zod's words, so a step fails with the text the TypeScript engine gives.
51
73
  # A key the schema does not declare is no problem: as a zod object does,
52
- # the schema drops it (`strip`), and `dropped` names where.
53
- def problems(value, path = nil)
54
- return ["#{path || "value"} must be an object, got #{value.inspect}"] unless value.is_a?(Hash)
74
+ # the schema drops it (`strip`), and `dropped` names where. `strict`
75
+ # refuses one at the root instead, as the TypeScript engine's args do.
76
+ #: (untyped, ?String?, ?strict: bool) -> Array[String]
77
+ def problems(value, path = nil, strict: false)
78
+ return ["#{path || "(root)"}: #{Schema.invalid("object", value)}"] unless value.is_a?(Hash)
55
79
 
56
80
  hash = value.transform_keys(&:to_s)
57
- fields.flat_map do |field|
81
+ found = fields.flat_map do |field|
58
82
  key = join(path, field.name)
59
- hash.key?(field.name.to_s) ? Schema.type_problems(field.type, hash[field.name.to_s], key) : ["#{key} is missing"]
83
+ if hash.key?(field.name.to_s) then Schema.type_problems(field.type, hash[field.name.to_s], key)
84
+ elsif field.type == :unknown then []
85
+ else Schema.type_problems(field.type, MISSING, key)
86
+ end
60
87
  end
88
+ extra = hash.keys - fields.map { _1.name.to_s }
89
+ return found unless strict && extra.any?
90
+
91
+ found + ["#{path || "(root)"}: Unrecognized key#{"s" if extra.size > 1}: #{extra.map { JSON.generate(_1) }.join(", ")}"]
61
92
  end
62
93
 
63
94
  # The value with every key the schema does not declare left out, at any
64
95
  # depth, with string keys. Assumes `problems` found none.
96
+ #: (Hash[untyped, untyped]) -> Hash[String, untyped]
65
97
  def strip(value)
66
98
  hash = value.transform_keys(&:to_s)
67
99
  fields.to_h { [_1.name.to_s, Schema.strip_type(_1.type, hash[_1.name.to_s])] }
68
100
  end
69
101
 
102
+ #: (untyped, untyped) -> untyped
70
103
  def self.strip_type(type, value)
71
104
  case type
72
105
  in [:nullable, inner] then value.nil? ? nil : strip_type(inner, value)
@@ -78,12 +111,37 @@ module Nukadoko
78
111
 
79
112
  # The paths of the keys `strip` leaves out, so a record can say what the
80
113
  # step returned and the contract did not keep.
114
+ #: (Hash[untyped, untyped], ?String?) -> Array[String]
81
115
  def dropped(value, path = nil)
82
116
  hash = value.transform_keys(&:to_s)
83
117
  names = fields.map { _1.name.to_s }
84
118
  (hash.keys - names).map { join(path, _1) } + fields.flat_map { Schema.dropped_type(_1.type, hash[_1.name.to_s], join(path, _1.name)) }
85
119
  end
86
120
 
121
+ # The keys the schema dropped, one entry per place that dropped any:
122
+ # `at` is the place as its keys and indexes, as the TypeScript engine's
123
+ # `returns_dropped` names it.
124
+ #: (untyped, ?Array[String]) -> Array[Hash[Symbol, untyped]]
125
+ def drops(value, at = [])
126
+ return [] unless value.is_a?(Hash)
127
+
128
+ hash = value.transform_keys(&:to_s)
129
+ keys = hash.keys - fields.map { _1.name.to_s }
130
+ own = keys.any? ? [{ at: at, keys: keys }] : []
131
+ own + fields.flat_map { Schema.drops_type(_1.type, hash[_1.name.to_s], [*at, _1.name.to_s]) }
132
+ end
133
+
134
+ #: (untyped, untyped, Array[String]) -> Array[Hash[Symbol, untyped]]
135
+ def self.drops_type(type, value, at)
136
+ case type
137
+ in [:nullable, inner] then value.nil? ? [] : drops_type(inner, value, at)
138
+ in [:array, item] then value.is_a?(Array) ? value.each_with_index.flat_map { drops_type(item, _1, [*at, _2.to_s]) } : []
139
+ in Schema then type.drops(value, at)
140
+ else []
141
+ end
142
+ end
143
+
144
+ #: (untyped, untyped, String) -> Array[String]
87
145
  def self.dropped_type(type, value, path)
88
146
  case type
89
147
  in [:nullable, inner] then value.nil? ? [] : dropped_type(inner, value, path)
@@ -93,36 +151,72 @@ module Nukadoko
93
151
  end
94
152
  end
95
153
 
154
+ # A key the value does not hold, which zod reads as undefined.
155
+ MISSING = Object.new.freeze
156
+ SAFE = 2**53 - 1
157
+
158
+ # What zod calls a value's type in "received ...".
159
+ #: (untyped) -> String
160
+ def self.received(value)
161
+ case value
162
+ when MISSING then "undefined"
163
+ when nil then "null"
164
+ when String then "string"
165
+ when true, false then "boolean"
166
+ when Float then value.nan? ? "NaN" : "number"
167
+ when Numeric then "number"
168
+ when Array then "array"
169
+ else "object"
170
+ end
171
+ end
172
+
173
+ #: (String, untyped) -> String
174
+ def self.invalid(expected, value) = "Invalid input: expected #{expected}, received #{received(value)}"
175
+
176
+ #: (untyped, untyped, String) -> Array[String]
96
177
  def self.type_problems(type, value, path)
97
- ok =
178
+ problem =
98
179
  case type
99
- in :string then value.is_a?(String)
100
- in :boolean then [true, false].include?(value)
101
- in :integer then value.is_a?(Integer)
102
- in :number then value.is_a?(Numeric)
103
- in :unknown then true
180
+ in :string then invalid("string", value) unless value.is_a?(String)
181
+ in :boolean then invalid("boolean", value) unless [true, false].include?(value)
182
+ in :number then invalid("number", value) unless value.is_a?(Numeric) && value.finite?
183
+ in :integer then integer_problem(value)
184
+ in :unknown then nil
104
185
  in [:nullable, inner] then return value.nil? ? [] : type_problems(inner, value, path)
105
- in [:enum, values] then values.include?(value.is_a?(Symbol) ? value.to_s : value)
186
+ in [:enum, values]
187
+ "Invalid option: expected one of #{values.map { JSON.generate(_1) }.join("|")}" unless values.include?(value.is_a?(Symbol) ? value.to_s : value)
106
188
  in [:array, item]
107
- return ["#{path} must be an array, got #{value.inspect}"] unless value.is_a?(Array)
189
+ return ["#{path}: #{invalid("array", value)}"] unless value.is_a?(Array)
108
190
 
109
- return value.each_with_index.flat_map { |v, i| type_problems(item, v, "#{path}[#{i}]") }
110
- in Schema then return type.problems(value, path)
191
+ return value.each_with_index.flat_map { |v, i| type_problems(item, v, "#{path}.#{i}") }
192
+ in Schema then return value.is_a?(Hash) ? type.problems(value, path) : ["#{path}: #{invalid("object", value)}"]
111
193
  end
112
- ok ? [] : ["#{path} must be #{type}, got #{value.inspect}"]
194
+ problem ? ["#{path}: #{problem}"] : []
195
+ end
196
+
197
+ # zod's int: a finite whole number within Number.MAX_SAFE_INTEGER.
198
+ #: (untyped) -> String?
199
+ def self.integer_problem(value)
200
+ return invalid("number", value) unless value.is_a?(Numeric) && value.finite?
201
+ return "Invalid input: expected int, received number" unless value == value.floor
202
+ return "Too big: expected int to be <=#{SAFE}" if value > SAFE
203
+
204
+ "Too small: expected int to be >=-#{SAFE}" if value < -SAFE
113
205
  end
114
206
 
115
207
  # The JSON Schema `nuka describe` prints, as zod's own conversion gives it:
116
208
  # the root is closed, and an inner object is closed only on the output
117
209
  # side (`returns`), where zod drops the keys it does not declare.
210
+ #: (?root: bool, ?output: bool) -> Hash[Symbol, untyped]
118
211
  def json_schema(root: true, output: false)
119
- schema = { type: "object", properties: fields.to_h { [_1.name, Schema.json_type(_1.type, output).merge(_1.description ? { description: _1.description } : {})] } }
212
+ schema = { type: "object", properties: fields.to_h { [_1.name, Schema.json_type(_1.type, output).merge(_1.description ? { description: _1.description } : {})] } } #: Hash[Symbol, untyped]
120
213
  schema[:required] = fields.map(&:name) if fields.any?
121
214
  return { "$schema": "https://json-schema.org/draft/2020-12/schema", **schema, additionalProperties: false } if root
122
215
 
123
216
  output ? schema.merge(additionalProperties: false) : schema
124
217
  end
125
218
 
219
+ #: (untyped, ?bool) -> Hash[Symbol, untyped]
126
220
  def self.json_type(type, output = false)
127
221
  case type
128
222
  in :string then { type: "string" }
@@ -137,9 +231,12 @@ module Nukadoko
137
231
  end
138
232
  end
139
233
 
234
+ #: () -> Array[String]
140
235
  def rbs_fields = fields.map { "attr_reader #{_1.name}: #{Schema.rbs_type(_1.type)}" }
236
+ #: () -> String
141
237
  def rbs_record = "{ #{fields.map { "#{_1.name}: #{Schema.rbs_type(_1.type)}" }.join(", ")} }"
142
238
 
239
+ #: (untyped) -> String
143
240
  def self.rbs_type(type)
144
241
  case type
145
242
  in :string then "String"
@@ -156,7 +253,9 @@ module Nukadoko
156
253
 
157
254
  private
158
255
 
256
+ #: (Symbol, untyped, String?, ?bool) -> void
159
257
  def add(name, type, description, null = false) = fields << Field.new(name.to_sym, null ? [:nullable, type] : type, description)
258
+ #: (String?, Symbol | String) -> String
160
259
  def join(path, name) = path ? "#{path}.#{name}" : name.to_s
161
260
  end
162
261
  end
@@ -0,0 +1,375 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ require "json"
5
+ require "open3"
6
+ require "stringio"
7
+
8
+ # Env files and the secrets they hold, as docs/spec.md "Environments and
9
+ # secrets" describes and the TypeScript engine reads them: one KEY=VALUE
10
+ # parser for the env fixture and the secret set, so the two agree on what a
11
+ # file holds; git as the classifier of which files are secret sources; and
12
+ # one redaction that writes `{{secret.NAME}}` for a loaded value in every
13
+ # spelling a record can carry it in. Nothing here decides when to redact:
14
+ # the run calls `redact` on each surface it writes.
15
+ module Nukadoko
16
+ module Engine
17
+ module EnvFile
18
+ # A configured env file that is on disk and cannot be read: setup
19
+ # stops, since a key the steps need would otherwise look missing.
20
+ class Unreadable < StandardError
21
+ #: (String, String) -> void
22
+ def initialize(path, detail)
23
+ super(%(env file "#{path}" could not be read: #{detail}))
24
+ end
25
+ end
26
+
27
+ QUOTES = ['"', "'", "`"].freeze
28
+
29
+ #: (String) -> Hash[String, String]
30
+ def self.parse(content) = scan(content)[0]
31
+
32
+ # The 1-based numbers of the lines that were not loaded; a blank, a
33
+ # comment, and a line inside a quoted value are not among them.
34
+ #: (String) -> Array[Integer]
35
+ def self.skipped_lines(content) = scan(content)[1]
36
+
37
+ # The format dotenv's default parser reads, with `=` as the only
38
+ # separator, scanned by hand so the lines it skips can be named.
39
+ #: (String) -> [Hash[String, String], Array[Integer]]
40
+ def self.scan(content)
41
+ text = content.gsub("\r\n", "\n").tr("\r", "\n")
42
+ values = {} #: Hash[String, String]
43
+ skipped = [] #: Array[Integer]
44
+ index = 0
45
+ line = 1
46
+ while index < text.length
47
+ at = line
48
+ index += 1 while space?(text[index])
49
+ char = text[index]
50
+ break if char.nil?
51
+
52
+ if char == "\n"
53
+ index += 1
54
+ line += 1
55
+ next
56
+ end
57
+ if char == "#"
58
+ index, line = rest_of_line(text, index, line)
59
+ next
60
+ end
61
+ if text[index, 6] == "export" && space?(text[index + 6])
62
+ index += 6
63
+ index += 1 while space?(text[index])
64
+ end
65
+ key_start = index
66
+ index += 1 while index < text.length && text[index] != "=" && text[index] != "\n"
67
+ key = text[key_start...index].to_s.strip
68
+ if text[index] != "=" || key.empty?
69
+ skipped << at
70
+ index, line = rest_of_line(text, index, line)
71
+ next
72
+ end
73
+ index += 1
74
+ index += 1 while space?(text[index])
75
+ if (quoted = quoted(text, index, line))
76
+ values[key], index, line = quoted
77
+ next
78
+ end
79
+ finish = index
80
+ finish += 1 while finish < text.length && text[finish] != "\n" && text[finish] != "#"
81
+ values[key] = text[index...finish].to_s.strip
82
+ index, line = rest_of_line(text, finish, line)
83
+ end
84
+ [values, skipped]
85
+ end
86
+
87
+ #: (String?) -> bool
88
+ def self.space?(char) = char == " " || char == "\t"
89
+
90
+ # A quoted value and where the scan resumes, or nil when the quote does
91
+ # not close or text follows it, so the line reads as unquoted.
92
+ #: (String, Integer, Integer) -> [String, Integer, Integer]?
93
+ def self.quoted(text, start, line)
94
+ quote = text[start]
95
+ return nil unless QUOTES.include?(quote)
96
+
97
+ index = start + 1
98
+ now = line
99
+ while index < text.length
100
+ char = text[index]
101
+ if char == "\\"
102
+ index += 1
103
+ if index < text.length
104
+ now += 1 if text[index] == "\n"
105
+ index += 1
106
+ end
107
+ next
108
+ end
109
+ if char == "\n"
110
+ now += 1
111
+ index += 1
112
+ next
113
+ end
114
+ if char != quote
115
+ index += 1
116
+ next
117
+ end
118
+ raw = text[(start + 1)...index].to_s
119
+ after = index + 1
120
+ after += 1 while space?(text[after])
121
+ following = text[after]
122
+ return nil unless following.nil? || following == "\n" || following == "#"
123
+
124
+ # dotenv expands \n and \r after the quotes come off, and a
125
+ # backslash before that pair is not special, so "\\n" is a
126
+ # backslash and a newline, as in the files people already have.
127
+ value = quote == '"' ? raw.gsub("\\n", "\n").gsub("\\r", "\r") : raw
128
+ after += 1 while following == "#" && after < text.length && text[after] != "\n"
129
+ if text[after] == "\n"
130
+ after += 1
131
+ now += 1
132
+ end
133
+ return [value, after, now]
134
+ end
135
+ nil
136
+ end
137
+
138
+ #: (String, Integer, Integer) -> [Integer, Integer]
139
+ def self.rest_of_line(text, index, line)
140
+ index += 1 while index < text.length && text[index] != "\n"
141
+ index < text.length ? [index + 1, line + 1] : [index, line]
142
+ end
143
+
144
+ # The configured files merged in order, later files winning. A path
145
+ # that is not on disk gives nothing, which `nuka check` warns about;
146
+ # any other failure to read raises. The process environment is never
147
+ # merged in, so the same files give the same record on any machine.
148
+ #: (String, Array[String]) -> Hash[String, String]
149
+ def self.load(root, paths)
150
+ paths.each_with_object({}) do |path, merged|
151
+ content = read(root, path)
152
+ merged.merge!(parse(content)) if content
153
+ end
154
+ end
155
+
156
+ #: (String, String) -> String?
157
+ def self.read(root, path)
158
+ File.read(File.join(root, path), encoding: "UTF-8")
159
+ rescue Errno::ENOENT
160
+ nil
161
+ rescue SystemCallError => e
162
+ raise Unreadable.new(path, e.class.name.to_s.split("::").last.to_s)
163
+ end
164
+ end
165
+
166
+ # One run's secret values, and the redaction that writes each as
167
+ # `{{secret.NAME}}`.
168
+ class Secrets
169
+ # A shorter value would match ordinary text (ids, statuses, short
170
+ # words) all over a record and destroy what redaction protects.
171
+ MIN_LENGTH = 4
172
+ # What encodeURIComponent leaves as itself.
173
+ URI_KEPT = /[A-Za-z0-9\-_.!~*'()]/
174
+ # What URLSearchParams leaves as itself; a space becomes `+`.
175
+ FORM_KEPT = /[A-Za-z0-9\-_.*]/
176
+
177
+ # Which configured files are secret sources: untracked, ignored, or
178
+ # tracked and different from HEAD. When git cannot answer (no git, no
179
+ # repository, no HEAD), every file is one: the classification fails
180
+ # safe and never fails the run.
181
+ #: (String, Array[String]) -> { tracked: Array[String], source: Array[String] }
182
+ def self.classify(root, paths)
183
+ return { tracked: [], source: [] } if paths.empty?
184
+
185
+ listed, status = Open3.capture2("git", "-C", root, "ls-files", "-z", "--", *paths, err: File::NULL)
186
+ return { tracked: [], source: paths.dup } unless status.success?
187
+
188
+ tracked = listed.split("\0").reject(&:empty?)
189
+ known = paths.select { tracked.include?(_1) }
190
+ dirty = known
191
+ if known.any?
192
+ # HEAD against the working tree, so a staged edit counts too;
193
+ # --relative names a file below root by the path it was given.
194
+ diff, status = Open3.capture2("git", "-C", root, "diff", "-z", "--name-only", "--relative", "HEAD", "--", *known, err: File::NULL)
195
+ dirty = diff.split("\0").reject(&:empty?) if status.success?
196
+ end
197
+ plain = paths.select { known.include?(_1) && !dirty.include?(_1) }
198
+ { tracked: plain, source: paths - plain }
199
+ rescue SystemCallError
200
+ { tracked: [], source: paths.dup }
201
+ end
202
+
203
+ # Every key of a secret source except `public` ones, and the keys of a
204
+ # tracked file that `redact` names, each at least MIN_LENGTH long.
205
+ #: (String, Array[String], ?public_keys: Array[String], ?redact_keys: Array[String]) -> Secrets
206
+ def self.of(root, paths, public_keys: [], redact_keys: [])
207
+ classified = classify(root, paths)
208
+ values = EnvFile.load(root, classified[:source])
209
+ EnvFile.load(root, classified[:tracked]).each { |key, value| values[key] = value if redact_keys.include?(key) }
210
+ new(values.reject { |key, value| public_keys.include?(key) || value.length < MIN_LENGTH })
211
+ end
212
+
213
+ #: Hash[String, String]
214
+ attr_reader :values
215
+
216
+ # Each name with its value, a name twice when two sets held it with
217
+ # different values (`with`), so neither value goes unredacted.
218
+ #: Array[[String, String]]
219
+ attr_reader :pairs
220
+
221
+ #: (?Hash[String, String] | Array[[String, String]]) -> void
222
+ def initialize(values = {})
223
+ @pairs = values.to_a.uniq
224
+ @values = @pairs.to_h
225
+ @replacements = replacements
226
+ @pattern = @replacements.empty? ? nil : Regexp.union((@replacements.keys + @replacements.values.uniq).sort_by { -_1.length })
227
+ end
228
+
229
+ #: () -> bool
230
+ def empty? = @pairs.empty?
231
+
232
+ # Both sets: a tree's pass redacts with head's secrets as well as its
233
+ # own, since the tree's config must not decide which of head's values
234
+ # may print.
235
+ #: (Secrets) -> Secrets
236
+ def with(other) = Secrets.new(@pairs + other.pairs)
237
+
238
+ # Every loaded value, each once.
239
+ #: () -> Array[String]
240
+ def shown_values = @pairs.map(&:last).uniq
241
+
242
+ # A copy of `value` with every secret spelling in its strings and
243
+ # keys written as its token. Two keys that redact to one would lose
244
+ # a subtree, so that raises.
245
+ #: (untyped) -> untyped
246
+ def redact(value)
247
+ return value unless @pattern
248
+
249
+ case value
250
+ when String then redact_string(value)
251
+ when Array then value.map { redact(_1) }
252
+ when Hash
253
+ value.each_with_object({}) do |(key, inner), out|
254
+ shown = key.is_a?(String) || key.is_a?(Symbol) ? redact_string(key.to_s) : key
255
+ shown = shown.to_sym if key.is_a?(Symbol) && shown.is_a?(String)
256
+ raise ArgumentError, "redact: keys #{JSON.generate(key.to_s)} and another both redact to #{JSON.generate(shown.to_s)}" if out.key?(shown)
257
+
258
+ out[shown] = redact(inner)
259
+ end
260
+ else value
261
+ end
262
+ end
263
+
264
+ # One pass over every spelling and every token, longest first, so a
265
+ # token already in the text matches as itself and a second redaction
266
+ # changes nothing.
267
+ #: (String) -> String
268
+ def redact_string(text)
269
+ pattern = @pattern
270
+ return text unless pattern
271
+
272
+ text.gsub(pattern) { |found| @replacements.fetch(found, found) }
273
+ end
274
+
275
+ private
276
+
277
+ # Each spelling a record can hold a value in: the value, its
278
+ # percent-encoded forms (as encodeURIComponent writes it, and with `'`
279
+ # as `%27`, as a URL's href does), its form-urlencoded form, and the
280
+ # inside of its JSON string. A raw value claims its spelling first;
281
+ # among equals the alphabetically first name wins.
282
+ #: () -> Hash[String, String]
283
+ def replacements
284
+ named = @pairs.select { |_, value| value.length >= MIN_LENGTH }.sort_by(&:first)
285
+ tokens = {} #: Hash[String, String]
286
+ named.each { |name, value| tokens[value] ||= "{{secret.#{name}}}" }
287
+ named.each do |name, value|
288
+ uri = encode(value, URI_KEPT)
289
+ [uri, uri.gsub("'", "%27"), encode(value, FORM_KEPT, space: "+"), JSON.generate(value)[1...-1].to_s].each do |spelling|
290
+ tokens[spelling] ||= "{{secret.#{name}}}"
291
+ end
292
+ end
293
+ tokens
294
+ end
295
+
296
+ #: (String, Regexp, ?space: String?) -> String
297
+ def encode(value, kept, space: nil)
298
+ value.each_char.map do |char|
299
+ next space if space && char == " "
300
+
301
+ char.match?(kept) ? char : char.bytes.map { format("%%%02X", _1) }.join
302
+ end.join
303
+ end
304
+ end
305
+
306
+ # What project code prints while a step runs reaches stderr, with the
307
+ # run's secrets redacted, so `nuka do`'s stdout stays the record alone
308
+ # and a printed token is no plainer than the record it was kept out of.
309
+ # A value split across two writes is not found, and a child process
310
+ # that writes to the file descriptors itself is not seen.
311
+ class RedactedOutput
312
+ #: [T] (Secrets) { () -> T } -> T
313
+ def self.around(secrets)
314
+ out = $stdout
315
+ err = $stderr
316
+ writer = new(err, secrets)
317
+ $stdout = writer
318
+ $stderr = writer
319
+ yield
320
+ ensure
321
+ $stdout = out if out
322
+ $stderr = err if err
323
+ end
324
+
325
+ #: (untyped, Secrets) -> void
326
+ def initialize(to, secrets)
327
+ @to = to
328
+ @secrets = secrets
329
+ end
330
+
331
+ #: (*untyped) -> Integer
332
+ def write(*parts) = @to.write(*parts.map { @secrets.redact_string(_1.to_s) })
333
+
334
+ #: (*untyped) -> nil
335
+ def puts(*lines)
336
+ text = StringIO.new
337
+ text.puts(*lines)
338
+ write(text.string)
339
+ nil
340
+ end
341
+
342
+ #: (*untyped) -> nil
343
+ def print(*parts)
344
+ write(*parts)
345
+ nil
346
+ end
347
+
348
+ #: (String, *untyped) -> nil
349
+ def printf(format, *values) = print(Kernel.format(format, *values))
350
+
351
+ #: (untyped) -> self
352
+ def <<(part)
353
+ write(part)
354
+ self
355
+ end
356
+
357
+ #: () -> self
358
+ def flush
359
+ @to.flush
360
+ self
361
+ end
362
+
363
+ #: () -> bool
364
+ def sync = true
365
+
366
+ #: (bool) -> bool
367
+ def sync=(value)
368
+ value
369
+ end
370
+
371
+ #: () -> bool
372
+ def tty? = false
373
+ end
374
+ end
375
+ end