nukadoko 0.1.0 → 0.2.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 (147) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +291 -0
  3. data/README.ja.md +58 -5
  4. data/README.md +15 -3
  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 +274 -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/claims.rb +407 -30
  15. data/lib/nukadoko/cli.rb +802 -19
  16. data/lib/nukadoko/codes.json +942 -0
  17. data/lib/nukadoko/codes.rb +19 -0
  18. data/lib/nukadoko/command.rb +214 -12
  19. data/lib/nukadoko/criteria.rb +172 -0
  20. data/lib/nukadoko/definition.rb +33 -41
  21. data/lib/nukadoko/env_check.rb +90 -0
  22. data/lib/nukadoko/features.rb +80 -10
  23. data/lib/nukadoko/fixtures.rb +296 -10
  24. data/lib/nukadoko/http_recording.rb +68 -0
  25. data/lib/nukadoko/init.rb +130 -0
  26. data/lib/nukadoko/judge.rb +221 -0
  27. data/lib/nukadoko/judgment_file.rb +78 -0
  28. data/lib/nukadoko/judgments.rb +256 -0
  29. data/lib/nukadoko/literal.rb +129 -0
  30. data/lib/nukadoko/measured.rb +105 -0
  31. data/lib/nukadoko/order.rb +84 -0
  32. data/lib/nukadoko/parts.rb +42 -21
  33. data/lib/nukadoko/pattern.rb +11 -1
  34. data/lib/nukadoko/poll.rb +17 -6
  35. data/lib/nukadoko/program.rb +105 -17
  36. data/lib/nukadoko/project_fixtures.rb +17 -2
  37. data/lib/nukadoko/report_allure.rb +751 -0
  38. data/lib/nukadoko/report_messages.rb +167 -0
  39. data/lib/nukadoko/report_run.rb +169 -0
  40. data/lib/nukadoko/run.rb +865 -88
  41. data/lib/nukadoko/run_record.rb +532 -0
  42. data/lib/nukadoko/scaffold.rb +1015 -0
  43. data/lib/nukadoko/schema.rb +61 -4
  44. data/lib/nukadoko/secrets.rb +359 -0
  45. data/lib/nukadoko/selection.rb +163 -0
  46. data/lib/nukadoko/signature.rb +4 -1
  47. data/lib/nukadoko/skill.rb +36 -0
  48. data/lib/nukadoko/step.rb +62 -21
  49. data/lib/nukadoko/summary.rb +662 -0
  50. data/lib/nukadoko/table.rb +34 -2
  51. data/lib/nukadoko/text_fit.rb +179 -0
  52. data/lib/nukadoko/trace.rb +244 -0
  53. data/lib/nukadoko/trace_actions.rb +116 -0
  54. data/lib/nukadoko/tree_passes.rb +119 -0
  55. data/lib/nukadoko/verdict.rb +128 -0
  56. data/lib/nukadoko/version.rb +2 -1
  57. data/lib/nukadoko/vocabulary.rb +6 -0
  58. data/lib/nukadoko/walk.rb +305 -0
  59. data/lib/nukadoko/walk_files.rb +473 -0
  60. data/lib/nukadoko/walk_step.rb +149 -0
  61. data/lib/nukadoko.rb +36 -0
  62. data/llms.txt +296 -0
  63. data/sig/generated/nukadoko/aria_snapshot.rbs +331 -0
  64. data/sig/generated/nukadoko/aria_tree.rbs +142 -0
  65. data/sig/generated/nukadoko/base.rbs +136 -0
  66. data/sig/generated/nukadoko/check.rbs +255 -0
  67. data/sig/generated/nukadoko/claim_check.rbs +118 -0
  68. data/sig/generated/nukadoko/claim_check_run.rbs +88 -0
  69. data/sig/generated/nukadoko/claim_line.rbs +158 -0
  70. data/sig/generated/nukadoko/claim_rules.rbs +172 -0
  71. data/sig/generated/nukadoko/claims.rbs +165 -0
  72. data/sig/generated/nukadoko/cli.rbs +182 -0
  73. data/sig/generated/nukadoko/codes.rbs +16 -0
  74. data/sig/generated/nukadoko/command.rbs +109 -0
  75. data/sig/generated/nukadoko/criteria.rbs +83 -0
  76. data/sig/generated/nukadoko/definition.rbs +30 -0
  77. data/sig/generated/nukadoko/env_check.rbs +38 -0
  78. data/sig/generated/nukadoko/features.rbs +101 -0
  79. data/sig/generated/nukadoko/fixtures.rbs +152 -0
  80. data/sig/generated/nukadoko/http_recording.rbs +29 -0
  81. data/sig/generated/nukadoko/init.rbs +66 -0
  82. data/sig/generated/nukadoko/judge.rbs +64 -0
  83. data/sig/generated/nukadoko/judgment_file.rbs +39 -0
  84. data/sig/generated/nukadoko/judgments.rbs +120 -0
  85. data/sig/generated/nukadoko/literal.rbs +71 -0
  86. data/sig/generated/nukadoko/measured.rbs +42 -0
  87. data/sig/generated/nukadoko/order.rbs +54 -0
  88. data/sig/generated/nukadoko/parts.rbs +35 -0
  89. data/sig/generated/nukadoko/pattern.rbs +28 -0
  90. data/sig/generated/nukadoko/poll.rbs +40 -0
  91. data/sig/generated/nukadoko/program.rbs +101 -0
  92. data/sig/generated/nukadoko/project_fixtures.rbs +57 -0
  93. data/sig/generated/nukadoko/report_allure.rbs +268 -0
  94. data/sig/generated/nukadoko/report_messages.rbs +68 -0
  95. data/sig/generated/nukadoko/report_run.rbs +102 -0
  96. data/sig/generated/nukadoko/run.rbs +257 -0
  97. data/sig/generated/nukadoko/run_record.rbs +174 -0
  98. data/sig/generated/nukadoko/scaffold.rbs +328 -0
  99. data/sig/generated/nukadoko/schema.rbs +137 -0
  100. data/sig/generated/nukadoko/secrets.rbs +157 -0
  101. data/sig/generated/nukadoko/selection.rbs +73 -0
  102. data/sig/generated/nukadoko/signature.rbs +17 -0
  103. data/sig/generated/nukadoko/skill.rbs +20 -0
  104. data/sig/generated/nukadoko/step.rbs +115 -0
  105. data/sig/generated/nukadoko/summary.rbs +204 -0
  106. data/sig/generated/nukadoko/table.rbs +43 -0
  107. data/sig/generated/nukadoko/text_fit.rbs +70 -0
  108. data/sig/generated/nukadoko/trace.rbs +127 -0
  109. data/sig/generated/nukadoko/trace_actions.rbs +40 -0
  110. data/sig/generated/nukadoko/tree_passes.rbs +48 -0
  111. data/sig/generated/nukadoko/verdict.rbs +56 -0
  112. data/sig/generated/nukadoko/version.rbs +5 -0
  113. data/sig/generated/nukadoko/vocabulary.rbs +25 -0
  114. data/sig/generated/nukadoko/walk.rbs +139 -0
  115. data/sig/generated/nukadoko/walk_files.rbs +189 -0
  116. data/sig/generated/nukadoko/walk_step.rbs +50 -0
  117. data/sig/generated/nukadoko.rbs +15 -0
  118. data/sig/nukadoko.rbs +5 -48
  119. data/skills/nukadoko/SKILL.md +120 -0
  120. data/skills/nukadoko/references/checking-steps.md +200 -0
  121. data/skills/nukadoko/references/diagnosing.md +200 -0
  122. data/skills/nukadoko/references/done.md +99 -0
  123. data/skills/nukadoko/references/evidence.md +124 -0
  124. data/skills/nukadoko/references/examples/cli.md +230 -0
  125. data/skills/nukadoko/references/examples/http-api.md +339 -0
  126. data/skills/nukadoko/references/examples/workflow.md +173 -0
  127. data/skills/nukadoko/references/exploring.md +184 -0
  128. data/skills/nukadoko/references/fixtures.md +198 -0
  129. data/skills/nukadoko/references/from-prose.md +51 -0
  130. data/skills/nukadoko/references/judgments.md +95 -0
  131. data/skills/nukadoko/references/maintenance.md +97 -0
  132. data/skills/nukadoko/references/merge-risk.md +74 -0
  133. data/skills/nukadoko/references/parts.md +152 -0
  134. data/skills/nukadoko/references/perturbed-worlds.md +107 -0
  135. data/skills/nukadoko/references/program.md +200 -0
  136. data/skills/nukadoko/references/reviewing.md +200 -0
  137. data/skills/nukadoko/references/running.md +200 -0
  138. data/skills/nukadoko/references/scenario-rules.md +188 -0
  139. data/skills/nukadoko/references/states.md +66 -0
  140. data/skills/nukadoko/references/step-files.md +200 -0
  141. data/skills/nukadoko/references/verdicts.md +200 -0
  142. data/skills/nukadoko/references/writing-steps.md +200 -0
  143. data/skills/nukadoko/references/writing-the-feature.md +165 -0
  144. data/skills/nukadoko/scripts/claude-code-verdict-hook.mjs +99 -0
  145. data/skills/nukadoko/scripts/merge-risk.jq +56 -0
  146. data/skills/nukadoko-verification/SKILL.md +263 -0
  147. metadata +121 -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,43 +7,63 @@
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
@@ -50,6 +71,7 @@ module Nukadoko
50
71
  # Every way `value` departs from the schema, as `path: problem` lines.
51
72
  # A key the schema does not declare is no problem: as a zod object does,
52
73
  # the schema drops it (`strip`), and `dropped` names where.
74
+ #: (untyped, ?String?) -> Array[String]
53
75
  def problems(value, path = nil)
54
76
  return ["#{path || "value"} must be an object, got #{value.inspect}"] unless value.is_a?(Hash)
55
77
 
@@ -62,11 +84,13 @@ module Nukadoko
62
84
 
63
85
  # The value with every key the schema does not declare left out, at any
64
86
  # depth, with string keys. Assumes `problems` found none.
87
+ #: (Hash[untyped, untyped]) -> Hash[String, untyped]
65
88
  def strip(value)
66
89
  hash = value.transform_keys(&:to_s)
67
90
  fields.to_h { [_1.name.to_s, Schema.strip_type(_1.type, hash[_1.name.to_s])] }
68
91
  end
69
92
 
93
+ #: (untyped, untyped) -> untyped
70
94
  def self.strip_type(type, value)
71
95
  case type
72
96
  in [:nullable, inner] then value.nil? ? nil : strip_type(inner, value)
@@ -78,12 +102,37 @@ module Nukadoko
78
102
 
79
103
  # The paths of the keys `strip` leaves out, so a record can say what the
80
104
  # step returned and the contract did not keep.
105
+ #: (Hash[untyped, untyped], ?String?) -> Array[String]
81
106
  def dropped(value, path = nil)
82
107
  hash = value.transform_keys(&:to_s)
83
108
  names = fields.map { _1.name.to_s }
84
109
  (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
110
  end
86
111
 
112
+ # The keys the schema dropped, one entry per place that dropped any:
113
+ # `at` is the place as its keys and indexes, as the TypeScript engine's
114
+ # `returns_dropped` names it.
115
+ #: (untyped, ?Array[String]) -> Array[Hash[Symbol, untyped]]
116
+ def drops(value, at = [])
117
+ return [] unless value.is_a?(Hash)
118
+
119
+ hash = value.transform_keys(&:to_s)
120
+ keys = hash.keys - fields.map { _1.name.to_s }
121
+ own = keys.any? ? [{ at: at, keys: keys }] : []
122
+ own + fields.flat_map { Schema.drops_type(_1.type, hash[_1.name.to_s], [*at, _1.name.to_s]) }
123
+ end
124
+
125
+ #: (untyped, untyped, Array[String]) -> Array[Hash[Symbol, untyped]]
126
+ def self.drops_type(type, value, at)
127
+ case type
128
+ in [:nullable, inner] then value.nil? ? [] : drops_type(inner, value, at)
129
+ in [:array, item] then value.is_a?(Array) ? value.each_with_index.flat_map { drops_type(item, _1, [*at, _2.to_s]) } : []
130
+ in Schema then type.drops(value, at)
131
+ else []
132
+ end
133
+ end
134
+
135
+ #: (untyped, untyped, String) -> Array[String]
87
136
  def self.dropped_type(type, value, path)
88
137
  case type
89
138
  in [:nullable, inner] then value.nil? ? [] : dropped_type(inner, value, path)
@@ -93,6 +142,7 @@ module Nukadoko
93
142
  end
94
143
  end
95
144
 
145
+ #: (untyped, untyped, String) -> Array[String]
96
146
  def self.type_problems(type, value, path)
97
147
  ok =
98
148
  case type
@@ -115,14 +165,16 @@ module Nukadoko
115
165
  # The JSON Schema `nuka describe` prints, as zod's own conversion gives it:
116
166
  # the root is closed, and an inner object is closed only on the output
117
167
  # side (`returns`), where zod drops the keys it does not declare.
168
+ #: (?root: bool, ?output: bool) -> Hash[Symbol, untyped]
118
169
  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 } : {})] } }
170
+ 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
171
  schema[:required] = fields.map(&:name) if fields.any?
121
172
  return { "$schema": "https://json-schema.org/draft/2020-12/schema", **schema, additionalProperties: false } if root
122
173
 
123
174
  output ? schema.merge(additionalProperties: false) : schema
124
175
  end
125
176
 
177
+ #: (untyped, ?bool) -> Hash[Symbol, untyped]
126
178
  def self.json_type(type, output = false)
127
179
  case type
128
180
  in :string then { type: "string" }
@@ -137,9 +189,12 @@ module Nukadoko
137
189
  end
138
190
  end
139
191
 
192
+ #: () -> Array[String]
140
193
  def rbs_fields = fields.map { "attr_reader #{_1.name}: #{Schema.rbs_type(_1.type)}" }
194
+ #: () -> String
141
195
  def rbs_record = "{ #{fields.map { "#{_1.name}: #{Schema.rbs_type(_1.type)}" }.join(", ")} }"
142
196
 
197
+ #: (untyped) -> String
143
198
  def self.rbs_type(type)
144
199
  case type
145
200
  in :string then "String"
@@ -156,7 +211,9 @@ module Nukadoko
156
211
 
157
212
  private
158
213
 
214
+ #: (Symbol, untyped, String?, ?bool) -> void
159
215
  def add(name, type, description, null = false) = fields << Field.new(name.to_sym, null ? [:nullable, type] : type, description)
216
+ #: (String?, Symbol | String) -> String
160
217
  def join(path, name) = path ? "#{path}.#{name}" : name.to_s
161
218
  end
162
219
  end
@@ -0,0 +1,359 @@
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
+ #: (?Hash[String, String]) -> void
217
+ def initialize(values = {})
218
+ @values = values
219
+ @replacements = replacements
220
+ @pattern = @replacements.empty? ? nil : Regexp.union((@replacements.keys + @replacements.values.uniq).sort_by { -_1.length })
221
+ end
222
+
223
+ #: () -> bool
224
+ def empty? = @values.empty?
225
+
226
+ # A copy of `value` with every secret spelling in its strings and
227
+ # keys written as its token. Two keys that redact to one would lose
228
+ # a subtree, so that raises.
229
+ #: (untyped) -> untyped
230
+ def redact(value)
231
+ return value unless @pattern
232
+
233
+ case value
234
+ when String then redact_string(value)
235
+ when Array then value.map { redact(_1) }
236
+ when Hash
237
+ value.each_with_object({}) do |(key, inner), out|
238
+ shown = key.is_a?(String) || key.is_a?(Symbol) ? redact_string(key.to_s) : key
239
+ shown = shown.to_sym if key.is_a?(Symbol) && shown.is_a?(String)
240
+ raise ArgumentError, "redact: keys #{JSON.generate(key.to_s)} and another both redact to #{JSON.generate(shown.to_s)}" if out.key?(shown)
241
+
242
+ out[shown] = redact(inner)
243
+ end
244
+ else value
245
+ end
246
+ end
247
+
248
+ # One pass over every spelling and every token, longest first, so a
249
+ # token already in the text matches as itself and a second redaction
250
+ # changes nothing.
251
+ #: (String) -> String
252
+ def redact_string(text)
253
+ pattern = @pattern
254
+ return text unless pattern
255
+
256
+ text.gsub(pattern) { |found| @replacements.fetch(found, found) }
257
+ end
258
+
259
+ private
260
+
261
+ # Each spelling a record can hold a value in: the value, its
262
+ # percent-encoded forms (as encodeURIComponent writes it, and with `'`
263
+ # as `%27`, as a URL's href does), its form-urlencoded form, and the
264
+ # inside of its JSON string. A raw value claims its spelling first;
265
+ # among equals the alphabetically first name wins.
266
+ #: () -> Hash[String, String]
267
+ def replacements
268
+ named = @values.select { |_, value| value.length >= MIN_LENGTH }.sort_by(&:first)
269
+ tokens = {} #: Hash[String, String]
270
+ named.each { |name, value| tokens[value] ||= "{{secret.#{name}}}" }
271
+ named.each do |name, value|
272
+ uri = encode(value, URI_KEPT)
273
+ [uri, uri.gsub("'", "%27"), encode(value, FORM_KEPT, space: "+"), JSON.generate(value)[1...-1].to_s].each do |spelling|
274
+ tokens[spelling] ||= "{{secret.#{name}}}"
275
+ end
276
+ end
277
+ tokens
278
+ end
279
+
280
+ #: (String, Regexp, ?space: String?) -> String
281
+ def encode(value, kept, space: nil)
282
+ value.each_char.map do |char|
283
+ next space if space && char == " "
284
+
285
+ char.match?(kept) ? char : char.bytes.map { format("%%%02X", _1) }.join
286
+ end.join
287
+ end
288
+ end
289
+
290
+ # What project code prints while a step runs reaches stderr, with the
291
+ # run's secrets redacted, so `nuka do`'s stdout stays the record alone
292
+ # and a printed token is no plainer than the record it was kept out of.
293
+ # A value split across two writes is not found, and a child process
294
+ # that writes to the file descriptors itself is not seen.
295
+ class RedactedOutput
296
+ #: [T] (Secrets) { () -> T } -> T
297
+ def self.around(secrets)
298
+ out = $stdout
299
+ err = $stderr
300
+ writer = new(err, secrets)
301
+ $stdout = writer
302
+ $stderr = writer
303
+ yield
304
+ ensure
305
+ $stdout = out if out
306
+ $stderr = err if err
307
+ end
308
+
309
+ #: (untyped, Secrets) -> void
310
+ def initialize(to, secrets)
311
+ @to = to
312
+ @secrets = secrets
313
+ end
314
+
315
+ #: (*untyped) -> Integer
316
+ def write(*parts) = @to.write(*parts.map { @secrets.redact_string(_1.to_s) })
317
+
318
+ #: (*untyped) -> nil
319
+ def puts(*lines)
320
+ text = StringIO.new
321
+ text.puts(*lines)
322
+ write(text.string)
323
+ nil
324
+ end
325
+
326
+ #: (*untyped) -> nil
327
+ def print(*parts)
328
+ write(*parts)
329
+ nil
330
+ end
331
+
332
+ #: (String, *untyped) -> nil
333
+ def printf(format, *values) = print(Kernel.format(format, *values))
334
+
335
+ #: (untyped) -> self
336
+ def <<(part)
337
+ write(part)
338
+ self
339
+ end
340
+
341
+ #: () -> self
342
+ def flush
343
+ @to.flush
344
+ self
345
+ end
346
+
347
+ #: () -> bool
348
+ def sync = true
349
+
350
+ #: (bool) -> bool
351
+ def sync=(value)
352
+ value
353
+ end
354
+
355
+ #: () -> bool
356
+ def tty? = false
357
+ end
358
+ end
359
+ end