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,150 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ # The values an ARIA snapshot reads as (lib/nukadoko/aria_snapshot.rb):
5
+ # the YAML items of its text, the nodes of the tree nukadoko took and of
6
+ # the tree a docstring states, and the scores the explanation of a misfit
7
+ # aligns them with. Nothing here reads a text or judges a fit; the classes
8
+ # sit apart from that module so its functions stay module functions of it
9
+ # alone.
10
+ module Nukadoko
11
+ module Engine
12
+ module AriaSnapshot
13
+ # One scalar of an item: its text after YAML unquoted it, and whether
14
+ # it was written plain, which is when YAML may read it as a number, a
15
+ # boolean, or null.
16
+ Scalar = Data.define(
17
+ :text, #: String
18
+ :plain, #: bool
19
+ )
20
+
21
+ # One item of the list: a key alone, a key and its text, or a key and
22
+ # its children. `source` is the item as written, after `- ` and before
23
+ # any comment, for a message.
24
+ Item = Data.define(
25
+ :line, #: Integer
26
+ :source, #: String
27
+ :key, #: Scalar
28
+ :value, #: Scalar?
29
+ :children, #: Array[Item]?
30
+ )
31
+
32
+ # A line of the text that holds an item: its number from 1, the
33
+ # column its content starts at, and the content.
34
+ Line = Data.define(
35
+ :number, #: Integer
36
+ :indent, #: Integer
37
+ :content, #: String
38
+ )
39
+
40
+ # A text as a docstring states it, and with its white space folded
41
+ # the way a page's text is: either one fits.
42
+ ExpectedText = Data.define(
43
+ :raw, #: String
44
+ :normalized, #: String
45
+ )
46
+
47
+ # Why a text is no ARIA snapshot, with the line it found that on.
48
+ class Problem < StandardError; end
49
+
50
+ # One node of the snapshot nukadoko took, or one a docstring names.
51
+ # A text node holds `text`; a role node holds the rest. The top of a
52
+ # tree is a node of role `fragment` that holds the list.
53
+ class Node
54
+ attr_reader :kind #: :role | :text
55
+ attr_reader :role #: String
56
+ attr_reader :name #: String
57
+ attr_reader :states #: Hash[String, untyped]
58
+ attr_reader :props #: Hash[String, untyped]
59
+ attr_reader :children #: Array[Node]
60
+ attr_accessor :children_mode #: String?
61
+ attr_reader :text #: untyped
62
+ attr_reader :line #: Integer
63
+ attr_reader :source #: String
64
+
65
+ #: (kind: :role | :text, line: Integer, source: String, ?role: String, ?name: String, ?states: Hash[String, untyped], ?props: Hash[String, untyped], ?children: Array[Node], ?children_mode: String?, ?text: untyped) -> void
66
+ def initialize(kind:, line:, source:, role: "", name: "", states: {}, props: {}, children: [], children_mode: nil, text: nil)
67
+ @kind = kind
68
+ @role = role
69
+ @name = name
70
+ @states = states
71
+ @props = props
72
+ @children = children
73
+ @children_mode = children_mode
74
+ @text = text
75
+ @line = line
76
+ @source = source
77
+ end
78
+
79
+ #: () -> bool
80
+ def text? = kind == :text
81
+ end
82
+
83
+ # How many nodes of an expected tree fit under an actual node, for
84
+ # each pairing, kept so the alignment counts each pair once.
85
+ class Scores
86
+ #: () -> void
87
+ def initialize
88
+ @memo = { false => {}.compare_by_identity, true => {}.compare_by_identity } #: Hash[bool, Hash[Node, Hash[Node, Integer]]]
89
+ end
90
+
91
+ # The nodes of `expected`'s tree that fit under `actual`, `expected`
92
+ # itself included (a fragment counts for none): 0 when `actual` is
93
+ # not the node `expected` names.
94
+ #: (Node, Node, bool) -> Integer
95
+ def of(expected, actual, deep)
96
+ by_actual = (@memo.fetch(deep)[expected] ||= {}.compare_by_identity)
97
+ cached = by_actual[actual]
98
+ return cached if cached
99
+
100
+ by_actual[actual] = compute(expected, actual, deep)
101
+ end
102
+
103
+ # The in-order pairing of expected children with actual children
104
+ # that fits the most expected nodes; of equals, the one that pairs
105
+ # each expected child with the earliest actual child it can.
106
+ #: (Array[Node], Array[Node]) -> [Integer, Hash[Integer, Integer]]
107
+ def aligned(expected, actual)
108
+ best = Array.new(expected.size + 1) { Array.new(actual.size + 1, 0) }
109
+ (expected.size - 1).downto(0) do |i|
110
+ (actual.size - 1).downto(0) do |j|
111
+ paired = of(expected.fetch(i), actual.fetch(j), false)
112
+ best[i][j] = [best[i][j + 1], best[i + 1][j], paired.zero? ? 0 : paired + best[i + 1][j + 1]].max
113
+ end
114
+ end
115
+ pairs = {} #: Hash[Integer, Integer]
116
+ i = 0
117
+ j = 0
118
+ while i < expected.size && j < actual.size
119
+ paired = of(expected.fetch(i), actual.fetch(j), false)
120
+ if paired.positive? && paired + best[i + 1][j + 1] == best[i][j]
121
+ pairs[i] = j
122
+ i += 1
123
+ j += 1
124
+ elsif best[i][j + 1] == best[i][j]
125
+ j += 1
126
+ else
127
+ i += 1
128
+ end
129
+ end
130
+ [best[0][0], pairs]
131
+ end
132
+
133
+ private
134
+
135
+ #: (Node, Node, bool) -> Integer
136
+ def compute(expected, actual, deep)
137
+ return 0 unless AriaSnapshot.line_fits?(actual, expected)
138
+ return 1 if expected.text?
139
+
140
+ own = expected.role == AriaSnapshot::FRAGMENT ? AriaSnapshot.stated_props(expected.props) : 1
141
+ children = actual.children
142
+ contain, deeper = AriaSnapshot.children_reading(expected, deep)
143
+ return own + aligned(expected.children, children).first if contain
144
+
145
+ own + expected.children.each_with_index.sum { |child, index| (at = children[index]) ? of(child, at, deeper) : 0 }
146
+ end
147
+ end
148
+ end
149
+ end
150
+ end
@@ -0,0 +1,294 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ require "digest"
5
+ require "fileutils"
6
+ require "json"
7
+ require "open3"
8
+ require "rbconfig"
9
+
10
+ # `nuka run --base <ref>`: what changed since the ref, and the trees the
11
+ # rows need to be judged against it. Two trees go in the run's own
12
+ # directory, under trees/:
13
+ #
14
+ # - base: the ref's code with head's features/ and config, so a new or
15
+ # changed criterion runs where its behaviour should be absent. The ref's
16
+ # program starts it, or head's when the ref has none: the program goes
17
+ # with the code, so the run writes the ref's config beside head's as
18
+ # nukadoko.tree-program.rb (or the ref's program file from before the
19
+ # program moved into the config as nukadoko.tree-legacy-program.rb).
20
+ # - old: head's working tree with the ref's features/ and config, so an
21
+ # unchanged criterion over a changed mapping runs under the steps it was
22
+ # approved with. Head's config goes beside it as nukadoko.tree-program.rb,
23
+ # so head's program starts it.
24
+ #
25
+ # The mapping is every file under features/ but a .feature file, the config
26
+ # file's bytes with its program lambda cut out, and the program's
27
+ # conditions and defaultEnvironments, which decide where a criterion is
28
+ # required. Every git command runs with
29
+ # hooks off, since a checkout's hook is the project's code and not the
30
+ # run's. Both trees are removed when the run ends.
31
+ module Nukadoko
32
+ module Engine
33
+ class Base
34
+ NO_HOOKS = ["-c", "core.hooksPath=/dev/null"].freeze
35
+ FEATURES = "features"
36
+ STATE = ".nukadoko"
37
+
38
+ attr_reader :ref #: String
39
+ attr_reader :commit #: String
40
+ attr_reader :changes #: Hash[untyped, Hash[Symbol, untyped]]
41
+ attr_reader :removed #: Array[Criteria::Criterion]
42
+ attr_reader :mapping #: Hash[Symbol, untyped]
43
+ attr_reader :base_root #: String?
44
+ attr_reader :old_root #: String?
45
+ attr_reader :old_environments #: Array[Environment]?
46
+ attr_reader :program_from_head #: bool?
47
+
48
+ # The commit `ref` names, or a Refusal with the TypeScript engine's
49
+ # code: outside git, a shallow clone that lacks it, or no such commit.
50
+ #: (String, String) -> String
51
+ def self.resolve(project, ref)
52
+ shallow, ok = git(project, "rev-parse", "--is-shallow-repository")
53
+ raise Refusal.new("base-outside-git", "nuka run --base #{ref} needs a git repository, and the project directory is not inside one") unless ok
54
+ raise Refusal.new("base-ref-unknown", "--base #{JSON.generate(ref)} names no commit", run: "git log --oneline") if ref.empty? || ref.start_with?("-")
55
+
56
+ commit, found = git(project, "rev-parse", "--verify", "--quiet", "#{ref}^{commit}")
57
+ return commit if found && !commit.empty?
58
+ if shallow == "true"
59
+ raise Refusal.new("base-shallow", "--base #{ref} names no commit in this shallow clone, which holds only part of the history; fetch the base first",
60
+ run: "git fetch --unshallow origin")
61
+ end
62
+
63
+ raise Refusal.new("base-ref-unknown", "--base #{ref} names no commit in the project's repository", run: "git log --oneline")
64
+ end
65
+
66
+ #: (String, *String, ?strip: bool) -> [String, bool]
67
+ def self.git(dir, *argv, strip: true)
68
+ out, status = Open3.capture2({ "LC_ALL" => "C" }, "git", *NO_HOOKS, "-C", dir, *argv, err: File::NULL)
69
+ [strip ? out.strip : out, status.success?]
70
+ rescue SystemCallError
71
+ ["", false]
72
+ end
73
+
74
+ # `selected` is each selected scenario's [feature, line]; `targets` the
75
+ # run's targets without a line, or nil for the features directory.
76
+ #: (project: String, ref: String, commit: String, run_dir: String, selected: Array[[String, Integer]], targets: Array[String]?, envs: Array[String], head_program: Hash[Symbol, untyped]?) -> void
77
+ def initialize(project:, ref:, commit:, run_dir:, selected:, targets:, envs:, head_program:)
78
+ @project = project
79
+ @ref = ref
80
+ @commit = commit
81
+ @trees = File.join(run_dir, "trees")
82
+ @top, = Base.git(project, "rev-parse", "--show-toplevel")
83
+ @prefix = Base.git(project, "rev-parse", "--show-prefix").first.delete_suffix("/")
84
+ @base_top = File.join(@trees, "base")
85
+ @old_top = File.join(@trees, "old")
86
+ prepare(selected, targets, envs, head_program)
87
+ rescue StandardError
88
+ cleanup
89
+ raise
90
+ end
91
+
92
+ #: () -> void
93
+ def cleanup
94
+ if @worktree
95
+ @worktree = false
96
+ Base.git(@top, "worktree", "remove", "--force", "--force", @base_top)
97
+ end
98
+ FileUtils.rm_rf([@base_top, @old_top])
99
+ Dir.rmdir(@trees) if Dir.exist?(@trees) && Dir.empty?(@trees)
100
+ end
101
+
102
+ # The ref's place of an unchanged head row, and the head row a place
103
+ # at the ref is.
104
+ #: ([String, Integer]) -> Hash[Symbol, untyped]?
105
+ def at(key) = @changes[key]&.then { _1[:change] == "unchanged" ? _1[:at] : nil }
106
+
107
+ #: (String, Integer) -> [String, Integer]?
108
+ def row_of(feature, line) = @changes.find { |_, change| change[:at] == { feature: feature, line: line } }&.first
109
+
110
+ #: () -> Hash[Symbol, untyped]
111
+ def mapping_changes
112
+ { files: @mapping[:files].map { File.join(FEATURES, _1) }, config: @mapping[:config], conditions: @mapping[:conditions],
113
+ default_environments: @mapping[:default_environments], unseen: [] }
114
+ end
115
+
116
+ private
117
+
118
+ #: (String) -> String
119
+ def in_repo(path) = @prefix.empty? ? path : File.join(@prefix, path)
120
+
121
+ #: (Array[[String, Integer]], Array[String]?, Array[String], Hash[Symbol, untyped]?) -> void
122
+ def prepare(selected, targets, envs, head_program)
123
+ FileUtils.mkdir_p(@trees)
124
+ _, ok = Base.git(@top, "worktree", "add", "--detach", "--quiet", @base_top, @commit)
125
+ raise Refusal.new("base-git-failed", "nuka run --base #{@ref} could not compare with the base: git worktree add failed") unless ok
126
+
127
+ @worktree = true
128
+ base_project = File.join(@base_top, @prefix)
129
+ ref_paths = feature_files(base_project, [FEATURES, *targets.to_a])
130
+ ref_criteria, @unparsed = Criteria.of_files(base_project, ref_paths)
131
+ head_criteria, = Criteria.of_files(@project, feature_files(@project, [FEATURES, *targets.to_a]))
132
+ compared = Criteria.compare(ref_criteria, head_criteria)
133
+ @changes = compared[:changes]
134
+ targeted = targets && feature_files(base_project, targets)
135
+ @removed = targeted ? compared[:removed].select { targeted.include?(_1.feature) } : compared[:removed]
136
+
137
+ head_files = working_tree_files
138
+ ref_files = Base.git(@base_top, "ls-files", "-z", strip: false).first.split("\0").reject(&:empty?)
139
+ ref_program = read_program(base_project)
140
+ ref_config = File.join(base_project, CONFIG)
141
+ ref_config_text = File.exist?(ref_config) ? File.read(ref_config) : nil
142
+ @mapping = compare_mapping(head_files, ref_files, base_project, head_program, ref_program)
143
+
144
+ wanted = selected.map { @changes[_1] }
145
+ base_needed = wanted.any? { %w[changed new].include?(_1&.dig(:change)) }
146
+ old_needed = wanted.any? { _1&.dig(:change) == "unchanged" && (@mapping[:changed] || _1[:retagged] || _1[:renamed_from]) }
147
+ write_old_tree(head_files, ref_files) if old_needed
148
+ if base_needed
149
+ overlay_base_tree(head_files, ref_files, ref_program && ref_config_text)
150
+ @base_root = base_project
151
+ @program_from_head = ref_program.nil? && !(head_program || {}).empty?
152
+ else
153
+ @worktree = false
154
+ Base.git(@top, "worktree", "remove", "--force", "--force", @base_top)
155
+ end
156
+ @old_root = File.join(@old_top, @prefix) if old_needed
157
+ @old_environments = old_environments_of(ref_program, envs)
158
+ end
159
+
160
+ # The environments the old world runs in, with the conditions the ref's
161
+ # program gives each; nil when the ref has no program, so
162
+ # head's environments are the old world's too.
163
+ #: (Hash[Symbol, untyped]?, Array[String]) -> Array[Environment]?
164
+ def old_environments_of(program, envs)
165
+ return nil if program.nil? || program[:problem]
166
+
167
+ declared = program[:environments]
168
+ names = if envs.any? then envs
169
+ elsif program[:defaultEnvironments] then program[:defaultEnvironments]
170
+ else
171
+ conditioned = declared.select { |_, e| e[:conditions] }.keys
172
+ conditioned.any? ? conditioned : ["default"]
173
+ end
174
+ names.map { |name| Environment.new(name, (declared.dig(name, :conditions) || {}).transform_keys(&:to_s), {}, Program.env_files(declared[name] || {})) }
175
+ end
176
+
177
+ #: (String, Array[String]) -> Array[String]
178
+ def feature_files(root, targets)
179
+ targets.flat_map do |target|
180
+ absolute = File.join(root, target)
181
+ if File.directory?(absolute) then Dir.glob("**/*.feature", base: absolute).sort.map { File.join(target, _1) }
182
+ elsif target.end_with?(".feature") && File.file?(absolute) then [target]
183
+ else []
184
+ end
185
+ end.uniq.sort
186
+ end
187
+
188
+ # Head's working tree as a copy holds it: tracked files and untracked
189
+ # ones git does not ignore, on disk, outside the state directory.
190
+ #: () -> Array[String]
191
+ def working_tree_files
192
+ listed = Base.git(@top, "ls-files", "-z", "--cached", "--others", "--exclude-standard", strip: false).first.split("\0").reject(&:empty?)
193
+ listed.uniq.reject { within?(_1, in_repo(STATE)) }.select { File.exist?(File.join(@top, _1)) || File.symlink?(File.join(@top, _1)) }
194
+ end
195
+
196
+ #: (String, String) -> bool
197
+ def within?(file, dir) = dir.empty? || file == dir || file.start_with?("#{dir}/")
198
+
199
+ #: (String) -> bool
200
+ def mapping?(file) = within?(file, in_repo(FEATURES)) || file == in_repo(CONFIG)
201
+
202
+ #: (String) -> String
203
+ def hash_of(file) = File.symlink?(file) ? "link:#{File.readlink(file)}" : Digest::SHA256.file(file).hexdigest
204
+
205
+ #: (Array[String], String) -> Hash[String, String]
206
+ def mapping_files(files, top)
207
+ dir = in_repo(FEATURES)
208
+ files.select { within?(_1, dir) && !_1.end_with?(".feature") && File.file?(File.join(top, _1)) }
209
+ .to_h { [_1.delete_prefix("#{dir}/"), hash_of(File.join(top, _1))] }
210
+ end
211
+
212
+ # The ref's program: its program file from before the program moved
213
+ # into the config, or its config's program, read in a process of its
214
+ # own (ProjectProgram.elsewhere). nil when the ref has neither.
215
+ #: (String) -> Hash[Symbol, untyped]?
216
+ def read_program(root)
217
+ legacy = File.join(root, LEGACY_PROGRAM)
218
+ config = File.join(root, CONFIG)
219
+ program = if File.exist?(legacy) then ProjectProgram.elsewhere(legacy, legacy: true) || {}
220
+ elsif File.exist?(config) then ProjectProgram.elsewhere(config, legacy: false)
221
+ end
222
+ return nil if program.nil?
223
+
224
+ { environments: (program[:environments] || {}).transform_keys(&:to_s), defaultEnvironments: program[:defaultEnvironments] }
225
+ rescue Refusal => e
226
+ { problem: e.message }
227
+ end
228
+
229
+ #: (Hash[Symbol, untyped]?) -> Hash[Symbol, untyped]
230
+ def program_mapping(program)
231
+ environments = (program && program[:environments]) || {}
232
+ { conditions: environments.to_h { |name, e| [name.to_s, JSON.generate(e[:conditions])] }, defaults: JSON.generate(program && program[:defaultEnvironments]) }
233
+ end
234
+
235
+ #: (Array[String], Array[String], String, Hash[Symbol, untyped]?, Hash[Symbol, untyped]?) -> Hash[Symbol, untyped]
236
+ def compare_mapping(head_files, ref_files, base_project, head_program, ref_program)
237
+ head = mapping_files(head_files, @top)
238
+ ref = mapping_files(ref_files, @base_top)
239
+ files = (head.keys | ref.keys).select { head[_1] != ref[_1] }.sort
240
+ config_hash = ->(root) { File.exist?(File.join(root, CONFIG)) ? Digest::SHA256.hexdigest(ProjectProgram.mapping_text(File.read(File.join(root, CONFIG)))) : nil }
241
+ config = config_hash.(@project) != config_hash.(base_project)
242
+ after = program_mapping(head_program && { environments: (head_program[:environments] || {}).transform_keys(&:to_s), defaultEnvironments: head_program[:defaultEnvironments] })
243
+ if ref_program&.dig(:problem)
244
+ conditions = after[:conditions].keys.sort
245
+ defaults = true
246
+ else
247
+ before = program_mapping(ref_program)
248
+ none = JSON.generate(nil)
249
+ conditions = (before[:conditions].keys | after[:conditions].keys).select { before[:conditions].fetch(_1, none) != after[:conditions].fetch(_1, none) }.sort
250
+ defaults = before[:defaults] != after[:defaults]
251
+ end
252
+ changed = files.any? || config || conditions.any? || defaults || !ref_program&.dig(:problem).nil?
253
+ { changed: changed, files: files, config: config, conditions: conditions, default_environments: defaults }
254
+ end
255
+
256
+ #: (String, String) -> void
257
+ def copy(from, to)
258
+ FileUtils.mkdir_p(File.dirname(to))
259
+ FileUtils.rm_rf(to)
260
+ File.symlink?(from) ? File.symlink(File.readlink(from), to) : FileUtils.cp(from, to)
261
+ end
262
+
263
+ # The ref's checkout loses the ref's mapping and gains head's. The
264
+ # ref's program stays: its program file under the tree's own name, or
265
+ # its config `ref_config` beside head's. When the ref has no program,
266
+ # head's config brings head's.
267
+ #: (Array[String], Array[String], String?) -> void
268
+ def overlay_base_tree(head_files, ref_files, ref_config)
269
+ ref_files.select { mapping?(_1) }.each { FileUtils.rm_f(File.join(@base_top, _1)) }
270
+ head_files.select { mapping?(_1) }.each { copy(File.join(@top, _1), File.join(@base_top, _1)) }
271
+ legacy = File.join(@base_top, in_repo(LEGACY_PROGRAM))
272
+ if File.exist?(legacy)
273
+ FileUtils.mv(legacy, File.join(@base_top, in_repo(TREE_LEGACY_PROGRAM)))
274
+ elsif ref_config
275
+ File.write(File.join(@base_top, in_repo(TREE_PROGRAM)), ref_config)
276
+ end
277
+ end
278
+
279
+ # Head's working tree with the ref's mapping in place of its own,
280
+ # written before the base checkout is overlaid. Head's program stays:
281
+ # head's config goes beside the ref's, or a file that names no
282
+ # program when head has no config.
283
+ #: (Array[String], Array[String]) -> void
284
+ def write_old_tree(head_files, ref_files)
285
+ head_files.reject { mapping?(_1) }.each { copy(File.join(@top, _1), File.join(@old_top, _1)) }
286
+ ref_files.select { mapping?(_1) }.each { copy(File.join(@base_top, _1), File.join(@old_top, _1)) }
287
+ head_config = File.join(@project, CONFIG)
288
+ tree_program = File.join(@old_top, in_repo(TREE_PROGRAM))
289
+ FileUtils.mkdir_p(File.dirname(tree_program))
290
+ File.write(tree_program, File.exist?(head_config) ? File.read(head_config) : "# Head has no config, so no program.\n")
291
+ end
292
+ end
293
+ end
294
+ end