featureparity 0.0.32 → 0.0.34

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: dc148bcfad876dfa40128241e661004d4469788e2c943263446513fa2023c61a
4
- data.tar.gz: 1dc7dd025ad5e7d228cdefa76d2c40ccdbbd7a74ab1ff8a64e642f05625cdaf3
3
+ metadata.gz: aafad86b986d2525cc70638c90b69adae68811060c936a7ed8dd509fb1daa1b6
4
+ data.tar.gz: 123666707b9d8a6df2e7cba775e7aff6856c40aa9bff4f46feeed6a6559e0d6e
5
5
  SHA512:
6
- metadata.gz: 1e66acc239526910b5a67ea8436f056b4437ce2292cc825e367671e15b936e11cbb43a83bf2417e894901bd2203ecf0caefb9763adc4f25e1e1fb58c55587c5d
7
- data.tar.gz: a63607ba0033c147e8ed262eee5d484b0026c56e46c17d097d6a349b06cec43aae472347d0e744fa04486110ffb7e842907f78d8c211fe4a66fb64f9e72da915
6
+ metadata.gz: 7bead9325320839ed572b4a25f6e7fffe369b148be92cfce1c60c139704e8f8bcc44f54ff48bb6bda58651d9727235cd059b0288d6257657a9f7839074dd35c4
7
+ data.tar.gz: c6fc3aeb020b2535f9e1cdcc438eeab6697475218f219b3e35657c531f59be71659bfba004457f5d7a9c93e490e003dd4055b33b53ee3e48ca0c0c10e4d4a26a
data/lib/fp/cli.rb CHANGED
@@ -38,7 +38,9 @@ module Fp
38
38
  'repos' => Commands::Repos,
39
39
  'setup' => Commands::Setup,
40
40
  'whoami' => Commands::Whoami,
41
+ 'skill' => Commands::Skill,
41
42
  'version' => Commands::Version,
43
+ 'update' => Commands::Update,
42
44
  'help' => Commands::Help,
43
45
  'attach' => Commands::Attach,
44
46
  'attachments' => Commands::Attachments,
@@ -83,7 +85,7 @@ module Fp
83
85
 
84
86
  # Profile/config commands don't need auth. `init` is here too: it only writes
85
87
  # files into the repo, and onboarding a repo must work before anyone has a key.
86
- needs_auth = !%w[init doctor profile config repos setup whoami version help mark tutorial].include?(command_name)
88
+ needs_auth = !%w[init doctor profile config repos setup whoami skill version update help mark tutorial].include?(command_name)
87
89
 
88
90
  if needs_auth
89
91
  config = Config.new(profile: global_opts[:profile], api_url: global_opts[:api_url])
@@ -95,11 +97,14 @@ module Fp
95
97
  client = Client.new(config)
96
98
  else
97
99
  config = Config.new(profile: global_opts[:profile], api_url: global_opts[:api_url])
100
+ # whoami asks the API who the key acts as, but still works with no valid key.
101
+ client = Client.new(config) if command_name == 'whoami' && config.valid?
98
102
  end
99
103
 
100
104
  output = Output.new(json: global_opts[:json])
101
105
  command = command_class.new(client: client, output: output, config: config)
102
106
  command.run(args + passthrough)
107
+ announce_update(config, command_name, json: global_opts[:json])
103
108
  rescue Interrupt
104
109
  warn "\nAborted."
105
110
  exit 130
@@ -111,6 +116,15 @@ module Fp
111
116
 
112
117
  private
113
118
 
119
+ # At most once a day, say on stderr that a newer fp is published (Fizzy #1993).
120
+ # Never with --json: a caller reading that stream gets the envelope and nothing else.
121
+ def announce_update(config, command_name, json:)
122
+ return if json
123
+
124
+ notice = UpdateCheck.daily_notice(config.api_url, command: command_name)
125
+ warn "\n#{notice}" if notice
126
+ end
127
+
114
128
  # True when the remaining args ask for help on the command: `--help` or `-h`
115
129
  # anywhere in the args. We don't treat a lone `help` positional specially here —
116
130
  # that's a real subcommand for some commands.
data/lib/fp/client.rb CHANGED
@@ -22,6 +22,11 @@ module Fp
22
22
  get("/api/projects/#{id}")
23
23
  end
24
24
 
25
+ # GET /whoami — who the key acts as (key name and owner)
26
+ def whoami
27
+ get('/api/whoami')
28
+ end
29
+
25
30
  # POST /projects
26
31
  def create_project(params)
27
32
  post('/api/projects', params)
@@ -281,6 +281,7 @@ module Fp
281
281
  print_inherited(report)
282
282
  print_orphans(report)
283
283
  print_pending_reviews(report, project_slug)
284
+ print_retirements(report)
284
285
  print_unscoped_warning(summary, project_slug)
285
286
  print_next_steps(report, violations)
286
287
  print_verdict(passed, violations, opts, report)
@@ -333,6 +334,34 @@ module Fp
333
334
  puts
334
335
  end
335
336
 
337
+ # Retired requirements whose tests still run somewhere: a removal was approved, but
338
+ # the feature hasn't come out of every surface yet (Fizzy #1820). It fails the gate
339
+ # wherever `missing` does — the server decides (`retirements_violate`, already
340
+ # folded into `passing`); here it is rendered as a violation or a note. On a pull
341
+ # request only the surfaces this run put it back on count.
342
+ def print_retirements(report)
343
+ retirements = report['retirements'] || []
344
+ return if retirements.empty?
345
+
346
+ violates = report['retirements_violate']
347
+ lead = "#{retirements.size} retired requirement(s) still shipping — the removal was approved, " \
348
+ 'but their tests still run'
349
+ puts violates ? "#{lead} (a violation at this level):" : "#{lead} (not failing the gate at this level):"
350
+ headers = %w[SLUG STILL_SHIPPING_ON REMOVED_FROM]
351
+ headers << 'ADDED_BY_THIS_CHANGE' if report['pull_request']
352
+ output.table(
353
+ headers,
354
+ retirements.map do |r|
355
+ row = [r['slug'], Array(r['still_shipping_on']).join(', '), Array(r['removed_from']).join(', ')]
356
+ row << Array(r['introduced_on']).join(', ') if report['pull_request']
357
+ row
358
+ end
359
+ )
360
+ hint = retirements.first['action_hint']
361
+ puts "Next step (agent): #{hint}" if hint
362
+ puts
363
+ end
364
+
336
365
  def print_violations(violations, report = {})
337
366
  return if violations.empty?
338
367
 
@@ -7,13 +7,15 @@ module Fp
7
7
  # fp doctor [--dir PATH] [--json]
8
8
  #
9
9
  # Says whether fp will work here, and what this repo needs before its tests can report
10
- # (Fizzy #1786). Purely local: no API calls, no key needed.
10
+ # (Fizzy #1786). No key needed. Everything is read locally except the newest published
11
+ # version (Fizzy #1993), one unauthenticated lookup that is skipped when it can't be made.
11
12
  #
12
13
  # Ruby which Ruby is running fp, where the gem lives, and whether this directory
13
14
  # pins a different Ruby (.ruby-version, .tool-versions, mise.toml). A
14
15
  # version-manager shim resolves `fp` against the *pinned* Ruby, so a gem
15
16
  # installed under another one fails inside the repo with
16
17
  # `mise ERROR No version is set for shim: fp` and works from /tmp.
18
+ # Also whether a newer fp is published, and the command that installs it.
17
19
  # Config the API environment (warning off production), whether a key resolved,
18
20
  # and which .featureparity.yml applies.
19
21
  # Repo RepoDetector's summary: test runners and the command that makes each emit
@@ -28,7 +30,7 @@ module Fp
28
30
  help_flag :dir, 'Directory to check (defaults to the working directory)'
29
31
  help_example 'fp doctor'
30
32
  help_example 'fp doctor --json', 'Machine-readable, for an agent to act on'
31
- help_note "Purely local; makes no API calls, so it works without a key.\n" \
33
+ help_note "Works without a key and offline. Its one network call asks the API for the newest fp version.\n" \
32
34
  "If `fp` itself fails with `mise ERROR No version is set for shim: fp`, the shim stopped it\n" \
33
35
  'before fp could run: install the gem under the pinned Ruby (`gem install featureparity` in the repo).'
34
36
 
@@ -51,6 +53,7 @@ module Fp
51
53
  repo: RepoDetector.new(repo_root(dir)).detect
52
54
  }
53
55
  report[:agents_section] = agents_section_report(repo_root(dir))
56
+ report[:update] = UpdateCheck.status(config.api_url) unless UpdateCheck.disabled?
54
57
 
55
58
  output.success(report) { print_report(report) }
56
59
  end
@@ -187,6 +190,18 @@ module Fp
187
190
  end
188
191
  end
189
192
 
193
+ def print_update(update)
194
+ line = if update[:latest_version].nil?
195
+ 'could not check (offline, or the API is unreachable)'
196
+ elsif update[:update_available]
197
+ "#{update[:latest_version]} — newer than this one. Run `#{update[:update_command]}` " \
198
+ "(or `#{UpdateCheck::GEM_COMMAND}`)."
199
+ else
200
+ "#{update[:latest_version]} (up to date)"
201
+ end
202
+ puts " Latest fp: #{line}"
203
+ end
204
+
190
205
  def print_report(report)
191
206
  ruby = report[:ruby]
192
207
  cfg = report[:config]
@@ -195,6 +210,7 @@ module Fp
195
210
  puts "fp #{ruby[:fp_version]} on Ruby #{ruby[:version]} (#{ruby[:ruby]})"
196
211
  puts " Gem: #{ruby[:gem_path]}"
197
212
  puts " fp on PATH: #{ruby[:fp_on_path] || '(not found)'}#{ruby[:fp_on_path_is_shim] ? ' [version-manager shim]' : ''}"
213
+ print_update(report[:update]) if report[:update]
198
214
  if ruby[:pinned]
199
215
  state = ruby[:mismatch] ? '⚠ differs from the Ruby running fp' : 'matches'
200
216
  puts " Ruby pin: #{ruby[:pinned]} (#{ruby[:pinned_by]}) — #{state}"
@@ -108,9 +108,11 @@ module Fp
108
108
  profile add|list Manage named profiles
109
109
  config set|get|unset|list Manage global settings
110
110
  whoami Show the resolved config (profile, env, API URL, key)
111
+ skill install [--agent X] Install the bundled agent skill (.claude/skills, .agents/skills)
111
112
  repos set|get|list|unset Map surfaces to local repo paths
112
113
  setup Interactive first-time setup
113
114
  version Show version (also: fp --version, fp -v)
115
+ update [--check] Install the newest fp, or check whether one is available
114
116
  help Show this help
115
117
 
116
118
  GLOBAL FLAGS
@@ -255,6 +257,10 @@ module Fp
255
257
  fp whoami --json
256
258
  fp --profile staging whoami
257
259
 
260
+ # Install the agent skill that ships with this gem (.claude/skills/fp, .agents/skills/fp)
261
+ fp skill install
262
+ fp skill install --agent claude --global
263
+
258
264
  # Non-interactive setup for CI/automation
259
265
  fp setup --api-key fp_... --profile ci-agent --non-interactive
260
266
 
@@ -533,6 +533,21 @@ module Fp
533
533
  end
534
534
  end
535
535
 
536
+ # How to get a report out of the suite, said for the repo's first detected test
537
+ # runner (Fizzy #1991). A pytest repo was told about RSpec's JSON report first.
538
+ def report_shortcut
539
+ runner = ((@detection || {})['test_runners'] || []).first
540
+ if runner && runner['fp_run'] && runner['name'] != 'rspec'
541
+ "To run the suite and report in one step, with no formatter added to the project:\n" \
542
+ "`#{runner['fp_run']}`. Or write the report yourself with\n" \
543
+ "`#{runner['report_command']}` and pass it to `--junit`."
544
+ else
545
+ "`--junit` also takes RSpec's own `--format json` report. To run the suite and report in\n" \
546
+ "one step with no formatter added to the project (rspec, pytest, vitest, playwright):\n" \
547
+ '`fp run --surface <surface> --repo <org/repo> -- <test command>`.'
548
+ end
549
+ end
550
+
536
551
  def agents_section(project_slug)
537
552
  <<~MARKDOWN
538
553
  #{AGENTS_MARKER}
@@ -638,9 +653,7 @@ module Fp
638
653
  --work-item <card-or-issue-url>
639
654
  ```
640
655
 
641
- `--junit` also takes RSpec's own `--format json` report. To run the suite and report in
642
- one step with no formatter added to the project (rspec, pytest, vitest, playwright):
643
- `fp run --surface <surface> --repo <org/repo> -- <test command>`.
656
+ #{report_shortcut}
644
657
 
645
658
  Report `present` or `stub` only — **never** claim `passing`/`failing`. Those are CI's
646
659
  to write, via `fp ci-report`, and the gate trusts them precisely because agents can't
@@ -1,27 +1,52 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require 'digest'
4
+ require 'fileutils'
5
+ require 'json'
6
+ require 'tmpdir'
7
+
3
8
  module Fp
4
9
  module Commands
5
- # fp mark <slug> <file>:<line> [--surface a,b] [--type e2e] [--comment '#'] [--dry-run]
10
+ # fp mark <slug> <file>:<line>|<file>::<test name> [more targets…] [--surface a,b] [--type e2e]
11
+ # [--comment '#'] [--dry-run]
12
+ #
13
+ # Insert an fp:<slug> marker directly above a test, in that file's own comment syntax
14
+ # and indentation (Fizzy #1786). Marking by hand across Ruby, JS, Swift and SQL meant a
15
+ # script per language and the occasional marker the scanner didn't recognise; this
16
+ # writes one the scanner reads back, and says which test it binds to. Purely local: no
17
+ # API key, no network.
6
18
  #
7
- # Insert an fp:<slug> marker directly above the test at <file>:<line>, in that
8
- # file's own comment syntax and indentation (Fizzy #1786). Marking by hand across
9
- # Ruby, JS, Swift and SQL meant a script per language and the occasional marker the
10
- # scanner didn't recognise; this writes one the scanner reads back, and says which
11
- # test it binds to. Purely local: no API key, no network.
19
+ # A test can be named instead of numbered (`file::test name`), and several targets can
20
+ # go in one call (Fizzy #1987). An agent that reads a file once and then marks three of
21
+ # its tests by line number put the second and third markers one and two lines too low,
22
+ # because each insert pushes everything below it down. A name is found in the file as
23
+ # it is when the command runs, and the line numbers given in one call all refer to the
24
+ # file before that call changes it.
25
+ #
26
+ # Separate calls are covered too (Fizzy #1991). fp remembers the marker lines it put
27
+ # into a file for a while, and while nothing else has edited that file, a line number
28
+ # that no longer points at a test is also read as it was numbered before those
29
+ # markers went in. So `fp mark a f:3`, `fp mark b f:7`, `fp mark c f:11`, all from one
30
+ # read of the file, land on the three tests that were on lines 3, 7 and 11.
12
31
  class Mark < Base
13
32
  help_summary 'Insert an fp:<slug> marker above a test, in the file\'s own comment syntax'
14
- help_usage 'fp mark <slug> <file>:<line> [--surface a,b] [--type <test-type>] [--dry-run]'
33
+ help_usage 'fp mark <slug> <file>:<line>|<file>::<test name> [more targets…] [--surface a,b] [--type <test-type>] [--dry-run]'
15
34
  help_flag :surface, 'Pin the marker to these surfaces (fp:slug@a,b); omit to use --surface at report time'
16
35
  help_flag :type, 'Pin the kind of test (fp:slug@surface:e2e); needs --surface'
17
36
  help_flag :comment, "Comment prefix to use when the extension isn't known (e.g. '#', '//', '--')"
18
37
  help_flag :dry_run, 'Show the marker and where it would go; change nothing'
19
38
  help_example 'fp mark academic_experience_required_fields spec/models/academic_experience_spec.rb:52'
39
+ help_example "fp mark locker_rejects_oversize tests/test_parcel_locker.py::test_rejects_oversize_parcel"
40
+ help_example "fp mark required_fields 'spec/models/user_spec.rb::requires an email' spec/models/user_spec.rb:40"
20
41
  help_example 'fp mark checkout_flow e2e/checkout.spec.ts:10 --surface web --type e2e'
21
- help_note "<line> is the test's own line (the `it`/`test`/`def test_` line); the marker goes directly above it.\n" \
22
- "Each insert shifts every line below it down by one. Marking several tests in one file from a single read of it?\n" \
23
- "Mark from the bottom of the file upward, or re-read the line numbers between marks. The \"It binds to:\" line is the check:\n" \
24
- "if it names the wrong test, or fp warns that no test declaration was recognised, the marker landed on the wrong line.\n" \
42
+ help_note "A target is <file>:<line> (the `it`/`test`/`def test_` line) or <file>::<test name> (the name as the file declares it;\n" \
43
+ "a pytest id like file.py::TestClass::test_x works too). The marker goes directly above the test.\n" \
44
+ "Marking several tests in one file? Name them, and the line numbers can't go stale. Line numbers given in one call\n" \
45
+ "all refer to the file before that call. Across separate calls each insert shifts the lines below it down by one;\n" \
46
+ "fp allows for the markers it added itself, so line numbers from one read of the file keep working, and it says\n" \
47
+ "so when it moved one. If a number could mean two tests, fp asks for the name instead of guessing.\n" \
48
+ "The \"It binds to:\" line is the check: if it names the wrong test, or fp warns that no test declaration was\n" \
49
+ "recognised, the marker landed on the wrong line.\n" \
25
50
  'Marking a test binds it to a requirement: never mark a test that is currently failing to make it count.'
26
51
 
27
52
  KNOWN_FLAGS = {
@@ -44,18 +69,25 @@ module Fp
44
69
  SLUG_RE = /\A[a-z0-9][a-z0-9_-]*\z/.freeze
45
70
  KEY_RE = /\A[a-z0-9_-]+\z/.freeze
46
71
 
72
+ # How many of a file's test names to list when a named test isn't there.
73
+ NAMES_SHOWN = 12
74
+
75
+ # How long fp remembers the markers it inserted into a file, in seconds. Long enough
76
+ # for an agent working down a file from one read of it, short enough that a line
77
+ # number from a later, fresh read is rarely second-guessed.
78
+ JOURNAL_TTL = 30 * 60
79
+
47
80
  def run(args)
48
81
  opts, positional = parse_flags(args, KNOWN_FLAGS)
49
- slug, location = positional
82
+ slug, *locations = positional
50
83
 
51
- unless slug && location
52
- output.error('Usage: fp mark <slug> <file>:<line>')
84
+ if slug.nil? || locations.empty?
85
+ output.error('Usage: fp mark <slug> <file>:<line>|<file>::<test name> [more targets…]')
53
86
  exit 1
54
87
  end
55
88
 
56
89
  fail_with("'#{slug}' isn't a valid slug (lowercase letters, numbers, - and _).") unless slug.match?(SLUG_RE)
57
90
 
58
- path, line_no = parse_location(location)
59
91
  surfaces = (opts[:surface] || '').split(',').map(&:strip).reject(&:empty?)
60
92
  bad = surfaces.reject { |s| s.match?(KEY_RE) }
61
93
  fail_with("Invalid surface key(s): #{bad.join(', ')}") unless bad.empty?
@@ -64,50 +96,195 @@ module Fp
64
96
  fail_with('--type needs --surface: a marker pins its kind after its surfaces (fp:slug@api:e2e)') if surfaces.empty?
65
97
  end
66
98
 
99
+ marker = "fp:#{slug}"
100
+ marker += "@#{surfaces.join(',')}" unless surfaces.empty?
101
+ marker += ":#{opts[:type]}" if opts[:type]
102
+
103
+ # Resolve every target against the files as they are now, before anything is
104
+ # written, so one target can't move another and a bad target changes nothing.
105
+ targets = locations.map { |location| parse_location(location) }
106
+ files = targets.map { |t| t[:path] }.uniq.to_h { |path| [path, File.read(path).lines] }
107
+ earlier = files.to_h { |path, lines| [path, earlier_inserts(path, lines)] }
108
+ targets.each { |t| t[:line] = resolve_line(t, files[t[:path]], earlier[t[:path]]) }
109
+ targets = targets.uniq { |t| [t[:path], t[:line]] }
110
+
111
+ results = targets.group_by { |t| t[:path] }.flat_map do |path, file_targets|
112
+ mark_file(path, files[path], file_targets, slug, marker, opts, earlier[path])
113
+ end
114
+
115
+ report(results)
116
+ end
117
+
118
+ private
119
+
120
+ # Insert the marker above each target in one file. Targets go in from the bottom up,
121
+ # so every line number still means what it meant when the command started; each
122
+ # result's `line` is then where its marker sits in the file as written.
123
+ def mark_file(path, lines, file_targets, slug, marker, opts, earlier = [])
67
124
  prefix = opts[:comment] || comment_prefix_for(path)
68
125
  unless prefix
69
126
  fail_with("Don't know the comment syntax for #{File.basename(path)}. Pass --comment, e.g. --comment '#' or --comment '//'.")
70
127
  end
71
128
 
72
- lines = File.read(path).lines
73
- if line_no > lines.length
74
- fail_with("#{path} has #{lines.length} line(s); there is no line #{line_no}.")
75
- end
129
+ updated = lines.dup
130
+ results = file_targets.sort_by { |t| -t[:line] }.map do |target|
131
+ line_no = target[:line]
132
+ if already_marked?(updated, line_no, marker)
133
+ next { file: path, original_line: line_no, marker: marker, already: true }
134
+ end
76
135
 
77
- marker = "fp:#{slug}"
78
- marker += "@#{surfaces.join(',')}" unless surfaces.empty?
79
- marker += ":#{opts[:type]}" if opts[:type]
136
+ test_line = updated[line_no - 1]
137
+ comment_line = "#{test_line[/\A[ \t]*/]}#{prefix} #{marker}#{line_ending(test_line)}"
138
+ updated.insert(line_no - 1, comment_line)
139
+ found = Fp::JUnit.scan_markers(updated.join).find { |m| m[:line] == line_no && m[:slug] == slug }
140
+ unless found
141
+ fail_with("A '#{prefix}' comment isn't one fp's scanner reads as a marker. Use #, //, -- or /* … */.")
142
+ end
80
143
 
81
- target = lines[line_no - 1]
82
- indent = target[/\A[ \t]*/]
83
- comment_line = "#{indent}#{prefix} #{marker}#{line_ending(target)}"
144
+ { file: path, original_line: line_no, marker: marker, found: found, comment_line: comment_line.strip,
145
+ given_line: target[:given_line] }
146
+ end
84
147
 
85
- if already_marked?(lines, line_no, marker)
86
- return report(path, line_no, marker, nil, already: true)
148
+ File.write(path, updated.join) unless opts[:dry_run]
149
+
150
+ # A marker moves down one line for every marker inserted above it.
151
+ inserted = results.reject { |r| r[:already] }.map { |r| r[:original_line] }
152
+ results = results.sort_by { |r| r[:original_line] }.map do |r|
153
+ r.merge(line: r[:original_line] + inserted.count { |l| l < r[:original_line] }, dry_run: opts[:dry_run])
87
154
  end
88
155
 
89
- updated = lines.dup.insert(line_no - 1, comment_line)
90
- found = Fp::JUnit.scan_markers(updated.join).find { |m| m[:line] == line_no && m[:slug] == slug }
91
- unless found
92
- fail_with("A '#{prefix}' comment isn't one fp's scanner reads as a marker. Use #, //, -- or /* … */.")
156
+ unless opts[:dry_run] || inserted.empty?
157
+ # Markers from earlier calls move down too: one line for each insert at or above them.
158
+ moved = earlier.map { |line| line + inserted.count { |l| l <= line } }
159
+ remember_inserts(path, updated, moved + results.reject { |r| r[:already] }.map { |r| r[:line] })
93
160
  end
161
+ results
162
+ end
94
163
 
95
- File.write(path, updated.join) unless opts[:dry_run]
96
- report(path, line_no, marker, found, dry_run: opts[:dry_run], comment_line: comment_line.chomp)
164
+ # The marker lines fp inserted into this file in earlier calls, as line numbers in the
165
+ # file as it stands, oldest first. Empty once anything else has edited the file (its
166
+ # content no longer matches what fp wrote) or the note is older than JOURNAL_TTL.
167
+ def earlier_inserts(path, lines)
168
+ note = JSON.parse(File.read(journal_file(path)))
169
+ return [] unless note['sha'] == Digest::SHA256.hexdigest(lines.join)
170
+ return [] if Time.now.to_i - note['at'].to_i > JOURNAL_TTL
171
+
172
+ Array(note['inserted']).map(&:to_i)
173
+ rescue StandardError
174
+ []
97
175
  end
98
176
 
99
- private
177
+ # Best effort: without the note, line numbers are simply read as the file stands.
178
+ def remember_inserts(path, lines, inserted)
179
+ file = journal_file(path)
180
+ FileUtils.mkdir_p(File.dirname(file), mode: 0o700)
181
+ Dir.glob(File.join(File.dirname(file), '*.json')).each do |old|
182
+ File.delete(old) if Time.now - File.mtime(old) > JOURNAL_TTL
183
+ end
184
+ File.write(file, JSON.generate('sha' => Digest::SHA256.hexdigest(lines.join), 'at' => Time.now.to_i,
185
+ 'inserted' => inserted))
186
+ rescue StandardError
187
+ nil
188
+ end
100
189
 
190
+ def journal_file(path)
191
+ File.join(Dir.tmpdir, "fp-mark-#{Process.uid}", "#{Digest::SHA256.hexdigest(File.expand_path(path))}.json")
192
+ end
193
+
194
+ # <file>::<test name> or <file>:<line>. The name form is checked first, so a test
195
+ # named with digits isn't read as a line number.
101
196
  def parse_location(location)
197
+ if (m = location.match(/\A(.+?)::(.+)\z/))
198
+ path = m[1]
199
+ fail_with("No such file: #{path}") unless File.file?(path)
200
+ return { path: path, name: m[2] }
201
+ end
202
+
102
203
  m = location.match(/\A(.+):(\d+)\z/)
103
- fail_with("Give the test's location as <file>:<line> (got '#{location}').") unless m
204
+ fail_with("Give the test's location as <file>:<line> or <file>::<test name> (got '#{location}').") unless m
104
205
 
105
206
  path = m[1]
106
207
  line_no = m[2].to_i
107
208
  fail_with("No such file: #{path}") unless File.file?(path)
108
209
  fail_with('Line numbers start at 1.') if line_no < 1
109
210
 
110
- [path, line_no]
211
+ { path: path, line: line_no }
212
+ end
213
+
214
+ def resolve_line(target, lines, earlier = [])
215
+ path = target[:path]
216
+ if target[:name]
217
+ line_for_name(path, lines, target[:name])
218
+ else
219
+ fail_with("#{path} has #{lines.length} line(s); there is no line #{target[:line]}.") if target[:line] > lines.length
220
+ line = line_allowing_for_earlier_marks(path, lines, target[:line], earlier)
221
+ target[:given_line] = target[:line] if line != target[:line]
222
+ line
223
+ end
224
+ end
225
+
226
+ # A line number may have been read before fp's earlier markers pushed the file's
227
+ # lines down. Read it both ways: as the file stands, and as it was numbered before
228
+ # each run of those markers went in. When exactly one reading lands on a test
229
+ # declaration, that is the test. When none does, the number is taken as given, as it
230
+ # always was. When several do, nothing says which was meant, so nothing is written.
231
+ def line_allowing_for_earlier_marks(path, lines, given, earlier)
232
+ return given if earlier.empty?
233
+
234
+ readings = (0..earlier.length).filter_map { |known| line_numbered_without(lines, given, earlier[known..]) }.uniq
235
+ tests = readings.select { |line| Fp::JUnit.test_declared_on(lines[line - 1]) }
236
+ return given if tests.empty?
237
+ return tests.first if tests.length == 1
238
+
239
+ choices = tests.sort.map do |line|
240
+ name = Fp::JUnit.test_declared_on(lines[line - 1]).first
241
+ " #{path}::#{name} (line #{line} now)"
242
+ end
243
+ fail_with("fp added markers to #{path} a moment ago, so line #{given} could mean more than one test. " \
244
+ "Name the one you mean:\n#{choices.join("\n")}")
245
+ end
246
+
247
+ # The line that was numbered `given` before the marker lines in `unseen` existed.
248
+ def line_numbered_without(lines, given, unseen)
249
+ count = 0
250
+ (1..lines.length).each do |line|
251
+ next if unseen.include?(line)
252
+
253
+ count += 1
254
+ return line if count == given
255
+ end
256
+ nil
257
+ end
258
+
259
+ # The line declaring the test called `name`. Tried as given, then as the last part
260
+ # of a pytest id (TestClass::test_x), then without a pytest parameter suffix
261
+ # (test_x[case-1]), so an id copied out of a runner's output finds its test.
262
+ def line_for_name(path, lines, name)
263
+ declared = lines.each_with_index.filter_map do |line, i|
264
+ decl = Fp::JUnit.test_declared_on(line)
265
+ [decl.first, i + 1] if decl
266
+ end
267
+
268
+ candidates = [name, name.split('::').last]
269
+ candidates += candidates.map { |n| n.sub(/\[[^\]]*\]\z/, '') }
270
+ candidates.uniq.each do |candidate|
271
+ hits = declared.select { |n, _| n == candidate }.map(&:last)
272
+ return hits.first if hits.length == 1
273
+ next if hits.empty?
274
+
275
+ fail_with("#{path} declares '#{candidate}' more than once (lines #{hits.join(', ')}). " \
276
+ "Mark it as #{path}:<line> instead.")
277
+ end
278
+
279
+ known = declared.map(&:first).uniq
280
+ hint = if known.empty?
281
+ 'fp recognises no test declarations in it; mark it as <file>:<line> instead.'
282
+ else
283
+ shown = known.first(NAMES_SHOWN).map { |n| " #{n}" }.join("\n")
284
+ more = known.length > NAMES_SHOWN ? "\n …and #{known.length - NAMES_SHOWN} more" : ''
285
+ "The tests it declares:\n#{shown}#{more}"
286
+ end
287
+ fail_with("No test named '#{name}' in #{path}. #{hint}")
111
288
  end
112
289
 
113
290
  def comment_prefix_for(path)
@@ -140,24 +317,36 @@ module Fp
140
317
  s
141
318
  end
142
319
 
143
- def report(path, line_no, marker, found, already: false, dry_run: false, comment_line: nil)
144
- data = { file: path, line: line_no, marker: marker, already_marked: already, dry_run: dry_run,
145
- binds_to: found && found[:title] }.compact
146
- output.success(data) do
147
- if already
148
- puts "#{path}:#{line_no} is already marked #{marker}; nothing changed."
149
- next
150
- end
320
+ def report(results)
321
+ data = results.map do |r|
322
+ { file: r[:file], line: r[:line], marker: r[:marker], already_marked: r[:already] || false,
323
+ dry_run: r[:dry_run] || false, binds_to: r[:found] && r[:found][:title] }.compact
324
+ end
325
+ # One target answers with the one object it always has; several with a list.
326
+ output.success(data.length == 1 ? data.first : { marks: data }) do
327
+ results.each { |r| print_result(r) }
328
+ end
329
+ end
151
330
 
152
- verb = dry_run ? 'Would insert' : 'Inserted'
153
- puts "#{verb} at #{path}:#{line_no}:"
154
- puts " #{comment_line.strip}"
155
- if found[:title]
156
- puts "It binds to: #{found[:title]}"
157
- else
158
- puts "⚠️ No test declaration was recognised below line #{line_no}. Check that the line is the test itself;"
159
- puts ' if the runner reports file paths, the marker still binds by file.'
160
- end
331
+ def print_result(result)
332
+ path = result[:file]
333
+ line_no = result[:line]
334
+ if result[:already]
335
+ puts "#{path}:#{line_no} is already marked #{result[:marker]}; nothing changed."
336
+ return
337
+ end
338
+
339
+ if result[:given_line]
340
+ puts "Line #{result[:given_line]} was numbered before fp's earlier markers in #{path}; that test is on line #{result[:original_line]} now."
341
+ end
342
+ verb = result[:dry_run] ? 'Would insert' : 'Inserted'
343
+ puts "#{verb} at #{path}:#{line_no}:"
344
+ puts " #{result[:comment_line]}"
345
+ if result[:found][:title]
346
+ puts "It binds to: #{result[:found][:title]}"
347
+ else
348
+ puts "⚠️ No test declaration was recognised below line #{line_no}. Check that the line is the test itself;"
349
+ puts ' if the runner reports file paths, the marker still binds by file.'
161
350
  end
162
351
  end
163
352
 
@@ -201,6 +201,9 @@ module Fp
201
201
  else
202
202
  puts " Status: #{e['status']}"
203
203
  end
204
+ # The requirement was retired and the default branch's CI no longer runs
205
+ # this test: the feature is out of this surface (Fizzy #1820).
206
+ puts " Removed: #{e['removed_at']} (CI no longer runs this test)" if e['removed_at']
204
207
  # A pull request's CI may have written over the merged verdict; show both
205
208
  # when they differ so "failing" next to "PR: …" reads as the branch's
206
209
  # result, not the default branch's.