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
@@ -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,274 @@
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 file starts it, or head's when the ref has none.
17
+ # - old: head's working tree with the ref's features/ and config, so an
18
+ # unchanged criterion over a changed mapping runs under the steps it was
19
+ # approved with.
20
+ #
21
+ # The mapping is every file under features/ but a .feature file, the config
22
+ # file's bytes, and the program file's conditions and defaultEnvironments,
23
+ # which decide where a criterion is required. Every git command runs with
24
+ # hooks off, since a checkout's hook is the project's code and not the
25
+ # run's. Both trees are removed when the run ends.
26
+ module Nukadoko
27
+ module Engine
28
+ class Base
29
+ NO_HOOKS = ["-c", "core.hooksPath=/dev/null"].freeze
30
+ FEATURES = "features"
31
+ CONFIG = "nukadoko.config.rb"
32
+ PROGRAM = "nukadoko.program.rb"
33
+ STATE = ".nukadoko"
34
+
35
+ attr_reader :ref #: String
36
+ attr_reader :commit #: String
37
+ attr_reader :changes #: Hash[untyped, Hash[Symbol, untyped]]
38
+ attr_reader :removed #: Array[Criteria::Criterion]
39
+ attr_reader :mapping #: Hash[Symbol, untyped]
40
+ attr_reader :base_root #: String?
41
+ attr_reader :old_root #: String?
42
+ attr_reader :old_environments #: Array[Environment]?
43
+ attr_reader :program_from_head #: bool?
44
+
45
+ # The commit `ref` names, or a Refusal with the TypeScript engine's
46
+ # code: outside git, a shallow clone that lacks it, or no such commit.
47
+ #: (String, String) -> String
48
+ def self.resolve(project, ref)
49
+ shallow, ok = git(project, "rev-parse", "--is-shallow-repository")
50
+ raise Refusal.new("base-outside-git", "nuka run --base #{ref} needs a git repository, and the project directory is not inside one") unless ok
51
+ raise Refusal.new("base-ref-unknown", "--base #{JSON.generate(ref)} names no commit", run: "git log --oneline") if ref.empty? || ref.start_with?("-")
52
+
53
+ commit, found = git(project, "rev-parse", "--verify", "--quiet", "#{ref}^{commit}")
54
+ return commit if found && !commit.empty?
55
+ if shallow == "true"
56
+ 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",
57
+ run: "git fetch --unshallow origin")
58
+ end
59
+
60
+ raise Refusal.new("base-ref-unknown", "--base #{ref} names no commit in the project's repository", run: "git log --oneline")
61
+ end
62
+
63
+ #: (String, *String, ?strip: bool) -> [String, bool]
64
+ def self.git(dir, *argv, strip: true)
65
+ out, status = Open3.capture2({ "LC_ALL" => "C" }, "git", *NO_HOOKS, "-C", dir, *argv, err: File::NULL)
66
+ [strip ? out.strip : out, status.success?]
67
+ rescue SystemCallError
68
+ ["", false]
69
+ end
70
+
71
+ # `selected` is each selected scenario's [feature, line]; `targets` the
72
+ # run's targets without a line, or nil for the features directory.
73
+ #: (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
74
+ def initialize(project:, ref:, commit:, run_dir:, selected:, targets:, envs:, head_program:)
75
+ @project = project
76
+ @ref = ref
77
+ @commit = commit
78
+ @trees = File.join(run_dir, "trees")
79
+ @top, = Base.git(project, "rev-parse", "--show-toplevel")
80
+ @prefix = Base.git(project, "rev-parse", "--show-prefix").first.delete_suffix("/")
81
+ @base_top = File.join(@trees, "base")
82
+ @old_top = File.join(@trees, "old")
83
+ prepare(selected, targets, envs, head_program)
84
+ rescue StandardError
85
+ cleanup
86
+ raise
87
+ end
88
+
89
+ #: () -> void
90
+ def cleanup
91
+ if @worktree
92
+ @worktree = false
93
+ Base.git(@top, "worktree", "remove", "--force", "--force", @base_top)
94
+ end
95
+ FileUtils.rm_rf([@base_top, @old_top])
96
+ Dir.rmdir(@trees) if Dir.exist?(@trees) && Dir.empty?(@trees)
97
+ end
98
+
99
+ # The ref's place of an unchanged head row, and the head row a place
100
+ # at the ref is.
101
+ #: ([String, Integer]) -> Hash[Symbol, untyped]?
102
+ def at(key) = @changes[key]&.then { _1[:change] == "unchanged" ? _1[:at] : nil }
103
+
104
+ #: (String, Integer) -> [String, Integer]?
105
+ def row_of(feature, line) = @changes.find { |_, change| change[:at] == { feature: feature, line: line } }&.first
106
+
107
+ #: () -> Hash[Symbol, untyped]
108
+ def mapping_changes
109
+ { files: @mapping[:files].map { File.join(FEATURES, _1) }, config: @mapping[:config], conditions: @mapping[:conditions],
110
+ default_environments: @mapping[:default_environments], unseen: [] }
111
+ end
112
+
113
+ private
114
+
115
+ #: (String) -> String
116
+ def in_repo(path) = @prefix.empty? ? path : File.join(@prefix, path)
117
+
118
+ #: (Array[[String, Integer]], Array[String]?, Array[String], Hash[Symbol, untyped]?) -> void
119
+ def prepare(selected, targets, envs, head_program)
120
+ FileUtils.mkdir_p(@trees)
121
+ _, ok = Base.git(@top, "worktree", "add", "--detach", "--quiet", @base_top, @commit)
122
+ raise Refusal.new("base-git-failed", "nuka run --base #{@ref} could not compare with the base: git worktree add failed") unless ok
123
+
124
+ @worktree = true
125
+ base_project = File.join(@base_top, @prefix)
126
+ ref_paths = feature_files(base_project, [FEATURES, *targets.to_a])
127
+ ref_criteria, @unparsed = Criteria.of_files(base_project, ref_paths)
128
+ head_criteria, = Criteria.of_files(@project, feature_files(@project, [FEATURES, *targets.to_a]))
129
+ compared = Criteria.compare(ref_criteria, head_criteria)
130
+ @changes = compared[:changes]
131
+ targeted = targets && feature_files(base_project, targets)
132
+ @removed = targeted ? compared[:removed].select { targeted.include?(_1.feature) } : compared[:removed]
133
+
134
+ head_files = working_tree_files
135
+ ref_files = Base.git(@base_top, "ls-files", "-z", strip: false).first.split("\0").reject(&:empty?)
136
+ ref_program = File.exist?(File.join(base_project, PROGRAM)) ? read_program(base_project) : nil
137
+ @mapping = compare_mapping(head_files, ref_files, base_project, head_program, ref_program)
138
+
139
+ wanted = selected.map { @changes[_1] }
140
+ base_needed = wanted.any? { %w[changed new].include?(_1&.dig(:change)) }
141
+ old_needed = wanted.any? { _1&.dig(:change) == "unchanged" && (@mapping[:changed] || _1[:retagged] || _1[:renamed_from]) }
142
+ write_old_tree(head_files, ref_files) if old_needed
143
+ if base_needed
144
+ overlay_base_tree(head_files, ref_files)
145
+ @base_root = base_project
146
+ @program_from_head = !File.exist?(File.join(@base_top, in_repo(PROGRAM))) && File.exist?(File.join(@project, PROGRAM))
147
+ else
148
+ @worktree = false
149
+ Base.git(@top, "worktree", "remove", "--force", "--force", @base_top)
150
+ end
151
+ @old_root = File.join(@old_top, @prefix) if old_needed
152
+ @old_environments = old_environments_of(ref_program, envs)
153
+ end
154
+
155
+ # The environments the old world runs in, with the conditions the ref's
156
+ # program file gives each; nil when the ref has no program file, so
157
+ # head's environments are the old world's too.
158
+ #: (Hash[Symbol, untyped]?, Array[String]) -> Array[Environment]?
159
+ def old_environments_of(program, envs)
160
+ return nil if program.nil? || program[:problem]
161
+
162
+ declared = program[:environments]
163
+ names = if envs.any? then envs
164
+ elsif program[:defaultEnvironments] then program[:defaultEnvironments]
165
+ else
166
+ conditioned = declared.select { |_, e| e[:conditions] }.keys
167
+ conditioned.any? ? conditioned : ["default"]
168
+ end
169
+ names.map { |name| Environment.new(name, (declared.dig(name, :conditions) || {}).transform_keys(&:to_s), {}, Program.env_files(declared[name] || {})) }
170
+ end
171
+
172
+ #: (String, Array[String]) -> Array[String]
173
+ def feature_files(root, targets)
174
+ targets.flat_map do |target|
175
+ absolute = File.join(root, target)
176
+ if File.directory?(absolute) then Dir.glob("**/*.feature", base: absolute).sort.map { File.join(target, _1) }
177
+ elsif target.end_with?(".feature") && File.file?(absolute) then [target]
178
+ else []
179
+ end
180
+ end.uniq.sort
181
+ end
182
+
183
+ # Head's working tree as a copy holds it: tracked files and untracked
184
+ # ones git does not ignore, on disk, outside the state directory.
185
+ #: () -> Array[String]
186
+ def working_tree_files
187
+ listed = Base.git(@top, "ls-files", "-z", "--cached", "--others", "--exclude-standard", strip: false).first.split("\0").reject(&:empty?)
188
+ listed.uniq.reject { within?(_1, in_repo(STATE)) }.select { File.exist?(File.join(@top, _1)) || File.symlink?(File.join(@top, _1)) }
189
+ end
190
+
191
+ #: (String, String) -> bool
192
+ def within?(file, dir) = dir.empty? || file == dir || file.start_with?("#{dir}/")
193
+
194
+ #: (String) -> bool
195
+ def mapping?(file) = within?(file, in_repo(FEATURES)) || file == in_repo(CONFIG)
196
+
197
+ #: (String) -> String
198
+ def hash_of(file) = File.symlink?(file) ? "link:#{File.readlink(file)}" : Digest::SHA256.file(file).hexdigest
199
+
200
+ #: (Array[String], String) -> Hash[String, String]
201
+ def mapping_files(files, top)
202
+ dir = in_repo(FEATURES)
203
+ files.select { within?(_1, dir) && !_1.end_with?(".feature") && File.file?(File.join(top, _1)) }
204
+ .to_h { [_1.delete_prefix("#{dir}/"), hash_of(File.join(top, _1))] }
205
+ end
206
+
207
+ # The ref's program file read in a process of its own, since loading
208
+ # it here would replace head's: its conditions and defaultEnvironments.
209
+ #: (String) -> Hash[Symbol, untyped]
210
+ def read_program(root)
211
+ script = 'require "nukadoko"; load ARGV[0]; o = Nukadoko.program_options; ' \
212
+ 'puts JSON.generate(environments: (o[:environments] || {}).to_h { |k, v| [k, { conditions: v[:conditions] }] }, defaultEnvironments: o[:defaultEnvironments])'
213
+ out, err, status = Open3.capture3(RbConfig.ruby, "-I", File.expand_path("..", __dir__.to_s), "-rjson", "-e", script, File.join(root, PROGRAM), chdir: root)
214
+ return { problem: err.lines.first.to_s.strip } unless status.success?
215
+
216
+ program = JSON.parse(out, symbolize_names: true)
217
+ program[:environments] = program[:environments].transform_keys(&:to_s)
218
+ program
219
+ end
220
+
221
+ #: (Hash[Symbol, untyped]?) -> Hash[Symbol, untyped]
222
+ def program_mapping(program)
223
+ environments = (program && program[:environments]) || {}
224
+ { conditions: environments.to_h { |name, e| [name.to_s, JSON.generate(e[:conditions])] }, defaults: JSON.generate(program && program[:defaultEnvironments]) }
225
+ end
226
+
227
+ #: (Array[String], Array[String], String, Hash[Symbol, untyped]?, Hash[Symbol, untyped]?) -> Hash[Symbol, untyped]
228
+ def compare_mapping(head_files, ref_files, base_project, head_program, ref_program)
229
+ head = mapping_files(head_files, @top)
230
+ ref = mapping_files(ref_files, @base_top)
231
+ files = (head.keys | ref.keys).select { head[_1] != ref[_1] }.sort
232
+ config_hash = ->(root) { File.exist?(File.join(root, CONFIG)) ? hash_of(File.join(root, CONFIG)) : nil }
233
+ config = config_hash.(@project) != config_hash.(base_project)
234
+ after = program_mapping(head_program && { environments: (head_program[:environments] || {}).transform_keys(&:to_s), defaultEnvironments: head_program[:defaultEnvironments] })
235
+ if ref_program&.dig(:problem)
236
+ conditions = after[:conditions].keys.sort
237
+ defaults = true
238
+ else
239
+ before = program_mapping(ref_program)
240
+ none = JSON.generate(nil)
241
+ conditions = (before[:conditions].keys | after[:conditions].keys).select { before[:conditions].fetch(_1, none) != after[:conditions].fetch(_1, none) }.sort
242
+ defaults = before[:defaults] != after[:defaults]
243
+ end
244
+ changed = files.any? || config || conditions.any? || defaults || !ref_program&.dig(:problem).nil?
245
+ { changed: changed, files: files, config: config, conditions: conditions, default_environments: defaults }
246
+ end
247
+
248
+ #: (String, String) -> void
249
+ def copy(from, to)
250
+ FileUtils.mkdir_p(File.dirname(to))
251
+ FileUtils.rm_rf(to)
252
+ File.symlink?(from) ? File.symlink(File.readlink(from), to) : FileUtils.cp(from, to)
253
+ end
254
+
255
+ # The ref's checkout loses the ref's mapping and gains head's; the
256
+ # ref's program file stays, or head's comes in when the ref has none.
257
+ #: (Array[String], Array[String]) -> void
258
+ def overlay_base_tree(head_files, ref_files)
259
+ ref_files.select { mapping?(_1) }.each { FileUtils.rm_f(File.join(@base_top, _1)) }
260
+ head_files.select { mapping?(_1) }.each { copy(File.join(@top, _1), File.join(@base_top, _1)) }
261
+ program = in_repo(PROGRAM)
262
+ copy(File.join(@top, program), File.join(@base_top, program)) if !ref_files.include?(program) && head_files.include?(program)
263
+ end
264
+
265
+ # Head's working tree with the ref's mapping in place of its own,
266
+ # written before the base checkout is overlaid.
267
+ #: (Array[String], Array[String]) -> void
268
+ def write_old_tree(head_files, ref_files)
269
+ head_files.reject { mapping?(_1) }.each { copy(File.join(@top, _1), File.join(@old_top, _1)) }
270
+ ref_files.select { mapping?(_1) }.each { copy(File.join(@base_top, _1), File.join(@old_top, _1)) }
271
+ end
272
+ end
273
+ end
274
+ end