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
data/lib/nukadoko/cli.rb CHANGED
@@ -1,26 +1,116 @@
1
1
  # frozen_string_literal: true
2
+ # rbs_inline: enabled
2
3
 
3
4
  # The `nuka` command. With --json it prints one envelope in the shape the
4
5
  # TypeScript engine prints, so an agent reads both engines the same way.
5
6
  module Nukadoko
6
7
  class CLI
8
+ FLAGS = %w[--json --no-check --dry-run --then --replace --allure --records --meets --misses --step].freeze
9
+ REPEATED = %w[--tag --env --use].freeze
10
+ VALUED = %w[--format --out --base --repeat --concurrency --order --proof-runs --args --pattern --description --feature --command --request --from --cwd --body --argv
11
+ --run --by --because --walk --timeout].freeze
12
+
13
+ #: (Array[String], ?project: String, ?out: IO) -> void
7
14
  def initialize(argv, project: Dir.pwd, out: $stdout)
8
15
  @command, *rest = argv
9
- @json = rest.delete("--json")
10
- @no_check = rest.delete("--no-check")
11
- @rest = rest
16
+ @words = rest.dup
17
+ @options = Hash.new { |h, k| h[k] = [] }
18
+ @rest = []
19
+ @unknown = []
20
+ parse(rest)
21
+ @json = @options.key?("--json")
22
+ @no_check = @options.key?("--no-check")
12
23
  @project = File.expand_path(project)
13
24
  @out = out
14
25
  end
15
26
 
27
+ # The commands by what a user reaches them for, in the TypeScript
28
+ # engine's words, so `nuka --help` reads the same in both.
29
+ HELP = <<~TEXT
30
+ nuka <command>
31
+
32
+ Everyday:
33
+ nuka init set up a project; ends with a self-check
34
+ nuka scaffold [name] typed step template that fails until implemented
35
+ nuka check [feature..] static checks: pattern/schema mismatches, claim steps
36
+ and where they are bound, undefined steps per feature,
37
+ duplicate patterns, config coherence, and notes on
38
+ unused declarations
39
+ nuka run [feature..] check, then execute scenarios from a feature file or a
40
+ directory of them (features/ when none is given);
41
+ step records + run.json
42
+ nuka report [run] render a finished run as Markdown, Allure results, or
43
+ a cucumber-messages stream, from its run directory
44
+ alone
45
+ nuka verdict say whether the newest run judged the working tree as
46
+ it is now and left nothing red; exits 1 when it did
47
+ not, and never starts a run
48
+ nuka judge <target> show the values a run read for a criterion whose Then
49
+ asks for a judgment (<feature file>:<scenario line>),
50
+ or record a judgment of them with --meets or --misses
51
+ nuka steps list the whole vocabulary: name, patterns,
52
+ description, mutates
53
+ nuka describe <name> full contract, schemas as JSON Schema
54
+
55
+ Exploring:
56
+ nuka do <name> execute one typed step; step record to stdout
57
+ nuka step follow and answer a walk of nuka run --step, one pause
58
+ at a time
59
+
60
+ Upkeep:
61
+ nuka clean delete accumulated runs, do records, and what nuka
62
+ report wrote under export/, in the state directory
63
+ nuka skill path the agent-facing skills' source directory
64
+ nuka sig write sig/nukadoko/steps.rbs, the RBS of each step's
65
+ args and returns, for Steep
66
+
67
+ Options:
68
+ --version Show version number
69
+ --help Show help
70
+
71
+ An agent starts at the llms.txt in the gem's directory, the one above what
72
+ nuka skill path prints: the loop, every command, and every finding code.
73
+ Its Ruby section is how a Ruby step and the project files are written.
74
+ TEXT
75
+ COMMANDS = %w[init scaffold check run report verdict judge steps describe do step clean skill sig __tree].freeze
76
+
77
+ #: () -> Integer
16
78
  def call
79
+ if @command == "--help"
80
+ @out.write(HELP)
81
+ return 0
82
+ end
83
+ if @command == "--version"
84
+ @out.puts VERSION
85
+ return 0
86
+ end
87
+ unless COMMANDS.include?(@command)
88
+ @out = $stderr
89
+ message = @command.nil? ? "Not enough non-option arguments: got 0, need at least 1" : "Unknown argument: #{@command}"
90
+ return refuse(Engine::Refusal.new("invalid-arguments", message, run: "nuka --help"))
91
+ end
92
+ return refuse(Engine::Refusal.new("invalid-arguments", "Unknown argument: #{@unknown.first}")) if @unknown.any?
93
+ return verdict if @command == "verdict"
94
+ return Judge.new(@project, @rest, @options, json: @json, out: @out).call if @command == "judge"
95
+ return report if @command == "report"
96
+ return clean if @command == "clean"
97
+ return Walked.new(@project, @rest, @options, json: @json, out: @out).call if @command == "step"
98
+ return skill if @command == "skill"
99
+ return init if @command == "init"
100
+
17
101
  %w[nukadoko.config.rb nukadoko.program.rb].each do |name|
18
102
  file = File.join(@project, name)
19
103
  load file if File.exist?(file)
20
104
  end
21
105
  steps = Nukadoko.load_steps(File.join(@project, "features", "steps"))
22
- scenarios = Dir.chdir(@project) { Engine.load_features("features") }
23
- check = Engine::Check.new(steps, scenarios)
106
+ problems = []
107
+ scenarios = Dir.chdir(@project) { Engine.load_features("features", problems: problems) }
108
+ declared = (Nukadoko.program_options[:environments] || {}).values.flat_map { (_1[:conditions] || {}).keys.map(&:to_s) }
109
+ # condition-unmet is judged for the selection a run without --env
110
+ # starts; a selection --env names is a choice of where to run.
111
+ selected = (Engine::Program.new(Nukadoko.program_options).environments if Array(@options["--env"]).empty?) rescue nil
112
+ check = Engine::Check.new(steps, scenarios, features: Dir.exist?(File.join(@project, "features")), full: @command == "check",
113
+ conditions: declared, environments: selected, problems: problems, config: env_findings)
24
114
  findings = check.findings.map { relative(_1).to_h }
25
115
  case @command
26
116
  when "check" then finish("check", check.passed?, findings: findings)
@@ -45,32 +135,725 @@ module Nukadoko
45
135
  end
46
136
 
47
137
  finish("describe", true, findings: findings, **Vocabulary.describe(step, @project))
48
- when "run"
49
- return finish("run", false, findings: findings) unless @no_check || check.passed?
50
-
51
- result = Engine::Run.new(@project, check.usable, scenarios, Nukadoko.program_options, out: @json ? $stderr : @out).call
52
- passed = result.delete(:passed)
53
- finish("run", passed, findings: findings, **result)
138
+ when "run" then @options.key?("--step") ? walk(steps) : run(steps)
139
+ when "do" then run_one(check)
140
+ when "scaffold" then scaffold(steps, scenarios)
141
+ when "__tree" then tree(steps)
54
142
  else
55
- warn "usage: nuka check|run|steps|describe <step>|sig [--json] [--no-check]"
56
- 2
143
+ raise "unreachable: #{@command} is in COMMANDS but has no branch"
57
144
  end
58
145
  end
59
146
 
60
147
  private
61
148
 
149
+ # `--name value` and `--name=value` for the repeated options, bare
150
+ # flags, and every other word a target. An unknown `--name` is kept to
151
+ # refuse, so a typo never reads as a target or is silently ignored.
152
+ #: (Array[String]) -> void
153
+ def parse(words)
154
+ until words.empty?
155
+ word = words.shift
156
+ name, value = word.split("=", 2)
157
+ name = name.to_s
158
+ if REPEATED.include?(name) || VALUED.include?(name)
159
+ # `--command` alone leaves the entry point a TODO, so a flag after
160
+ # it is the next option, not its value.
161
+ value ||= "" if name == "--command" && (words.empty? || words.first.start_with?("--"))
162
+ @command_before_name = @rest.empty? if name == "--command" && !word.include?("=")
163
+ value ||= words.shift
164
+ next @unknown << name.delete_prefix("--") if value.nil?
165
+
166
+ @options[name] << value
167
+ elsif FLAGS.include?(word) then @options[word]
168
+ elsif word.start_with?("--") then @unknown << name.delete_prefix("--")
169
+ else @rest << word
170
+ end
171
+ end
172
+ end
173
+
174
+ # `nuka run --step`: a run of one scenario that pauses after each step
175
+ # until `nuka step` answers. The walk is recorded before anything else,
176
+ # so every way the run stops reaches a `nuka step` waiting for it: a
177
+ # refusal or nothing selected ends it as not run, with what the run
178
+ # printed; a signal, which is what ends a pause nobody answers, as
179
+ # interrupted; an exception as an error.
180
+ #: (Array[singleton(Step)]) -> Integer
181
+ def walk(steps)
182
+ targets = @rest.empty? ? ["features"] : @rest
183
+ @walk_target = [*targets, *@options["--env"].flat_map { ["--env", _1] }].map { Engine::Selection.shell_word(_1) }.join(" ")
184
+ opened = Engine::WalkFiles.open(@project, @walk_target, announce: @json ? nil : ->(text) { $stderr.write(text) })
185
+ if opened.is_a?(Hash)
186
+ return refuse(Engine::Refusal.new("walk-in-progress", opened[:message], run: "nuka step wait"))
187
+ end
188
+
189
+ @walk = opened
190
+ previous = { "INT" => 130, "TERM" => 143 }.to_h do |name, code|
191
+ [name, Signal.trap(name) do
192
+ opened.end({ how: "interrupted", exit_code: code, signal: "SIG#{name}" })
193
+ exit(code)
194
+ end]
195
+ end
196
+ code = run(steps)
197
+ opened.end({ how: "not-run", exit_code: code, findings: @stopped_with || [] })
198
+ code
199
+ rescue StandardError => e
200
+ opened.end({ how: "error", exit_code: 1, findings: [{ severity: "error", code: "unexpected-error", message: e.message }] }) if opened.is_a?(Engine::WalkFiles::Handle)
201
+ raise
202
+ ensure
203
+ previous&.each { |name, handler| Signal.trap(name, handler || "DEFAULT") }
204
+ end
205
+
206
+ # Why a walk cannot walk this run, raised as step-needs-one-scenario: a
207
+ # walk is one execution of one scenario, in one environment, where its
208
+ # conditions hold, since a control would run again for its proof.
209
+ #: (Array[Engine::Scenario], Array[Engine::Environment]) -> void
210
+ def one_execution(kept, environments)
211
+ first = kept.first
212
+ at = Engine::Selection.shell_word("#{first.uri}:#{first.line}")
213
+ envs = @options["--env"].flat_map { ["--env", Engine::Selection.shell_word(_1)] }
214
+ reason, again = if kept.size > 1
215
+ ["the targets select #{kept.size} scenarios", Engine::Walk.restart_command([at, *envs].join(" "))]
216
+ elsif environments.size > 1
217
+ ["it runs in #{environments.size} environments (#{environments.map(&:name).join(", ")})",
218
+ Engine::Walk.restart_command([at, "--env", Engine::Selection.shell_word(environments.first.name)].join(" "))]
219
+ elsif Engine::Table.role(Engine::Table.condition_tags(first.tags), environments.first.conditions) == "control"
220
+ ["the scenario's conditions do not hold in #{environments.first.name}, so it would run as a control"]
221
+ end
222
+ return unless reason
223
+
224
+ raise Engine::Refusal.new("step-needs-one-scenario", "nuka run --step walks one execution of one scenario, and #{reason}", run: again)
225
+ end
226
+
227
+ # A run checks the scenarios it selected, then runs them in each world
228
+ # it selected; a target or a world it cannot reach is refused first.
229
+ #: (Array[singleton(Step)]) -> Integer
230
+ def run(steps)
231
+ repeat = count_flag("--repeat")
232
+ concurrency = count_flag("--concurrency")
233
+ Engine::Table.proof_runs = count_flag("--proof-runs")
234
+ order = Engine::Order.read(@options["--order"].last)
235
+ unless order
236
+ raise Engine::Refusal.new("invalid-value", "--order must be file, shuffled, or shuffled:<seed> with a whole number from 0 to #{Engine::Order::MAX_SEED} (got #{JSON.generate(@options["--order"].last)}).")
237
+ end
238
+
239
+ # Progress is stderr's, so stdout holds only what was asked for: the
240
+ # records under --records, the envelope under --json. Under --json
241
+ # nothing else is written, and a warning is a finding in the envelope.
242
+ records = @options.key?("--records") ? @out : nil
243
+ progress = @json ? File.open(File::NULL, "w") : $stderr
244
+ ref = @options["--base"].last
245
+ if @walk && (repeat > 1 || ref)
246
+ why = repeat > 1 ? "--repeat #{repeat} runs it #{repeat} times" : "--base runs it in more than one world"
247
+ raise Engine::Refusal.new("step-needs-one-scenario", "nuka run --step walks one execution of one scenario, and #{why}",
248
+ run: Engine::Walk.restart_command(@walk_target))
249
+ end
250
+ commit = ref && Engine::Base.resolve(@project, ref)
251
+ selection = Engine::Selection.new(@project, @rest, @options["--tag"])
252
+ program = Engine::Program.new(Nukadoko.program_options)
253
+ environments = program.environments(@options["--env"])
254
+ # A scenario whose conditions hold in no environment of the run is
255
+ # left out, and counted, since no cell of it could show it holds.
256
+ kept, left_out = selection.scenarios.partition { meets?(_1, environments) }
257
+ kept = Engine::Order.arrange(kept, order)
258
+ # Without --env, a scenario no environment meets is a check error,
259
+ # condition-unmet; a selection --env names leaves it out instead.
260
+ default = @options["--env"].empty?
261
+ declared = program.declared.values.flat_map { (_1[:conditions] || {}).keys.map(&:to_s) }
262
+ check = Engine::Check.new(steps, default ? selection.scenarios : kept, conditions: declared,
263
+ environments: (environments if default), problems: selection.problems, config: env_findings)
264
+ # Only the check's errors hold a run back, so only they are reported.
265
+ findings = @no_check ? [] : check.findings.map { relative(_1).to_h }.select { _1[:severity] == "error" }
266
+ unless @no_check || check.passed?
267
+ errors = findings.select { _1[:severity] == "error" }
268
+ stop = { severity: "refused", code: "check-errors",
269
+ message: "nuka run did not start: nuka check reports #{errors.size} #{errors.size == 1 ? "error" : "errors"} for these scenarios",
270
+ fix: "Correct each error the findings name, or pass --no-check to run anyway.", do: check_command }
271
+ return finish("run", false, findings: errors + [stop], verdict: "refused", exit_code: 2)
272
+ end
273
+ if kept.empty? && left_out.any?
274
+ return finish("run", false, findings: [left_out_stop(left_out, program)], verdict: "failed", exit_code: 1)
275
+ end
276
+ one_execution(kept, environments) if @walk && kept.any?
277
+
278
+ dir = File.join(@project, ".nukadoko", "runs", "run-#{Time.now.utc.strftime("%Y%m%d-%H%M%S")}-#{SecureRandom.alphanumeric(4).downcase}")
279
+ base = if commit
280
+ targets = @rest.empty? ? nil : @rest.map { _1.sub(/:\d+\z/, "") }
281
+ Engine::Base.new(project: @project, ref: ref, commit: commit, run_dir: dir, selected: kept.map { Engine::Criteria.key(_1.uri, _1.line) },
282
+ targets: targets, envs: @options["--env"], head_program: Nukadoko.program_options)
283
+ end
284
+ # Workers are handed whole feature files, so one file has nothing to
285
+ # spread across them.
286
+ if concurrency > 1 && kept.map(&:uri).uniq.size <= 1
287
+ progress.puts "--concurrency has nothing to distribute: this run selects one feature file."
288
+ concurrency = 1
289
+ end
290
+ result = Engine::Run.new(@project, check.usable, kept, Nukadoko.program_options,
291
+ environments: environments, left_out: left_out.size, out: progress,
292
+ dir: dir, base: base, env_flags: @options["--env"].flat_map { ["--env", _1] },
293
+ repeat: repeat, concurrency: concurrency, order: order, records: records, walk: @walk,
294
+ rerun: { targets: @rest, tags: @options["--tag"].flat_map { ["--tag", _1] }, whole_files: selection.whole_files }).call
295
+ passed = result.delete(:passed)
296
+ findings += result.delete(:failures)
297
+ started = result.slice(:run_id, :run_dir, :started_at, :finished_at, :commit, :environments, :worlds)
298
+ rest = result.except(*started.keys)
299
+ envelope = { **head("run", passed ? "passed" : "failed", findings, check: @no_check ? "skipped" : "ran"),
300
+ **started, selection: selection.selection, tag_selection: selection.tag_selection, **rest } #: Hash[Symbol, untyped]
301
+ envelope.delete(:tag_selection) unless envelope[:tag_selection]
302
+ # The limits restate the fields above, so they are read from them,
303
+ # and a run with none has no field.
304
+ limits = Engine::Summary.limits(JSON.parse(JSON.generate(envelope), symbolize_names: true))
305
+ envelope[:limits] = limits if limits.any?
306
+ File.write(File.join(@project, result[:run_dir], "run.json"), "#{JSON.pretty_generate(envelope)}\n")
307
+ # The summary is rendered from run.json as written, so it can say
308
+ # nothing the record does not.
309
+ written = JSON.parse(JSON.generate(envelope), symbolize_names: true)
310
+ File.write(File.join(@project, result[:run_dir], "summary.md"), Engine::Summary.render(written))
311
+ # After run.json, so a `nuka step` that reads the walk as ended finds
312
+ # the run's record there.
313
+ scenarios = envelope[:scenarios] #: Array[Hash[Symbol, untyped]]
314
+ stopped = scenarios.find { _1[:stopped] }&.dig(:stopped)
315
+ @walk&.end({ how: "finished", exit_code: passed ? 0 : 1, findings: findings, **(stopped ? { stopped: stopped } : {}) })
316
+ unless @json
317
+ written = Dir.children(File.join(@project, result[:run_dir], "steps")).size
318
+ steps_dir = "#{File.join(result[:run_dir], "steps")}/"
319
+ progress.puts "steps #{steps_dir.ljust([30, steps_dir.size + 2].max)}#{written}" if envelope[:counts][:scenarios].positive?
320
+ progress.puts "summary #{File.join(result[:run_dir], "summary.md")}"
321
+ progress.puts "run #{File.join(result[:run_dir], "run.json")}"
322
+ run_end(envelope, progress)
323
+ end
324
+ emit(envelope, findings, "run", io: progress)
325
+ if limits.any? && !@json
326
+ progress.puts "limits: #{limits.group_by { _1[:kind] }.map { |kind, group| "#{group.size} #{kind}" }.join(", ")} (run.json limits)"
327
+ end
328
+ repeat_tallies(scenarios, progress) if repeat > 1 && !@json
329
+ passed ? 0 : 1
330
+ rescue Engine::Refusal => e
331
+ refuse(e)
332
+ end
333
+
334
+ # `--repeat`, `--concurrency`, and `--proof-runs` take a whole number of 1 or more.
335
+ #: (String) -> Integer
336
+ def count_flag(name)
337
+ value = @options[name].last
338
+ return 1 if value.nil? && name != "--proof-runs"
339
+ return Engine::Table::PROOF_RUNS if value.nil?
340
+
341
+ number = Integer(value, 10, exception: false)
342
+ return number if number && number >= 1
343
+
344
+ raise Engine::Refusal.new("invalid-value", "#{name} must be a whole number of 1 or more (got #{value}).")
345
+ end
346
+
347
+ # One pass of a `--base` tree, in the tree's own directory: the plan
348
+ # names the world, the environment, and the rows at their place in this
349
+ # tree, and the result goes to the file it names.
350
+ #: (Array[singleton(Step)]) -> Integer
351
+ def tree(steps)
352
+ plan = JSON.parse(File.read(@rest.first), symbolize_names: true)
353
+ found = Dir.chdir(@project) { Engine.load_features(plan[:targets].map { _1[:feature] }.uniq) }
354
+ scenarios = plan[:targets].filter_map { |target| found.find { _1.uri == target[:feature] && _1.line == target[:line] } }
355
+ result = begin
356
+ environment = Engine::Program.new(Nukadoko.program_options).environments([plan[:environment]]).first
357
+ usable = Engine::Check.new(steps, scenarios).usable
358
+ run = Engine::Run.new(@project, usable, scenarios, Nukadoko.program_options, environments: [environment],
359
+ world: plan[:world], dir: plan[:dir], out: @out)
360
+ { results: run.tree_pass, worlds: run.world_entries }
361
+ rescue Engine::Refusal => e
362
+ { not_run: "the #{plan[:world]} tree's program file does not give this environment: #{e.message}" }
363
+ end
364
+ File.write(plan[:result], JSON.generate(result))
365
+ 0
366
+ end
367
+
368
+ # `nuka do <step>`: one step alone, its args from --args and from the
369
+ # records --use names, in a world started for it. The step record goes
370
+ # to stdout and to .nukadoko/do/<id>/record.json, where a later
371
+ # `nuka do --use` reads it. A refusal goes to stderr, since stdout is
372
+ # the record's.
373
+ # Paths written go to stdout, notes and refusals to stderr.
374
+ #: () -> Integer
375
+ def init
376
+ @out = $stderr
377
+ return refuse(Engine::Refusal.new("invalid-arguments", "Unknown argument: json")) if @json
378
+ return refuse(Engine::Refusal.new("invalid-arguments", "--allure is not in the Ruby engine yet")) if @options.key?("--allure")
379
+
380
+ result = Engine::Init.new(@project, out: $stdout, err: $stderr).call
381
+ result.is_a?(Engine::Refusal) ? refuse(result) : result
382
+ end
383
+
384
+ # Writes stubs; their paths go to stdout, and notes and refusals to stderr.
385
+ #: (Array[singleton(Step)], Array[Engine::Scenario]) -> Integer
386
+ def scaffold(steps, scenarios)
387
+ @out = $stderr
388
+ return refuse(Engine::Refusal.new("invalid-arguments", "Unknown argument: json")) if @json
389
+ if @rest.empty? && !@options.key?("--feature")
390
+ missing = "Missing required argument: name (or --feature <path>)"
391
+ took = @options.fetch("--command", []).last.to_s
392
+ missing += "\n#{Engine::Scaffold.command_took_the_name(took)}" if took.match?(Engine::Scaffold::VALID_NAME)
393
+ return refuse(Engine::Refusal.new("invalid-arguments", missing))
394
+ end
395
+
396
+ scaffold = Engine::Scaffold.new(@project, @options, @rest, steps, scenarios)
397
+ scaffold.argv_words = @words.map { Engine::Selection.shell_word(_1) }
398
+ scaffold.command_before_name = @command_before_name || false
399
+ result = scaffold.call
400
+ return refuse(result) if result.is_a?(Engine::Refusal)
401
+
402
+ written, notes = result
403
+ written.each { $stdout.puts _1 }
404
+ notes.each { $stderr.puts _1 }
405
+ 0
406
+ end
407
+
408
+ #: (Engine::Check) -> Integer
409
+ def run_one(check)
410
+ @out = $stderr
411
+ return refuse(Engine::Refusal.new("invalid-arguments", "Unknown argument: json")) if @json
412
+
413
+ name = @rest.first
414
+ step = check.usable.find { _1.step_name == name }
415
+ return refuse(Engine::Refusal.new("unknown-step", "Unknown step: #{name}", fix: "Name a step that nuka steps lists.", run: "nuka steps")) unless step
416
+
417
+ describe = "nuka describe #{name}"
418
+ args_fix = "Pass --args as a JSON object with the keys that nuka describe <step> lists."
419
+ given = {}
420
+ if (text = @options["--args"].last)
421
+ begin
422
+ given = JSON.parse(text)
423
+ rescue JSON::ParserError => e
424
+ return refuse(Engine::Refusal.new("step-args-invalid", "Invalid JSON for --args: #{e.message.lines.first.strip}", fix: args_fix, run: describe))
425
+ end
426
+ return refuse(Engine::Refusal.new("step-args-invalid", "--args must be a JSON object", fix: args_fix, run: describe)) unless given.is_a?(Hash)
427
+ end
428
+ args, origins, used = used_args(step, @options["--use"])
429
+ if @options["--args"].empty? && (step.args.fields.map { _1.name.to_s } - args.keys).any?
430
+ return refuse(Engine::Refusal.new("step-args-invalid", "--args is required unless --use supplies this step's arguments", fix: args_fix, run: describe))
431
+ end
432
+
433
+ args = given.merge(args.reject { |key, _| given.key?(key) })
434
+ given.each_key { origins[_1] = "command_line:#{_1}" }
435
+ environment = Engine::Program.new(Nukadoko.program_options).environments(@options["--env"].last(1)).first
436
+ id = "step-#{Time.now.utc.strftime("%Y%m%d-%H%M%S")}-#{SecureRandom.alphanumeric(4).downcase}"
437
+ dir = File.join(@project, ".nukadoko", "do", id)
438
+ run = Engine::Run.new(@project, check.usable, [], Nukadoko.program_options, environments: [environment], dir: dir, out: $stderr)
439
+ texts = given.to_h { |key, value| [key, JSON.generate(value)] }
440
+ record = run.do_step(step, args, origins, texts, environment)
441
+ written = run.redact(do_record(record, id, step, given, origins, used, environment))
442
+ File.write(File.join(dir, "record.json"), JSON.pretty_generate(written))
443
+ $stdout.puts JSON.pretty_generate(written)
444
+ record[:status] == "passed" ? 0 : 1
445
+ rescue Engine::Refusal => e
446
+ refuse(e)
447
+ end
448
+
449
+ # Each from key of the step, from the newest record --use names whose
450
+ # step gives it, and where it came from.
451
+ #: (singleton(Step), Array[String]) -> [Hash[untyped, untyped], Hash[untyped, String], Array[Hash[Symbol, untyped]]]
452
+ def used_args(step, ids)
453
+ records = ids.map do |id|
454
+ path = [File.join(@project, ".nukadoko", "do", id, "record.json"), *Dir.glob(File.join(@project, ".nukadoko", "runs", "*", "steps", id, "record.json"))].find { File.exist?(_1) }
455
+ unless path
456
+ raise Engine::Refusal.new("step-inputs-invalid", "--use #{id}: no such step record. A step record is removed with its run once the run is older than the newest 20 runs, " \
457
+ "and a nuka do record once it is older than 7 days (retention in nukadoko.config.rb)")
458
+ end
459
+ [id, JSON.parse(File.read(path))]
460
+ end
461
+ args = {}
462
+ origins = {}
463
+ used = []
464
+ step.from.each do |key, sources|
465
+ sources.each do |cls, source_key|
466
+ id, found = records.reverse.find { |_, record| record["step"] == cls.step_name && record["result"].is_a?(Hash) && record["result"].key?(source_key.to_s) }
467
+ next unless found
468
+
469
+ args[key] = found["result"][source_key.to_s]
470
+ origins[key] = "from:#{cls.step_name}@#{id}.#{source_key}"
471
+ used << { step_record_id: id, step: cls.step_name, result: found["result"] } unless used.any? { _1[:step_record_id] == id }
472
+ break
473
+ end
474
+ end
475
+ [args, origins, used]
476
+ end
477
+
478
+ # The record `nuka do` prints, in the TypeScript engine's shape.
479
+ #: (Hash[Symbol, untyped], String, singleton(Step), Hash[untyped, untyped], Hash[untyped, String], Array[Hash[Symbol, untyped]], Engine::Environment) -> Hash[Symbol, untyped]
480
+ def do_record(record, id, step, given, origins, used, environment)
481
+ args_origin = (record[:args] || {}).keys.to_h do |key|
482
+ origin = origins[key]
483
+ if origin&.start_with?("from:")
484
+ step_name, rest = origin.delete_prefix("from:").split("@", 2)
485
+ record_id, source_key = rest.to_s.split(".", 2)
486
+ [key, { from: { step_record_id: record_id, step: step_name, key: source_key } }]
487
+ else [key, "command_line"]
488
+ end
489
+ end
490
+ passed = record[:status] == "passed"
491
+ outcome = passed ? { result: record[:result] || {}, returns_dropped: record[:returns_dropped] || [] } : { error: { message: record[:error], kind: record[:error_kind] } }
492
+ processes = record[:processes]
493
+ { schema_version: Engine::RunRecord::SCHEMA_VERSION, nukadoko: VERSION, step_record_id: id, step: step.step_name, kind: "do",
494
+ args: record[:args] || given, args_origin: args_origin, **outcome, status: record[:status], environment: environment.name,
495
+ world_name: nil, scenario_record_id: nil, run_id: nil, started_at: record[:started_at], finished_at: record[:finished_at],
496
+ evidence: { dir: File.join(".nukadoko", "do", id), screenshots: [] },
497
+ observed: { processes: processes&.any? ? processes : nil,
498
+ http: record[:http_count]&.positive? ? record[:http_count] : nil, files: nil, unmeasured: [] },
499
+ mutates: record[:mutates], **(used.any? ? { used: used } : {}),
500
+ **(record[:claim_records] ? { claims: record[:claim_records], observation: record[:observation] || "observed", attempts: 1 } : {}) }
501
+ end
502
+
503
+ #: (Engine::Scenario, Array[Engine::Environment]) -> bool
504
+ def meets?(scenario, environments)
505
+ tags = Engine::Table.condition_tags(scenario.tags)
506
+ environments.any? { Engine::Table.role(tags, _1.conditions) == "required" }
507
+ end
508
+
509
+ # The `nuka check` that reports the same errors: the files the targets
510
+ # name, and each --env.
511
+ #: () -> String
512
+ def check_command
513
+ files = @rest.map { _1.sub(/:\d+\z/, "") }.uniq
514
+ ["nuka check", *files.map { Engine::Selection.shell_word(_1) }, *@options["--env"].flat_map { ["--env", Engine::Selection.shell_word(_1)] }].join(" ")
515
+ end
516
+
517
+ # Why --env left out every selected scenario, and the run that meets
518
+ # them: the run without --env when it does, else the first environment
519
+ # of the program file that meets each, or else one that meets some.
520
+ #: (Array[Engine::Scenario], Engine::Program) -> Hash[Symbol, String]
521
+ def left_out_stop(left_out, program)
522
+ envs = @options["--env"]
523
+ count = left_out.size
524
+ them = count == 1 ? "it" : "them"
525
+ meets_each = ->(names) { left_out.all? { meets?(_1, names.map { |name| program.environment(name) }) } }
526
+ defaults = program.default_names
527
+ without = "A run without --env selects #{defaults.join(", ")} (#{program.chosen_by})"
528
+ rerun = ->(env) { ["nuka run", *[*@rest, *env].map { Engine::Selection.shell_word(_1) }].join(" ") }
529
+ message = "no scenario to run: the conditions of the #{count} selected #{count == 1 ? "scenario" : "scenarios"} hold in no environment --env names (#{envs.join(", ")}), so nothing was checked"
530
+ finding = { severity: "failed", code: "nothing-selected", message: message }
531
+ return finding.merge(fix: "#{without}, which meets #{them}.", do: rerun.([])) if meets_each.(defaults)
532
+
533
+ candidates = [*program.declared.keys, *(program.declared.key?("default") ? [] : ["default"])] - envs
534
+ other = candidates.find { meets_each.([_1]) } || candidates.find { |name| left_out.any? { meets?(_1, [program.environment(name)]) } }
535
+ unless other
536
+ return finding.merge(fix: "#{without}, which does not meet #{them} either, and no environment of nukadoko.program.rb meets #{them}. " \
537
+ "Declare the conditions #{count == 1 ? "it needs" : "they need"} on an environment, or change #{count == 1 ? "its" : "their"} tags.")
538
+ end
539
+
540
+ finding.merge(fix: "#{without}, which does not meet #{them} either. #{other} meets #{meets_each.([other]) ? them : "some of them"}.",
541
+ do: rerun.(["--env", other]))
542
+ end
543
+
544
+ # Removes what runs left in the state directory: each run directory,
545
+ # each `nuka do` record, the Allure results nukadoko wrote, and the
546
+ # directories an earlier release left. --dry-run lists them only.
547
+ #: () -> Integer
548
+ def clean
549
+ state = File.join(@project, ".nukadoko")
550
+ listed = ->(dir) { Dir.children(File.join(state, dir)).select { File.directory?(File.join(state, dir, _1)) }.sort.map { ".nukadoko/#{dir}/#{_1}" } rescue [] }
551
+ results = File.join(state, "export", "allure-results")
552
+ # The run of a live walk stays: it still writes there, and `nuka
553
+ # step` answers through it. A walk still starting may have made its
554
+ # directory without naming it yet, so every run with no run.json
555
+ # stays while it starts.
556
+ live = Engine::WalkFiles.live_run(@project)
557
+ runs, kept = listed.("runs").partition do |dir|
558
+ next true unless live
559
+
560
+ live[:run_dir] == "starting" ? File.exist?(File.join(@project, dir, "run.json")) : dir != live[:run_dir]
561
+ end
562
+ plan = {
563
+ records: runs + listed.("do"),
564
+ export: File.directory?(results) && !Dir.empty?(results) ? [".nukadoko/export/allure-results"] : [],
565
+ legacy: %w[cache records].select { File.directory?(File.join(state, _1)) }.map { ".nukadoko/#{_1}" },
566
+ kept: kept
567
+ }
568
+ walk = live&.dig(:walk)
569
+ notes = kept.map do |dir|
570
+ { severity: "note", code: "walk-run-kept", message: "kept #{dir}: walk #{walk} is live and its run writes there", do: Engine::Walk.wait_command(walk.to_i) }
571
+ end
572
+ dry_run = @options.key?("--dry-run")
573
+ gone = plan[:records] + plan[:export] + plan[:legacy]
574
+ if @json
575
+ emit({ **head("clean", "passed", notes), **plan, dry_run: dry_run }, notes, "clean")
576
+ else
577
+ gone.each { @out.puts _1 }
578
+ @out.puts "ok: nothing to clean" if gone.empty?
579
+ notes.each { $stderr.puts [_1[:severity], _1[:code], Engine::Summary.where_of(_1), _1[:message]].join("\t"), " do: #{_1[:do]}" }
580
+ end
581
+ return 0 if dry_run
582
+
583
+ gone.each { FileUtils.rm_rf(File.join(@project, _1)) }
584
+ # An `allure watch` already pointed at the results directory keeps
585
+ # finding it.
586
+ FileUtils.mkdir_p(results) if plan[:export].any?
587
+ 0
588
+ end
589
+
590
+ # `nuka skill path`, the one verb, as the TypeScript engine has it.
591
+ #: () -> Integer
592
+ def skill
593
+ verb = @rest.first
594
+ return Skill.print_path(@out, $stderr) if verb == "path" && @rest.size == 1
595
+ return refuse(Engine::Refusal.new("invalid-arguments", "Not enough non-option arguments: got 0, need at least 1")) if verb.nil?
596
+
597
+ refuse(Engine::Refusal.new("invalid-arguments", "Unknown argument: #{(@rest - ["path"]).first || verb}"))
598
+ end
599
+
600
+ # Renders a finished run again from its run.json alone: the run a
601
+ # directory names, or the newest one.
602
+ #: () -> Integer
603
+ def report
604
+ format = @options["--format"].last
605
+ out = @options["--out"].last
606
+ raise Engine::Refusal.new("invalid-arguments", "Missing required argument: format") unless format
607
+ unless %w[markdown allure messages].include?(format)
608
+ raise Engine::Refusal.new("invalid-arguments", %(Invalid values:; Argument: format, Given: #{JSON.generate(format)}, Choices: "markdown", "allure", "messages"))
609
+ end
610
+ if @json && !out && format != "allure"
611
+ raise Engine::Refusal.new("invalid-arguments", "nuka report --json needs --out for --format #{format}, since the #{format} output itself would go to stdout",
612
+ fix: "Add --out <path>.")
613
+ end
614
+
615
+ dir = report_dir
616
+ kind = format == "allure" ? :dir : :file
617
+ target = out ? File.expand_path(out, @project) : (File.join(@project, ".nukadoko", "export", "allure-results") if kind == :dir)
618
+ label = out ? "--out #{out}" : "the default allure directory #{target && shown_path(target)}"
619
+ if target && (problem = out_problem(target, kind, label))
620
+ raise Engine::Refusal.new("report-out-invalid", problem)
621
+ end
622
+
623
+ problems = [] #: Array[String]
624
+ if format == "markdown"
625
+ doc = JSON.parse(File.read(File.join(dir, "run.json"), encoding: "UTF-8"), symbolize_names: true)
626
+ text = Engine::Summary.render(doc)
627
+ else
628
+ run = Engine::ReportRun.new(dir, project_root: @project)
629
+ doc = run.document
630
+ text = Engine::ReportMessages.render(run) if format == "messages"
631
+ problems = run.problems.dup
632
+ end
633
+ # A part of the run the render left out is a failed finding of its
634
+ # own, and the rest is still written.
635
+ findings = -> { problems.map { { severity: "failed", code: "report-incomplete", message: _1 } } }
636
+ unless target
637
+ emit({}, findings.(), "report", io: $stderr)
638
+ @out.write(text)
639
+ return problems.empty? ? 0 : 1
640
+ end
641
+
642
+ exports = own_exports(dir, doc[:run_id], problems)
643
+ replace_own_exports(exports, target, kind)
644
+ FileUtils.mkdir_p(kind == :dir ? target : File.dirname(target))
645
+ if run && format == "allure"
646
+ files = Engine::ReportAllure.write(run, target, ->(message) { problems << message })
647
+ else
648
+ File.write(target, text)
649
+ files = [target]
650
+ end
651
+ note_own_exports(exports, files)
652
+ written = Pathname.new(target).relative_path_from(Pathname.new(@project)).to_s
653
+ return finish("report", problems.empty?, findings: findings.(), run_id: doc[:run_id], format: format, written: [written]) if @json
654
+
655
+ emit({}, findings.(), "report", io: $stderr)
656
+ if kind == :dir
657
+ count = files.count { _1.end_with?("-result.json") }
658
+ $stderr.puts "#{format.ljust(10)}#{"#{written}/".then { _1.ljust([30, _1.size + 2].max) }}#{count}"
659
+ else
660
+ $stderr.puts "#{format.ljust(10)}#{written}"
661
+ end
662
+ problems.empty? ? 0 : 1
663
+ rescue Engine::Refusal => e
664
+ refuse(e)
665
+ end
666
+
667
+ # Why a report cannot go to `target`, or nil when it can.
668
+ #: (String, Symbol, String) -> String?
669
+ def out_problem(target, kind, label)
670
+ if File.exist?(target)
671
+ return "#{label} is a directory; markdown and messages write one file" if kind == :file && File.directory?(target)
672
+ return "#{label} is not a regular file (a FIFO, a socket, or a device), so it is not written" if kind == :file && !File.file?(target)
673
+ return "#{label} is not a directory; allure writes a directory of results" if kind == :dir && !File.directory?(target)
674
+
675
+ return nil
676
+ end
677
+ parent = File.dirname(target)
678
+ parent = File.dirname(parent) until File.exist?(parent) || File.dirname(parent) == parent
679
+ File.directory?(parent) ? nil : "#{label} lies under #{shown_path(parent)}, which is not a directory"
680
+ end
681
+
682
+ #: (String) -> String
683
+ def shown_path(absolute)
684
+ relative = Pathname.new(absolute).relative_path_from(Pathname.new(@project)).to_s
685
+ relative == ".." || relative.start_with?("../") ? absolute : relative
686
+ end
687
+
688
+ # The files this project's own run noted in its exports manifest under
689
+ # the export directory, so a render of the same run replaces what the
690
+ # last one wrote there and retention removes them with the run. A run
691
+ # that is not one of this project's own notes nothing.
692
+ #: (String, untyped, Array[String]) -> Hash[Symbol, untyped]?
693
+ def own_exports(dir, run_id, problems)
694
+ runs = File.join(@project, ".nukadoko", "runs")
695
+ return nil unless File.expand_path(dir) == File.join(runs, run_id.to_s) && !File.symlink?(dir)
696
+
697
+ manifest = File.join(dir, "exports")
698
+ if File.symlink?(manifest)
699
+ problems << "exports of run #{run_id} resolves outside the run directory, so this render is not noted in it"
700
+ return nil
701
+ end
702
+ export = File.join(@project, ".nukadoko", "export")
703
+ lines = File.exist?(manifest) ? File.readlines(manifest, chomp: true).reject(&:empty?).uniq : []
704
+ files = lines.map { [_1, File.expand_path(_1, @project)] }.select { |_, file| file.start_with?("#{export}/") && File.basename(file).casecmp("allure-history.jsonl") != 0 }
705
+ { manifest: manifest, export: export, files: files }
706
+ end
707
+
708
+ #: (Hash[Symbol, untyped]?, String, Symbol) -> void
709
+ def replace_own_exports(exports, target, kind)
710
+ return unless exports
711
+
712
+ gone = exports[:files].select { |_, file| kind == :file ? file == target : file.start_with?("#{target}/") }
713
+ return if gone.empty?
714
+
715
+ gone.each { |_, file| FileUtils.rm_f(file) }
716
+ kept = File.readlines(exports[:manifest], chomp: true).reject { |entry| entry.empty? || gone.any? { |line, _| line == entry } }
717
+ File.write(exports[:manifest], kept.map { "#{_1}\n" }.join)
718
+ end
719
+
720
+ #: (Hash[Symbol, untyped]?, Array[String]) -> void
721
+ def note_own_exports(exports, files)
722
+ return unless exports
723
+
724
+ noted = files.select { _1.start_with?("#{exports[:export]}/") }
725
+ File.open(exports[:manifest], "a") { |io| noted.each { io.puts Pathname.new(_1).relative_path_from(Pathname.new(@project)).to_s } } if noted.any?
726
+ end
727
+
728
+ #: () -> String
729
+ def report_dir
730
+ if (named = @rest.first)
731
+ dir = File.expand_path(named, @project)
732
+ return dir if File.file?(File.join(dir, "run.json"))
733
+
734
+ raise Engine::Refusal.new("run-not-found", "#{dir} holds no run.json that nuka run wrote",
735
+ fix: Engine::Codes.fix("run-not-found"), run: "nuka report --help")
736
+ end
737
+ newest = Engine::Verdict.newest_run(@project)
738
+ raise Engine::Refusal.new("run-not-found", "no run under .nukadoko/runs has a run.json", fix: Engine::Codes.fix("run-not-found"), run: "nuka run") unless newest
739
+
740
+ File.join(@project, newest[:run_dir] || File.join(".nukadoko", "runs", newest[:run_id]))
741
+ end
742
+
743
+ # Reads run.json files and git only, so it loads no step.
744
+ #: () -> Integer
745
+ def verdict
746
+ answer = Engine::Verdict.new(@project)
747
+ if @json
748
+ emit({ **head("verdict", answer.open? ? "failed" : "passed", answer.findings), **answer.envelope_fields }, answer.findings, "verdict")
749
+ else
750
+ @out.puts answer.headline
751
+ emit({}, answer.findings, "verdict")
752
+ end
753
+ answer.open? ? 1 : 0
754
+ end
755
+
756
+ # What check says about the env files; a file it cannot read, or a key
757
+ # both secrets lists name, stops the command instead.
758
+ #: () -> Array[Engine::Finding]
759
+ def env_findings
760
+ Engine::EnvCheck.validate!
761
+ Engine::EnvCheck.findings(@project)
762
+ rescue Engine::EnvFile::Unreadable => e
763
+ raise Engine::Refusal.new("env-file-unreadable", e.message)
764
+ end
765
+
766
+ #: (Engine::Refusal) -> Integer
767
+ def refuse(refusal)
768
+ finish(@command, false, findings: [refusal.to_h(@command)], verdict: refusal.severity, exit_code: refusal.exit_code)
769
+ end
770
+
771
+ #: (Engine::Finding) -> Engine::Finding
62
772
  def relative(finding)
63
- finding.with(file: finding.file&.delete_prefix("#{@project}/"))
773
+ finding.with(file: finding.file&.delete_prefix("#{@project}/"), message: finding.message.gsub("#{@project}/", ""))
774
+ end
775
+
776
+ # Every envelope opens the same way, in the TypeScript engine's order.
777
+ #: (String?, String, Array[untyped], **untyped) -> Hash[Symbol, untyped]
778
+ def head(command, verdict, findings, **more)
779
+ { schema_version: Engine::RunRecord::SCHEMA_VERSION, nukadoko: VERSION, command: command, **more, verdict: verdict, findings: findings }
780
+ end
781
+
782
+ #: (String?, bool, findings: Array[untyped], ?verdict: String, ?exit_code: Integer, **untyped) -> Integer
783
+ def finish(command, passed, findings:, verdict: passed ? "passed" : "failed", exit_code: passed ? 0 : 1, **rest)
784
+ # What a walk that stops here ends with.
785
+ @stopped_with = findings
786
+ emit({ **head(command, verdict, findings), **rest }, findings, command)
787
+ exit_code
64
788
  end
65
789
 
66
- def finish(command, passed, findings:, verdict: passed ? "passed" : "failed", **rest)
790
+ #: (Hash[Symbol, untyped], Array[untyped], String?, ?io: IO) -> void
791
+ def emit(envelope, findings, command, io: @out)
67
792
  if @json
68
- @out.puts JSON.pretty_generate({ nukadoko: VERSION, engine: "ruby", command: command, verdict: verdict, findings: findings, **rest })
793
+ @out.puts JSON.pretty_generate(envelope)
69
794
  else
70
- findings.each { @out.puts [_1[:severity], _1[:code], [_1[:file], _1[:line]].compact.join(":"), _1[:message]].join("\t") }
71
- @out.puts "ok: no issues found" if command == "check" && findings.empty?
795
+ findings.each do |f|
796
+ io.puts [f[:severity], f[:code], Engine::Summary.where_of(f), f[:message]].join("\t")
797
+ io.puts " fix: #{f[:fix]}" if f[:fix]
798
+ io.puts " do: #{f[:do]}" if f[:do]
799
+ end
800
+ io.puts "ok: no issues found" if command == "check" && findings.empty?
801
+ end
802
+ end
803
+
804
+ # The counts after where the run wrote, as the TypeScript engine prints
805
+ # them: the scenarios, then the control runs, then the criteria when a
806
+ # control or a base makes the scenario count no verdict count, then the
807
+ # criteria left out.
808
+ #: (Hash[Symbol, untyped], IO) -> void
809
+ def run_end(envelope, io)
810
+ counts = envelope[:counts] #: Hash[Symbol, Integer]
811
+ total = counts[:scenarios]
812
+ stopped = counts[:stopped]
813
+ io.puts "#{total} scenario#{total == 1 ? "" : "s"}: #{counts[:passed]} passed, #{total - counts[:passed] - stopped} failed" \
814
+ "#{stopped.positive? ? ", #{stopped} stopped" : ""}#{counts[:not_run].positive? ? ", #{counts[:not_run]} not run" : ""}" \
815
+ " (#{duration(envelope[:started_at], envelope[:finished_at])})"
816
+ if counts[:controls].positive? || counts[:controls_not_run].positive?
817
+ not_run = counts[:controls_not_run].positive? ? ", #{counts[:controls_not_run]} not run" : ""
818
+ io.puts "#{counts[:controls]} control run#{counts[:controls] == 1 ? "" : "s"}#{not_run}"
819
+ end
820
+ table = envelope[:table] #: Hash[Symbol, untyped]
821
+ rows = table[:rows] #: Array[Hash[Symbol, untyped]]
822
+ based = !table[:base].nil?
823
+ if based || counts[:controls].positive?
824
+ count = ->(word) { rows.count { _1[:verdict] == word } }
825
+ extra = based ? ", #{count.("unproven")} unproven, #{count.("moved")} moved, #{count.("removed")} removed" : ""
826
+ io.puts "criteria: #{count.("held")} held, #{count.("proven")} proven, #{count.("failed")} failed#{extra}"
827
+ end
828
+ left_out = table[:left_out].to_i
829
+ return unless left_out.positive?
830
+
831
+ io.puts left_out == 1 ? "1 criterion not run: its conditions hold in no selected environment" : "#{left_out} criteria not run: their conditions hold in no selected environment"
832
+ end
833
+
834
+ # `1h 2m 3s`, the unit a whole run reads in.
835
+ #: (String, String) -> String
836
+ def duration(started_at, finished_at)
837
+ total = [(Time.iso8601(finished_at) - Time.iso8601(started_at)).round, 0].max
838
+ hours, rest = total.divmod(3600)
839
+ minutes, seconds = rest.divmod(60)
840
+ [*(hours.positive? ? ["#{hours}h"] : []), *(hours.positive? || minutes.positive? ? ["#{minutes}m"] : []), "#{seconds}s"].join(" ")
841
+ end
842
+
843
+ # After the failed list, under --repeat, each scenario that failed at
844
+ # least once and how many of its executions passed. No verdict is
845
+ # named: one that fails every time is not flaky.
846
+ #: (Array[Hash[Symbol, untyped]], IO) -> void
847
+ def repeat_tallies(scenarios, io)
848
+ named = @options["--env"].size > 1
849
+ scenarios.reject { _1[:world] }.group_by { _1.values_at(:feature, :line, :environment) }.each_value do |runs|
850
+ passed = runs.count { _1[:status] == "passed" }
851
+ next if passed == runs.size
852
+
853
+ first = runs.first
854
+ name = named ? "#{first[:scenario]} (#{first[:environment]})" : first[:scenario]
855
+ io.puts "repeat #{first[:feature]}:#{first[:line]} #{name} #{passed} of #{runs.size} passed"
72
856
  end
73
- passed ? 0 : 1
74
857
  end
75
858
  end
76
859
  end