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
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ require "json"
5
+
6
+ # Every code a finding or a refusal can carry, with its description and
7
+ # the edit that gets past it, as the TypeScript engine's registry holds
8
+ # them (`bin/sync-codes` writes codes.json from it), so one code reads the
9
+ # same in either engine. Data only.
10
+ module Nukadoko
11
+ module Engine
12
+ module Codes
13
+ ALL = JSON.parse(File.read(File.join(__dir__.to_s, "codes.json"), encoding: "UTF-8")).freeze
14
+
15
+ #: (String) -> String?
16
+ def self.fix(code) = ALL.dig(code, "fix")
17
+ end
18
+ end
19
+ end
@@ -1,8 +1,11 @@
1
1
  # frozen_string_literal: true
2
+ # rbs_inline: enabled
2
3
 
3
4
  require "open3"
4
5
  require "tmpdir"
5
6
  require "fileutils"
7
+ require "securerandom"
8
+ require "timeout"
6
9
 
7
10
  # What a command-line scenario needs: scratch directories that live as long
8
11
  # as one scenario, and a way to run the program under test that keeps every
@@ -10,51 +13,250 @@ require "fileutils"
10
13
  # directory it made or forgets to note a process it started.
11
14
  module Nukadoko
12
15
  # Runs a command and gives what it left: the exit code (nil when a signal
13
- # ended it), stdout, and stderr. Inside a step, the run is noted in the
14
- # step record's processes.
15
- def self.run_command(command, args = [], cwd: Dir.pwd, env: {}, stdin: nil)
16
+ # ended it), the signal, stdout, and stderr. Inside a step the run is
17
+ # noted in the step record's processes, with what changed under `cwd`
18
+ # while it ran, which the result gives as `files` too; `files: true`
19
+ # measures that outside a step as well. `env` is added to the runner's
20
+ # environment. A run that `timeout` seconds stopped raises, since it has
21
+ # no exit code to read. `input` (or `stdin`) is written to the program's
22
+ # stdin. `redact` names secrets the step holds itself, which the record
23
+ # writes as `{{secret.NAME}}` while the program still gets the real value.
24
+ #: (String, ?Array[String], ?cwd: String, ?env: Hash[String | Symbol, String], ?input: String?, ?stdin: String?, ?timeout: Numeric?, ?redact: Hash[String | Symbol, String], ?files: bool) -> Hash[Symbol, untyped]
25
+ def self.run_command(command, args = [], cwd: Dir.pwd, env: {}, input: nil, stdin: nil, timeout: nil, redact: {}, files: false)
26
+ stdin = input.nil? ? stdin : input
27
+ held = Engine::Secrets.new(redact.to_h { |name, value| [name.to_s, value.to_s] })
28
+ recording = Engine::Processes.current
29
+ cwd = File.expand_path(cwd)
30
+ # A tool that copies TRACEPARENT into its requests makes the program's
31
+ # log lines for them the step's. A value the step chose is kept.
32
+ env = env.transform_keys(&:to_s)
33
+ traceparent = (Engine::Trace.current&.process_traceparent unless env.key?("TRACEPARENT"))
34
+ chosen = env
35
+ env = env.merge("TRACEPARENT" => traceparent) if traceparent
36
+ before = Engine::FileWalk.snapshot(cwd) if recording || files
16
37
  started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
17
- stdout, stderr, status = Open3.capture3(env.transform_keys(&:to_s), command, *args, chdir: cwd, stdin_data: stdin.to_s)
18
- result = { exitCode: status.exitstatus, stdout: stdout, stderr: stderr }
19
- Engine::Processes.current&.push(
20
- command: command, args: args, cwd: File.expand_path(cwd), exit_code: status.exitstatus,
21
- signal: status.termsig && Signal.signame(status.termsig),
22
- duration_ms: ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000).round
38
+ # A group of its own, so its close tells whether anything it started still runs.
39
+ stdout, stderr, status, timed_out = Engine::Processes.spawn(env, [command, *args], cwd, stdin, timeout, group: !recording.nil?)
40
+ duration = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000).round
41
+ changes = Engine::FileWalk.difference(before, Engine::FileWalk.snapshot(cwd)) if before
42
+ signal = (number = status.termsig) && "SIG#{Signal.signame(number)}"
43
+ recording&.push(
44
+ { command: held.redact([command, *args]), cwd: cwd, exit_code: status.exitstatus, signal: signal, timed_out: timed_out || nil,
45
+ group: (Engine::Processes.group_state(status.pid) if Engine::Processes.groups?), duration_ms: duration, files: changes,
46
+ env: Engine::Processes.env_entry(chosen), traceparent: traceparent }.compact.merge(output: held.redact({ stdout: stdout, stderr: stderr, stdin: stdin }))
23
47
  )
24
- result
48
+ raise Timeout::Error, "#{command} did not finish in #{timeout} seconds, so it has no exit code" if timed_out
49
+
50
+ { exitCode: status.exitstatus, signal: signal, stdout: stdout, stderr: stderr, **(changes ? { files: changes } : {}) }
25
51
  end
26
52
 
27
53
  module Engine
28
54
  # The processes the running step started, kept per thread so a step
29
55
  # that calls run_command from a helper is still measured.
30
56
  module Processes
57
+ #: () -> Array[untyped]?
31
58
  def self.current = Thread.current[:nukadoko_processes]
32
59
 
33
60
  # Fills `into` even when the step raises, so a failed step still names
34
61
  # the processes it ran.
62
+ #: [T] (Array[untyped]) { () -> T } -> T
35
63
  def self.collect(into)
36
64
  Thread.current[:nukadoko_processes] = into
37
65
  yield
38
66
  ensure
39
67
  Thread.current[:nukadoko_processes] = nil
40
68
  end
69
+
70
+ #: () -> bool
71
+ def self.groups? = !Gem.win_platform?
72
+
73
+ # Runs the command to its close, its stdin closed after `input`.
74
+ #: (Hash[String, String], Array[String], String, String?, Numeric?, group: bool) -> [String, String, Process::Status, bool?]
75
+ def self.spawn(env, argv, cwd, input, timeout, group:)
76
+ options = { chdir: cwd } #: Hash[Symbol, untyped]
77
+ options[:pgroup] = true if group && groups?
78
+ Open3.popen3(env, *argv, **options) do |stdin, out, err, thread|
79
+ stdin.write(input.to_s)
80
+ stdin.close
81
+ readers = [Thread.new { out.read }, Thread.new { err.read }]
82
+ timed_out = timeout && !thread.join(timeout)
83
+ if timed_out
84
+ begin
85
+ Process.kill("TERM", group && groups? ? -thread.pid : thread.pid)
86
+ rescue Errno::ESRCH
87
+ nil
88
+ end
89
+ end
90
+ status = thread.value
91
+ [readers[0].value.to_s.force_encoding("UTF-8"), readers[1].value.to_s.force_encoding("UTF-8"), status, timed_out]
92
+ end
93
+ end
94
+
95
+ # `ended` when no process of the group still runs as the leader closed.
96
+ #: (Integer) -> String
97
+ def self.group_state(pid)
98
+ Process.kill(0, -pid)
99
+ "running"
100
+ rescue Errno::ESRCH, Errno::EPERM
101
+ "ended"
102
+ end
103
+
104
+ # The child's environment against the runner's: every name the step
105
+ # set, and a value only when it cannot be a credential.
106
+ #: (Hash[untyped, untyped]) -> Hash[Symbol, untyped]
107
+ def self.env_entry(env)
108
+ return { inherited: true } if env.empty?
109
+
110
+ added = {}
111
+ changed = {}
112
+ env.each do |name, value|
113
+ name = name.to_s
114
+ (ENV.key?(name) ? changed : added)[name] = shown_value(value.to_s)
115
+ end
116
+ { added: added, changed: changed, removed: [] }
117
+ end
118
+
119
+ #: (String) -> (String | Hash[Symbol, Integer])
120
+ def self.shown_value(value)
121
+ safe = (value.start_with?("/") && !value.match?(/[[:cntrl:]]/) && File.exist?(value)) || value.match?(/\A-?\d+\z/) || %w[true false].include?(value)
122
+ safe ? value : { hidden_bytes: value.bytesize }
123
+ end
124
+ end
125
+
126
+ # A directory's files as their identities, before and after something
127
+ # wrote there, and the difference as the record names it.
128
+ module FileWalk
129
+ SKIPPED = %w[node_modules .git .nukadoko].freeze
130
+ LIMIT = 20_000
131
+
132
+ #: (String) -> Hash[Symbol, untyped]
133
+ def self.snapshot(dir)
134
+ entries = {}
135
+ skipped = []
136
+ walk = lambda do |at, relative|
137
+ Dir.each_child(at) do |name|
138
+ path = File.join(at, name)
139
+ stat = File.lstat(path)
140
+ if stat.directory? && SKIPPED.include?(name)
141
+ skipped << "#{relative}#{name}/"
142
+ next
143
+ end
144
+ key = "#{relative}#{name}#{"/" if stat.directory?}"
145
+ entries[key] = [stat.size, stat.mtime.to_r, stat.ctime.to_r, stat.ino]
146
+ throw :too_many if entries.size > LIMIT
147
+
148
+ walk.(path, key) if stat.directory?
149
+ rescue Errno::ENOENT
150
+ nil
151
+ end
152
+ end
153
+ whole = catch(:too_many) do
154
+ walk.(dir, "")
155
+ true
156
+ end
157
+ return { unmeasured: "#{dir} holds more than #{LIMIT} entries" } unless whole
158
+
159
+ { entries: entries, skipped: skipped.sort }
160
+ rescue SystemCallError => e
161
+ { unmeasured: "#{dir} could not be read: #{e.message}" }
162
+ end
163
+
164
+ #: (Hash[Symbol, untyped], Hash[Symbol, untyped]) -> Hash[Symbol, untyped]
165
+ def self.difference(before, after)
166
+ return { unmeasured: before[:unmeasured] || after[:unmeasured] } if before[:unmeasured] || after[:unmeasured]
167
+
168
+ b = before[:entries]
169
+ a = after[:entries]
170
+ { added: (a.keys - b.keys).sort, changed: (a.keys & b.keys).reject { a[_1] == b[_1] || _1.end_with?("/") }.sort,
171
+ removed: (b.keys - a.keys).sort, **(after[:skipped].any? ? { skipped: after[:skipped] } : {}) }
172
+ end
41
173
  end
42
174
 
43
175
  # The `scratch` fixture: `dir` makes a fresh directory, and the engine
44
176
  # removes every one of them when the scenario ends, passed or failed.
45
177
  class Scratch
46
- def initialize
178
+ # `root` is what a relative `copy` source resolves against: the
179
+ # project's directory.
180
+ #: (?String) -> void
181
+ def initialize(root = Dir.pwd)
182
+ @root = root
47
183
  @dirs = []
48
184
  end
49
185
 
186
+ # A directory under the system's temporary directory, named
187
+ # `<prefix>-` and six characters, as the TypeScript engine names it.
188
+ #: (?String) -> String
50
189
  def dir(prefix = "nukadoko-scratch")
51
190
  raise ArgumentError, "a scratch prefix cannot hold a path separator: #{prefix}" if prefix.match?(%r{[/\\]})
52
191
 
53
- Dir.mktmpdir(prefix).tap { @dirs << _1 }
192
+ path = File.join(File.realpath(Dir.tmpdir), "#{prefix}-#{SecureRandom.alphanumeric(6)}")
193
+ Dir.mkdir(path, 0o700)
194
+ @dirs << path
195
+ path
196
+ rescue Errno::EEXIST
197
+ retry
198
+ end
199
+
200
+ # A fresh scratch directory holding a copy of `source`: a directory's
201
+ # contents, or a file under its own name. The source is read before
202
+ # the directory is made, so a missing one raises without leaving an
203
+ # empty directory in the step record.
204
+ #: (String) -> String
205
+ def copy(source)
206
+ from = File.expand_path(source, @root)
207
+ file = File.file?(from)
208
+ raise Errno::ENOENT, from unless file || File.directory?(from)
209
+
210
+ target = dir
211
+ FileUtils.cp_r(file ? from : File.join(from, "."), target)
212
+ target
54
213
  end
55
214
 
215
+ #: () -> Array[String]
56
216
  def dirs = @dirs.dup
57
217
 
218
+ FILE_TEXT = 8 * 1024
219
+ STEP_TEXT = 64 * 1024
220
+
221
+ # Each scratch directory's paths as identities, to compare a step's
222
+ # start with its end.
223
+ #: () -> Hash[String, Hash[Symbol, untyped]]
224
+ def snapshot = @dirs.to_h { [_1, FileWalk.snapshot(_1)] }
225
+
226
+ # What the step changed in the scratch directories, absolute and
227
+ # sorted, each file with its size and text after the step: a
228
+ # directory made during the step is compared with an empty one. The
229
+ # step reads at most 64 KiB of content in all, 8 KiB of each file.
230
+ #: (Hash[String, Hash[Symbol, untyped]]) -> Array[Hash[Symbol, untyped]]
231
+ def changes(before)
232
+ budget = STEP_TEXT
233
+ @dirs.flat_map do |dir|
234
+ after = FileWalk.snapshot(dir)
235
+ earlier = before.fetch(dir, { entries: {}, skipped: [] })
236
+ next [] if after[:unmeasured] || earlier[:unmeasured]
237
+
238
+ diff = FileWalk.difference(earlier, after)
239
+ root = dir.end_with?("/") ? dir : "#{dir}/"
240
+ own = before.key?(dir) ? [] : [{ path: root, change: "added" }]
241
+ own + %i[added changed removed].flat_map { |change| diff[change].map { [_1, change] } }.map do |relative, change|
242
+ path = "#{root}#{relative}"
243
+ next { path: path, change: change.to_s } if change == :removed || relative.end_with?("/")
244
+
245
+ size = File.size(path)
246
+ read = [size, FILE_TEXT, budget].min
247
+ budget -= read
248
+ bytes = File.binread(path, read).to_s
249
+ text = bytes.dup.force_encoding("UTF-8")
250
+ content = if read < [size, FILE_TEXT].min then { text: "", bytes: size, truncated: true }
251
+ elsif !text.valid_encoding? then { bytes: size, binary: true }
252
+ else { text: text, bytes: size, **(size > read ? { truncated: true } : {}) }
253
+ end
254
+ { path: path, change: change.to_s, bytes: size, content: content }
255
+ end
256
+ end.sort_by { _1[:path] }
257
+ end
258
+
259
+ #: () -> void
58
260
  def remove_all
59
261
  @dirs.each { FileUtils.rm_rf(_1) }
60
262
  end
@@ -0,0 +1,172 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ require "gherkin"
5
+ require "json"
6
+
7
+ # What one criterion is, and how `nuka run --base <ref>` finds the same
8
+ # criterion at the ref. A criterion is one pickle: a scenario, or one
9
+ # Examples row. Its identity is its feature file and its name. Its content
10
+ # is what a person approved: the steps in order (Background steps first),
11
+ # each with its effective keyword, text, docstring, and table; the
12
+ # Examples row; and the tags that decide where it must hold (condition
13
+ # tags, `@expects:` tags, and `@held`). Other tags and the name are not
14
+ # content, so a scenario renamed or tagged `@smoke` still says what it said,
15
+ # though a hook or a World could read them, so such a criterion keeps its
16
+ # change and is marked `retagged` or `renamed_from`, and runs in the old
17
+ # world as a changed mapping does.
18
+ #
19
+ # Matching follows the TypeScript engine's order: the same identity and
20
+ # content is unchanged; the same content under another identity, where it
21
+ # is the one answer (same file first, then anywhere), is unchanged and
22
+ # renamed; one left over per identity on each side is changed; the rest of
23
+ # head is new and the rest of the ref removed. Taking the first of several
24
+ # candidates would make the answer depend on reading order, so a tie is
25
+ # never paired.
26
+ module Nukadoko
27
+ module Engine
28
+ module Criteria
29
+ Criterion = Data.define(:feature, :line, :name, :content, :tags, :all_tags, :lines)
30
+
31
+ HELD = "@held"
32
+
33
+ module_function
34
+
35
+ #: (Array[String]) -> Array[String]
36
+ def content_tags(tags) = tags.select { _1 == HELD || _1.match?(/\A@(with|without|expects):/) }.uniq.sort
37
+
38
+ # The criteria of each feature file under `root` that `paths` names,
39
+ # relative to it. A file that does not parse is returned apart, with
40
+ # why, since its criteria cannot be compared.
41
+ #: (String, Array[String]) -> [Array[Criterion], Array[Hash[Symbol, untyped]]]
42
+ def of_files(root, paths)
43
+ criteria = []
44
+ unparsed = []
45
+ paths.each do |path|
46
+ envelopes = Dir.chdir(root) { Gherkin.from_paths([path], include_source: false, include_gherkin_document: true, include_pickles: true).to_a }
47
+ errors = envelopes.filter_map { _1.parse_error&.message }
48
+ next unparsed << { feature: path, message: errors.first } if errors.any?
49
+
50
+ document = envelopes.find(&:gherkin_document)&.gherkin_document
51
+ pickles = envelopes.filter_map(&:pickle)
52
+ criteria.concat(of_feature(path, document, pickles)) if document
53
+ end
54
+ [criteria, unparsed]
55
+ end
56
+
57
+ #: (String, untyped, Array[untyped]) -> Array[Criterion]
58
+ def of_feature(feature, document, pickles)
59
+ places = places_of(document)
60
+ rows = {}
61
+ places.each_value do |place|
62
+ place[:scenario].examples.each do |examples|
63
+ examples.table_body.each { |row| rows[row.id] = { header: examples.table_header, row: row } }
64
+ end
65
+ end
66
+ pickles.filter_map do |pickle|
67
+ scenario_id, row_id = pickle.ast_node_ids
68
+ place = places[scenario_id] or next
69
+ example = row_id && rows[row_id]
70
+ values = ->(row) { row ? row.cells.map(&:value) : [] }
71
+ tags = content_tags(pickle.tags.map(&:name))
72
+ content = JSON.generate(
73
+ steps: pickle.steps.map do |step|
74
+ doc = step.argument&.doc_string
75
+ table = step.argument&.data_table
76
+ { keyword: step.type || "Unknown", text: step.text,
77
+ docString: doc && { mediaType: doc.media_type, content: doc.content },
78
+ rows: table&.rows&.map { |row| row.cells.map(&:value) } }
79
+ end,
80
+ example: example && { header: values.(example[:header]), row: values.(example[:row]) },
81
+ tags: tags
82
+ )
83
+ lines = [*([tags.join(" ")] unless tags.empty?),
84
+ *place[:backgrounds].flat_map { |background| background.steps.flat_map { step_lines(_1) } },
85
+ *place[:scenario].steps.flat_map { step_lines(_1) },
86
+ *(example ? [*(row_line(example[:header]) if example[:header]), row_line(example[:row])] : [])]
87
+ Criterion.new(feature, pickle.location&.line || 0, pickle.name, content, tags, pickle.tags.map(&:name).uniq.sort, lines)
88
+ end
89
+ end
90
+
91
+ #: (untyped) -> Hash[String, Hash[Symbol, untyped]]
92
+ def places_of(document)
93
+ places = {}
94
+ feature = document.feature or return places
95
+ backgrounds = feature.children.filter_map(&:background)
96
+ feature.children.each do |child|
97
+ places[child.scenario.id] = { backgrounds: backgrounds, scenario: child.scenario } if child.scenario
98
+ next unless child.rule
99
+
100
+ inner = [*backgrounds, *child.rule.children.filter_map(&:background)]
101
+ child.rule.children.each { places[_1.scenario.id] = { backgrounds: inner, scenario: _1.scenario } if _1.scenario }
102
+ end
103
+ places
104
+ end
105
+
106
+ #: (untyped) -> String
107
+ def row_line(row) = "| #{row.cells.map { _1.value.gsub("\\", "\\\\\\\\").gsub("|", "\\|") }.join(" | ")} |"
108
+
109
+ #: (untyped) -> Array[String]
110
+ def step_lines(step)
111
+ lines = ["#{step.keyword.strip} #{step.text}"]
112
+ if (doc = step.doc_string)
113
+ lines.push("#{doc.delimiter}#{doc.media_type}", *doc.content.split("\n", -1), doc.delimiter)
114
+ end
115
+ step.data_table&.rows&.each { lines << row_line(_1) }
116
+ lines
117
+ end
118
+
119
+ #: (Criterion) -> [untyped, untyped]
120
+ def identity(criterion) = [criterion.feature, criterion.name]
121
+
122
+ #: (String, Integer) -> [String, Integer]
123
+ def key(feature, line) = [feature, line]
124
+
125
+ # Each head criterion's change, by `key`, and the ref's criteria that
126
+ # head no longer has.
127
+ #: (Array[Criterion], Array[Criterion]) -> Hash[Symbol, untyped]
128
+ def compare(base, head)
129
+ changes = {}
130
+ unmatched = base.dup
131
+ take = lambda do |found, criterion, renamed|
132
+ at = unmatched.index { _1.equal?(found) } #: Integer
133
+ unmatched.delete_at(at)
134
+ change = { change: "unchanged", at: { feature: found.feature, line: found.line } } #: Hash[Symbol, untyped]
135
+ change[:renamed_from] = { feature: found.feature, name: found.name } if renamed
136
+ change[:retagged] = true if found.all_tags != criterion.all_tags
137
+ changes[key(criterion.feature, criterion.line)] = change
138
+ end
139
+ left = head.reject do |criterion|
140
+ found = unmatched.find { identity(_1) == identity(criterion) && _1.content == criterion.content }
141
+ take.(found, criterion, false) if found
142
+ found
143
+ end
144
+ [true, false].each do |same_file|
145
+ candidates = left.to_h do |criterion|
146
+ [criterion, unmatched.select { _1.content == criterion.content && (!same_file || _1.feature == criterion.feature) }]
147
+ end
148
+ claimants = Hash.new(0).compare_by_identity
149
+ candidates.each_value { |list| list.each { claimants[_1] += 1 } }
150
+ left = left.reject do |criterion|
151
+ list = candidates[criterion]
152
+ next false unless list.size == 1 && claimants[list.first] == 1
153
+
154
+ take.(list.first, criterion, true)
155
+ true
156
+ end
157
+ end
158
+ before = unmatched.group_by { identity(_1) }
159
+ left.group_by { identity(_1) }.each do |id, group|
160
+ earlier = before.fetch(id, [])
161
+ paired = group.size == 1 && earlier.size == 1
162
+ if paired
163
+ at = unmatched.index { _1.equal?(earlier.first) } #: Integer
164
+ unmatched.delete_at(at)
165
+ end
166
+ group.each { changes[key(_1.feature, _1.line)] = { change: paired ? "changed" : "new" } }
167
+ end
168
+ { changes: changes, removed: base.select { |criterion| unmatched.any? { _1.equal?(criterion) } } }
169
+ end
170
+ end
171
+ end
172
+ end
@@ -1,67 +1,59 @@
1
1
  # frozen_string_literal: true
2
+ # rbs_inline: enabled
2
3
 
3
4
  # What the TypeScript engine's defineStep refuses when a step file loads:
4
5
  # a claim or a poll that could only be judged one way, or that would let a
5
6
  # line fill the value a claim measures. The Ruby engine reads the same
6
- # declarations after loading, and check reports each as the TypeScript
7
- # engine does, as step-file-import-failed, so the step leaves the vocabulary.
7
+ # declarations after loading, and check reports the first as the
8
+ # TypeScript engine does, as step-file-import-failed, so the step leaves
9
+ # the vocabulary.
8
10
  module Nukadoko
9
11
  module Engine
10
12
  class Definition
13
+ # setTimeout's own limit, which a poll's timeout cannot pass.
14
+ MAX_TIMEOUT_MS = 2_147_483_647
15
+
16
+ #: (singleton(Step)) -> void
11
17
  def initialize(step)
12
18
  @step = step
13
- @from = step.from.keys
14
- @captures = step.pattern ? Pattern.new(step.pattern).keys : []
15
- @args = step.args.fields.map { _1.name.to_s }
16
- @observe = step.method_defined?(:observe)
19
+ @observe = step.method_defined?(:observe) #: bool
17
20
  end
18
21
 
22
+ #: () -> Array[String]
19
23
  def problems
20
- return [] unless @step.claims
24
+ claims = @step.claims
25
+ return [] unless claims
21
26
 
22
- claim_problems + poll_problems
27
+ problem = ClaimRules.first_problem(claims, shape) || poll_problem
28
+ # Named by the class, as the TypeScript engine names its defineStep call.
29
+ problem ? ["#{@step.name} #{problem}."] : []
23
30
  end
24
31
 
25
32
  private
26
33
 
27
- def claim_problems
28
- @step.claims.each_with_index.flat_map do |claim, i|
29
- label = "claims[#{i}]"
30
- actual_problems(label, claim) + expected_problems(label, claim)
31
- end
32
- end
33
-
34
- def actual_problems(label, claim)
35
- head = claim[:actual].to_s.split(".").first
36
- from = @from.include?(head)
37
- if !from && !@observe
38
- [%(#{label}.actual starts with "#{head}", which is not a key of this step's from, and the step has no observe to read it)]
39
- elsif from && @captures.include?(head)
40
- [%(#{label}.actual starts with "#{head}", which a pattern captures, so a line would fill the value the claim measures. Take it out of the pattern, so an earlier step fills it)]
41
- elsif !from && @args.include?(head)
42
- [%(#{label}.actual starts with "#{head}", an args key the sentence fills. A claim's actual is a value an earlier step returned (a from key) or one observe read)]
43
- else []
44
- end
34
+ #: () -> ClaimRules::Shape
35
+ def shape
36
+ fields = @step.args.fields
37
+ ClaimRules::Shape.new(
38
+ patterns: [@step.pattern].compact, args_keys: fields.map { _1.name.to_s },
39
+ string_args: fields.select { _1.type == :string }.map { _1.name.to_s },
40
+ from_keys: @step.from.keys.map(&:to_s), capture_keys: @step.pattern ? Pattern.new(@step.pattern).keys : [],
41
+ observe: @observe
42
+ )
45
43
  end
46
44
 
47
- def expected_problems(label, claim)
48
- key = claim[:expected].is_a?(Hash) && claim[:expected][:from]&.to_s&.split(".")&.first
49
- return [] unless key
50
- return [%(#{label}.expected.from starts with "#{key}", which is not a key of this step's from)] unless @from.include?(key)
51
- return [%(#{label}.expected.from starts with "#{key}", which a pattern captures, so a line fills it and no earlier step does)] if @captures.include?(key)
52
-
53
- []
54
- end
55
-
56
- def poll_problems
45
+ #: () -> String?
46
+ def poll_problem
57
47
  poll = @step.poll
58
- return [] if poll.nil? || poll == false
59
- unless poll.is_a?(Hash) && (poll.keys - %i[timeout_ms settled]).empty? && poll[:timeout_ms].is_a?(Numeric) && poll[:timeout_ms].positive?
60
- return ["poll must be false or { timeout_ms, settled? } with a number of milliseconds greater than 0; got #{poll.inspect}"]
48
+ return nil if poll.nil? || poll == false
49
+
50
+ timeout = poll.is_a?(Hash) ? poll[:timeout_ms] : nil
51
+ unless poll.is_a?(Hash) && (poll.keys - %i[timeout_ms settled]).empty? && timeout.is_a?(Numeric) && (!timeout.is_a?(Float) || timeout.finite?) && timeout.positive? && timeout <= MAX_TIMEOUT_MS
52
+ return "poll must be false or { timeout_ms, settled? } with a number of milliseconds greater than 0 and at most #{MAX_TIMEOUT_MS}; got #{ClaimRules.describe(poll)}"
61
53
  end
62
- return ["poll re-runs observe, and the step has no observe. Values from earlier steps do not change between readings"] unless @observe
54
+ return "poll re-runs observe, and the step has no observe. Values from earlier steps do not change between readings" unless @observe
63
55
 
64
- []
56
+ nil
65
57
  end
66
58
  end
67
59
  end
@@ -0,0 +1,88 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ # What `nuka check` says about the env files the config and the program
5
+ # name, as the TypeScript engine says it. A missing file is a warning, since
6
+ # a run reads it as empty; a line that loads nothing, and a `secrets` key
7
+ # that reaches nothing, are warnings too. None of it prints a value: the
8
+ # files hold secrets. The one guess here, whether a key's name looks like a
9
+ # secret, decides only a warning and never what is redacted.
10
+ module Nukadoko
11
+ module Engine
12
+ module EnvCheck
13
+ # `KEY` counts only as a whole underscore-delimited word, so MONKEY,
14
+ # KEYWORD, and APIKEY are not guessed to be secrets.
15
+ SECRET_LOOKING = /SECRET|PASSWORD|TOKEN|CREDENTIAL|(?:^|_)KEY(?:_|$)/i
16
+
17
+ # A key in both lists is two opposite instructions, so the config is
18
+ # refused before anything reads it.
19
+ #: () -> void
20
+ def self.validate!
21
+ both = keys(:public) & keys(:redact)
22
+ return if both.empty?
23
+
24
+ raise Refusal.new("config-invalid",
25
+ %(#{CONFIG} is invalid: secrets.public and secrets.redact both name "#{both.first}": that is two opposite instructions (demote vs. promote) for the same key; remove it from one of the two lists.))
26
+ end
27
+
28
+ #: (Symbol) -> Array[String]
29
+ def self.keys(list) = (Nukadoko.config_options.dig(:secrets, list) || []).map(&:to_s)
30
+
31
+ #: (String) -> Array[Finding]
32
+ def self.findings(project)
33
+ config_files = (Nukadoko.config_options[:envFiles] || []).map(&:to_s)
34
+ environments = (Nukadoko.program_options[:environments] || {}).to_h { |name, e| [name.to_s, (e[:envFiles] || []).map(&:to_s)] }
35
+ all = config_files + environments.values.flatten
36
+ exists = ->(path) { File.exist?(File.join(project, path)) }
37
+ found = config_files.reject(&exists).map do |path|
38
+ warning("env-file-missing", path, %(envFile "#{path}" does not exist), %(Create #{path}, or remove "#{path}" from envFiles in #{CONFIG}.))
39
+ end
40
+ environments.each do |name, paths|
41
+ paths.reject(&exists).each do |path|
42
+ found << warning("environment-env-file-missing", path, %(environments.#{name}.envFiles names "#{path}", which does not exist),
43
+ %(Create #{path}, or remove "#{path}" from environments.#{name}.envFiles in #{CONFIG}.))
44
+ end
45
+ end
46
+ defined = EnvFile.load(project, all)
47
+ all.uniq.each do |path|
48
+ content = readable(project, path) or next
49
+ EnvFile.skipped_lines(content).each do |line|
50
+ found << Finding.new("warning", "env-file-skipped-line", path, line, nil, %(envFile "#{path}" line #{line} was skipped, so nothing on it was loaded),
51
+ Codes.fix("env-file-skipped-line"), nil)
52
+ end
53
+ end
54
+ keys(:public).reject { defined.key?(_1) }.each do |key|
55
+ found << warning("secrets-public-key-unknown", CONFIG, %(secrets.public names "#{key}", which is not defined in any configured envFile))
56
+ end
57
+ keys(:redact).each do |key|
58
+ if !defined.key?(key)
59
+ found << warning("secrets-redact-key-unknown", CONFIG, %(secrets.redact names "#{key}", which is not defined in any configured envFile))
60
+ elsif defined.fetch(key).length < Secrets::MIN_LENGTH
61
+ found << warning("secrets-redact-key-too-short", CONFIG,
62
+ %(secrets.redact names "#{key}", but its value is shorter than #{Secrets::MIN_LENGTH} characters, so nukadoko never redacts it))
63
+ end
64
+ end
65
+ Secrets.classify(project, all)[:tracked].each do |path|
66
+ content = readable(project, path) or next
67
+ EnvFile.parse(content).each_key do |key|
68
+ next if keys(:redact).include?(key) || !key.match?(SECRET_LOOKING)
69
+
70
+ found << warning("tracked-secret-looking-key", path,
71
+ %("#{key}" in "#{path}" looks like a secret by name, but that file is tracked by git so its value is not redacted; add "#{key}" to secrets.redact if it should be))
72
+ end
73
+ end
74
+ found
75
+ end
76
+
77
+ #: (String, String, String, ?String?) -> Finding
78
+ def self.warning(code, file, message, fix = nil) = Finding.new("warning", code, file, nil, nil, message, fix || Codes.fix(code), nil)
79
+
80
+ #: (String, String) -> String?
81
+ def self.readable(project, path)
82
+ File.read(File.join(project, path), encoding: "UTF-8")
83
+ rescue SystemCallError
84
+ nil
85
+ end
86
+ end
87
+ end
88
+ end