Class: Mutineer::CLI

Inherits:
Object
  • Object
show all
Defined in:
lib/mutineer/cli.rb

Overview

Command-line entry point. start is the single public method called by bin/mutineer; it parses argv, acts, and exits with a pinned code.

Exit codes:

0  success / requested output (--version, --help, score >= threshold)
1  survivors below threshold, a runtime error, or an ignore id
 `migrate` could not map
2  usage / flag error (unknown subcommand, invalid flag, unknown operator,
 out-of-range threshold)

Constant Summary collapse

UNPAIRED_RUN_HINT =

How to run a source that pairing skipped. The reporter keeps its own copy of the longer hint.

"Add a test at the conventional path, or run those sources in a separate command with --test."
<<~USAGE
  Usage: mutineer [options] <command> [args]

  Commands:
    run [options] <source...> [--test <test>...]
                                                 Mutate, run, and report
    run --dry-run [options] <source...>          Print candidate mutations only
    triage REPORT.json --reason TEXT
        (--id ID ... | --all)                    Print ignore: entries for
                                                 survivors and for each copy
                                                 dropped as a repeat of one.
                                                 Does not edit files.
    migrate [options] <source...>                Rewrite old ignore ids in
                                                 .mutineer.yml. --dry-run lists
                                                 each change and every entry
                                                 that matches no mutant, writes
                                                 nothing, and exits 1 for a miss.
                                                 run warns and still exits 0
    init [--rails] [--force]                     Write .mutineer.yml and print
                                                 the first run command.
                                                 --force replaces an existing file.
    config KEY [run options]                     Print the cache_dir or baseline
                                                 that run would use. Writes nothing

  Run options:
    --test PATH          Test file, directory or quoted glob (repeat for more).
                         Omit to pair each source with its test by convention
                         and any tests: map in .mutineer.yml (not under
                         --dry-run). A source at app/<dir>/concerns/ with no
                         test there also pairs with a split test at its
                         namespace path.
                         --test replaces pairing and the map
    --operators LIST     Comma-separated operator names (default: Tier 1 set)
    --threshold FLOAT    Fail (exit 1) when score < FLOAT (default: 0 = off)
    --baseline FILE      Fail (exit 1) on NEW survivors / score drop vs a prior
                         --format json run (CI delta gate)
    --baseline-epsilon FLOAT  Score-drop tolerance for --baseline (default: 0)
    --only NAME          Restrict to one fully-qualified subject
    --since REF          Only mutate lines changed since git REF (e.g. origin/main)
    --no-since           Disable diff scoping (a typed no beats a .mutineer.yml since:)
    --jobs N             Parallel worker count (default: processor count);
                         --test-command, --fail-fast, or --rails
                         without --daemon forces 1
    --strategy NAME      reload (whole-file) or redefine (surgical); default: reload
    --timeout SECONDS    Per-mutant time limit for in-process runs (default: 10;
                         not with --daemon or --test-command); a mutant over it
                         is a timeout, excluded from the score
    --capture-timeout SECONDS  Time limit for each coverage-capture subprocess
                         and the clean check (default: 120; not with --test-command);
                         the combined clean check gets the larger of this and
                         1.5x its files' summed capture time, rounded up
    --cache-dir DIR      Directory for the coverage cache (default: .mutineer;
                         not with --test-command)
    --coverage-from FILE Reuse the coverage.json of a --rails/--boot capture over
                         these sources or more; runs alone only the tests that
                         cover these sources
    --framework NAME     minitest or rspec (default: auto-detect from --test names)
    --boot FILE          Require FILE once in the parent before the sources, then
                         fork per mutant (an app entry point or a gem's lib/<name>.rb;
                         needs a test, given or found by convention)
    --rails              Boot config/environment; without --daemon, defaults to
                         redefine and serial execution
    --test-command CMD   Run the target suite in the app's own runtime as a
                         subprocess (for apps on Ruby < 3.4). CMD must contain
                         %{files}. Scrubs Mutineer Ruby PATH pins; set RAILS_ENV
                         on the mutineer command (not as KEY=val inside CMD).
                         CMD must run tests in a fixed order: put SEED=1
                         before the mutineer command for Minitest, or add
                         --order defined to an RSpec CMD
    --daemon             Boot the app ONCE in a persistent daemon and fork per
                         mutant, with per-worker DB isolation so --jobs N is safe
                         under Rails (needs --rails/--boot; not with --test-command).
                         --no-daemon beats a .mutineer.yml daemon: (2.0 will default
                         --rails to --daemon; --no-daemon keeps it serial)
    --format human|json|html  Report format (default: human)
    --output FILE        Write the report to FILE instead of stdout
    --dry-run            List mutations without executing
    --fail-fast          Stop at the first surviving mutant (--no-fail-fast beats a
                         .mutineer.yml fail_fast:)
    --matrix             Run every covering test for each mutant and report blind and
                         redundant tests; the JSON report also lists each mutant's
                         killers (in-process only; not with --daemon, --test-command,
                         --fail-fast or --dry-run; --no-matrix beats a .mutineer.yml
                         matrix:)
    --allow-empty        A run with no mutants is expected; do not warn (--no-allow-empty
                         beats a .mutineer.yml allow_empty:)
    --verbose            Show full error details: the backtrace and causes of a load
                         failure, the real error of a failed fork capture, and the
                         --test-command output (alias: --debug)

  Options:
    --list-operators  List available operators (default vs optional) and exit
    --version         Print version and exit
    --help            Print this help and exit
USAGE
PRINTABLE_SETTINGS =

Settings mutineer config prints. The GitHub Action asks for these (#394), so it does not copy the CLI's precedence and flag rules.

%w[cache_dir baseline].freeze
UNUSED_SETTING_SCOPE =

Where each setting a backend may ignore applies, for the warning.

{
  timeout: "in-process runs only",
  capture_timeout: "in-process and --daemon coverage capture",
  cache_dir: "the in-process and --daemon coverage cache",
  coverage_from: "in-process --rails/--boot runs"
}.freeze

Class Method Summary collapse

Class Method Details

.autopair!(config) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Auto-pair sources to tests by path convention when no --test was given (explicit --test wins). Each source keeps its paired tests, then any mapped tests from the resolved tests: map (R6, R10). A source with neither is dropped with a one-line stderr warning and stored on config.unpaired_sources. The run continues with the rest. Split files for one source are all kept (#87). If every source is dropped: in boot mode the dedicated --boot/--rails-requires-test check reports it; otherwise exit 2 with a usage message. The framework is re-detected from the inferred set unless it was set explicitly (a spec-only project loads/reports as rspec). An explicit test list leaves unpaired_sources empty and does not drop sources.

Parameters:



914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
# File 'lib/mutineer/cli.rb', line 914

def self.autopair!(config)
  return unless config.tests.empty?

  resolved = @resolved_test_map
  @resolved_test_map = nil
  if resolved.nil? && !config.test_map.empty? && !config.explicit?(:tests)
    resolved = Pairing.resolve_test_map(config.test_map, project_root: config.project_root)
  end

  paired, unpaired = convention_pairs(config, resolved: resolved)
  unpaired.each do |source|
    warn "[mutineer] no test found by convention for #{source}; skipping"
  end
  config.unpaired_sources = unpaired
  config.sources = paired.map(&:first)
  config.tests   = paired.flat_map(&:last).uniq
  config.framework = Config.detect_framework(config.tests) unless config.explicit?(:framework)

  return unless config.sources.empty?
  return if config.boot # let the --boot/--rails-requires-test check report it

  warn "mutineer: no test files found by convention; pass --test or add tests"
  exit 2
end

.convention_pairs(config, resolved: nil) ⇒ Array(Array<Array(String, Array<String>)>, Array<String>)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Pairs each source with its conventional tests and any matching tests: map entries. A source with neither is unpaired. Source order is kept. This does not change config.

Parameters:

Returns:

  • (Array(Array<Array(String, Array<String>)>, Array<String>)) —

    paired rows of [source, tests], then unpaired paths.



771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
# File 'lib/mutineer/cli.rb', line 771

def self.convention_pairs(config, resolved: nil)
  resolved ||= @resolved_test_map
  paired = []
  unpaired = []
  config.sources.each do |source|
    convention = Pairing.infer_tests(source, project_root: config.project_root, prefer: config.framework)
    mapped = resolved ? Pairing.mapped_tests_for(source, resolved) : []
    tests = (convention + mapped).uniq
    if tests.empty?
      unpaired << source
    else
      paired << [source, tests]
    end
  end
  [paired, unpaired]
end

.declined_summary(declined, since:) ⇒ String

Formats the dry run's declined count: the total, then each operator's count when the total is above zero. --since does not narrow the count, so under --since the text says so.

Parameters:

  • declined (Hash{String => Integer}) —

    operator name => declined count.

  • since (String, nil) —

    the --since ref, when set.

Returns:

  • (String) —

    e.g. 2 declined (range: 2).



1420
1421
1422
1423
1424
1425
1426
1427
# File 'lib/mutineer/cli.rb', line 1420

def self.declined_summary(declined, since:)
  total = declined.values.sum
  text = "#{total} declined"
  text += " in the scanned files (not narrowed by --since)" if since
  return text if total.zero?

  "#{text} (#{declined.map { |op, n| "#{op}: #{n}" }.join(', ')})"
end

.dry_run(config) ⇒ void

This method returns an undefined value.

Runs dry-run mode. Reuses JobPlan.collect_jobs (+ scope_since) so the candidate list cannot drift from a real run's job selection. --format json emits the lean candidate list (#362); other formats keep the human listing.

Parameters:



1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
# File 'lib/mutineer/cli.rb', line 1297

def self.dry_run(config)
  operator_classes = MutatorRegistry.resolve(config.operators || MutatorRegistry::DEFAULT_NAMES)
  jobs, ignored_results, source_map, extras = JobPlan.collect_jobs(config, operator_classes)
  warn_legacy_ignore_matches(extras[:legacy_ignore_matches])
  unmatched_ignores = unmatched_ignore_ids(config, extras)
  warn_unmatched_ignores(unmatched_ignores)
  # Narrow jobs and ignored the same way a real run does, so the summary
  # matches the printed list.
  jobs, ignored_results, = JobPlan.scope_since(jobs, ignored_results, source_map, config, extras: extras)
  ignored = ignored_results.size
  # One valid? pass for both formats: Mutation#valid? re-parses the whole file.
  valid, invalid = jobs.partition do |subject, mutation, _id|
    mutation.valid?(source_map[subject.file])
  end
  skipped = invalid.size

  # Copies of the mutants this dry run accounts for: the valid candidates
  # it lists, and the ignored mutants a finished run lists. A candidate
  # that does not re-parse is skipped and has no row, so its repeats are
  # left out, as in a finished report (#374).
  copies = Reporter.copies_for(extras[:copies], valid.map(&:last) + ignored_results.map(&:id))
  dropped = Reporter.dropped_count_for(copies)
  if config.format == "json"
    rendered = Reporter.dry_run_json(valid, source_map, declined: extras[:declined] || {},
                                     skipped_invalid: skipped, ignored: ignored,
                                     unmatched_ignores: unmatched_ignores, copies: copies)
    if config.output
      abs = File.expand_path(config.output)
      File.write(abs, rendered)
      warn "Report written to #{abs}"
    else
      print rendered
    end
    exit 0
  end

  per_operator = Hash.new(0)
  valid.each do |subject, mutation, _id|
    source = source_map[subject.file]
    line = source.byteslice(0, mutation.start_offset).count("\n") + 1
    per_operator[mutation.operator] += 1
    original = source.byteslice(mutation.start_offset...mutation.end_offset)
    puts "[#{mutation.operator}] #{subject.qualified_name}  " \
         "#{subject.file}:#{line}  `#{original}` -> `#{mutation.replacement}`"
  end

  # One line per method with no mutants, only with --verbose: on a Rails app
  # they can be most methods (#386). No brackets, so `^\[` still counts mutations.
  unmutated = extras[:unmutated_subjects]
  if config.verbose
    unmutated.each { |entry| puts "no mutants: #{entry[:subject]}  #{entry[:file]}:#{entry[:line]}" }
  end

  total = per_operator.values.sum
  breakdown = per_operator.map { |op, n| "#{op}: #{n}" }.join(", ")
  summary = breakdown.empty? ? "" : "#{breakdown} — "
  puts "#{summary}#{total} mutations (dry run, not executed); " \
       "#{skipped} skipped (invalid); #{ignored} ignored (suppressed); " \
       "#{dropped} dropped (repeats of a kept mutant); " \
       "#{declined_summary(extras[:declined], since: config.since)}; " \
       "#{dry_run_unpaired_clause(config, jobs)}; " \
       "#{unmutated_summary(unmutated.size, extras[:subjects], since: config.since)}"
  exit 0
end

.dry_run_unpaired_clause(config, jobs) ⇒ String

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

The dry-run unpaired clause. A run with tests, or with no unpaired source, prints 0 unpaired. A run with no tests counts jobs in the unpaired sources. It does not drop those sources from the list above.

Parameters:

  • config (Mutineer::Config) —

    run configuration.

  • jobs (Array) —

    scheduled jobs after --since.

Returns:

  • (String) —

    the clause, without a leading semicolon.



1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
# File 'lib/mutineer/cli.rb', line 1370

def self.dry_run_unpaired_clause(config, jobs)
  return "0 unpaired" unless config.tests.empty?

  _paired, unpaired = convention_pairs(config)
  return "0 unpaired" if unpaired.empty?

  root = config.project_root
  unpaired_abs = unpaired.map { |file| File.expand_path(file, root) }
  count = jobs.count do |subject,|
    unpaired_abs.include?(File.expand_path(subject.file, root))
  end
  noun = unpaired.size == 1 ? "source has" : "sources have"
  "#{count} unpaired (#{unpaired.size} #{noun} no paired test; a run without --test skips them)"
end

.execute(config) ⇒ void

This method returns an undefined value.

Executes the run command.

Parameters:



1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
# File 'lib/mutineer/cli.rb', line 1011

def self.execute(config)
  if config.tests.empty?
    warn "mutineer: run requires at least one --test file (or use --dry-run)"
    exit 2
  end

  operator_classes = MutatorRegistry.resolve(config.operators || MutatorRegistry::DEFAULT_NAMES)
  unpaired, failures, unpaired_ids = JobPlan.unpaired_counts(config, operator_classes)
  warn_unpaired_count_failures(failures)

  aggregate, source_map, extras = Runner.execute(config)
  # Pairing drops unpaired sources before collect_jobs. Their ids still
  # count, so a real run agrees with a dry run of the same files. The
  # baseline keeps the paired id map: an unpaired mutant is not a survivor.
  legacy_matches = merged_legacy_matches(extras[:legacy_ignore_matches], unpaired_ids[:legacy_ignore_matches])
  warn_legacy_ignore_matches(legacy_matches)
  # Matched before --since narrows the jobs, so an entry for a mutant
  # outside the diff is not listed. --only returns an empty list.
  known = { id_map: extras[:id_map].merge(unpaired_ids[:id_map]),
            dropped_id_map: extras[:dropped_id_map].merge(unpaired_ids[:dropped_id_map]) }
  unmatched_ignores = unmatched_ignore_ids(config, known)
  warn_unmatched_ignores(unmatched_ignores)
  matrix = KillMatrix.new(aggregate.results) if config.matrix
  reporter = Reporter.new(aggregate, source_map, matrix: matrix, unpaired: unpaired,
                          fail_fast: config.fail_fast)

  # Diff the current run against the baseline (preflighted above) by the
  # stable survivor id. The delta is rendered inline (human section / additive
  # json block) and gates exit independently of --threshold. A --since run is
  # scoped: its score covers a different denominator than a full-run baseline,
  # so only the new-survivor half of the gate applies (see Baseline#diff).
  delta = if config.baseline
            Baseline.load(config.baseline).diff(aggregate, epsilon: config.baseline_epsilon,
                                                           scoped: !config.since.nil?,
                                                           id_map: extras[:id_map],
                                                           project_root: config.project_root)
          end
  warn_legacy_baseline if delta&.legacy_matches&.positive?

  # ignore counts old-format entries (one warning each), not the ids they matched.
  legacy_id_matches = { ignore: legacy_matches.size,
                        baseline: delta ? delta.legacy_matches : 0 }
  reporter.report(out: $stdout, err: $stderr, threshold: config.threshold,
                  format: config.format, output: config.output, baseline: delta,
                  scoped: !config.since.nil?, legacy_id_matches: legacy_id_matches,
                  unmatched_ignores: unmatched_ignores,
                  declined: extras.fetch(:declined, {}), subjects: extras.fetch(:subjects, 0),
                  unmutated_subjects: extras.fetch(:unmutated_subjects, []),
                  copies: extras.fetch(:copies, {}))
  warn_empty_run(config, extras, unpaired) if aggregate.total.zero?

  # Warn (stderr, so it never pollutes json/html) that an external run's score
  # is not comparable to an in-process run: no coverage narrowing (uncovered
  # mutants count as survivors), and an infra failure that exits 1 can still
  # score as a kill (#292): with the summary check on, when its output names a
  # failing test; with it off (the clean run printed no Minitest or RSpec
  # summary line), on any exit 1, a load crash included. Daemon coverage
  # fallback warnings are emitted from the runner only when the map is
  # unavailable, not on every --daemon run.
  if config.test_command
    warn "[mutineer] --test-command score is an upper bound, not comparable to an " \
         "in-process run: no coverage narrowing (uncovered mutants count as survivors). " \
         "Only exit 1 counts as a kill, or a SimpleCov gate exit whose summary shows a failing " \
         "test (an RSpec --failure-exit-code other than 1 makes every kill an error). When the clean run printed a Minitest or RSpec summary line, " \
         "Mutineer also reads it to tell a crash from a kill. See https://github.com/davidteren/mutineer/blob/main/docs/rails-setup.md#apps-on-ruby--34"
  end

  # Nudge toward the opt-in tier-2 operators (human report only: never
  # pollute JSON output).
  if !%w[json html].include?(config.format) && (hint = tier2_hint(config.operators))
    puts hint
  end

  # --baseline and --threshold are independent gates OR'd together.
  # `max` of two 0/1 codes is the OR; usage (2) is handled earlier and wins.
  baseline_exit = delta&.regressed ? 1 : 0
  exit [reporter.exit_code(threshold: config.threshold), baseline_exit].max
end

.expand_tests!(config) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Expand each typed --test value before a run. A blank value exits 2. With --test-command, a directory stays as typed. A glob still expands. A directory or glob with no test file exits 2. Each expanded value prints one count on stderr. Duplicate files keep the first spelling. The framework is detected again from the expanded list, unless the user set it.

Parameters:



798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
# File 'lib/mutineer/cli.rb', line 798

def self.expand_tests!(config)
  root = config.project_root
  seen = {}
  tests = []
  counts = []
  errors = []

  Array(config.tests).each do |value|
    kind = Pairing.classify_test_value(value, project_root: root)
    if kind == :blank
      errors << %(mutineer: --test must name a file, a directory or a glob, not blank (got: "#{value}"))
      next
    end
    if kind == :directory && config.test_command
      store_test_path(tests, seen, root, value)
      next
    end

    paths = Pairing.expand_test(value, project_root: root)
    if paths.empty?
      errors << no_test_match_message(value, kind)
      next
    end
    if kind == :directory || kind == :glob
      noun = paths.size == 1 ? "file" : "files"
      counts << "[mutineer] --test #{value}: #{paths.size} test #{noun}"
    end
    paths.each { |path| store_test_path(tests, seen, root, path) }
  end

  unless errors.empty?
    errors.each { |msg| warn msg }
    exit 2
  end

  counts.each { |line| warn line }
  config.tests = tests
  config.framework = Config.detect_framework(config.tests) unless config.explicit?(:framework)
end

.list_operators ⇒ void

This method returns an undefined value.

Lists available operators.



424
425
426
427
428
429
430
# File 'lib/mutineer/cli.rb', line 424

def self.list_operators
  MutatorRegistry::ALL.each_key do |name|
    state = MutatorRegistry.default?(name) ? "default" : "disabled"
    puts format("%-20s tier %d  %-9s %s",
                name, MutatorRegistry.tier(name), state, MutatorRegistry::DESCRIPTIONS[name])
  end
end

.merged_legacy_matches(paired, unpaired) ⇒ Hash{String => Array}

Old-format ignore matches from the paired run plus sources pairing skipped. Arrays are copied, so the paired extras stay unchanged.

Parameters:

  • paired (Hash{String => Array}) —

    old id => hits from the paired run.

  • unpaired (Hash{String => Array}) —

    the same from unpaired sources.

Returns:

  • (Hash{String => Array})


1228
1229
1230
1231
1232
1233
1234
# File 'lib/mutineer/cli.rb', line 1228

def self.merged_legacy_matches(paired, unpaired)
  merged = paired.to_h { |old, hits| [old, hits.dup] }
  unpaired.each do |old, hits|
    (merged[old] ||= []).concat(hits)
  end
  merged
end

.migrate(config, file_path) ⇒ void

This method returns an undefined value.

Rewrites old-format ids in the loaded .mutineer.yml ignore: list. Prints each change. With --dry-run, writes nothing. Exits 1 when any id matched no mutant in these sources and operators, or when an id in a { id:, reason: } entry now matches several mutants (split it by hand). Those ids stay in the file. Exits 0 when every id is current or was rewritten. An unsupported ignore: shape exits 2 and leaves the file unchanged.

Parameters:

  • config (Mutineer::Config) —

    run configuration, sources already set.

  • file_path (String) —

    the .mutineer.yml to edit.



357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
# File 'lib/mutineer/cli.rb', line 357

def self.migrate(config, file_path)
  current, old_to_new = Migrate.id_maps(config)
  text = File.read(file_path, encoding: "UTF-8")
  outcome = Migrate.rewrite(text, current, old_to_new)
  outcome.replacements.each do |rep|
    puts "[mutineer] #{rep.old_id} -> #{rep.new_ids.join(', ')}"
  end
  outcome.unmapped.each do |id|
    warn "[mutineer] ignore entry #{id} matched no mutant in these sources and operators. " \
         "It was left in place."
  end
  outcome.split.each do |rep|
    warn "[mutineer] ignore entry #{rep.old_id} has a reason and now matches several mutants " \
         "(#{rep.new_ids.join(', ')}). Split it into one entry per id by hand. It was left in place."
  end
  warn "[mutineer] dry run: .mutineer.yml was not changed" if config.dry_run
  replace_file(file_path, outcome.text) if !config.dry_run && outcome.text != text
  exit(outcome.unmapped.empty? && outcome.split.empty? ? 0 : 1)
rescue ArgumentError => e
  warn "mutineer: #{e.message}"
  exit 2
rescue Mutineer::ParseError => e
  warn "mutineer: error reading: #{e.message}"
  exit 1
rescue SystemCallError => e
  warn "mutineer: #{e.message}"
  exit 2
end

.no_test_match_message(value, kind) ⇒ String

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Usage text when a directory or glob matched no test file.

Parameters:

  • value (String) —

    the --test value, as typed.

  • kind (Symbol) —

    :directory or :glob.

Returns:

  • (String)


844
845
846
847
848
849
# File 'lib/mutineer/cli.rb', line 844

def self.no_test_match_message(value, kind)
  message = "mutineer: --test #{value} matched no test files"
  return message unless kind == :directory

  "#{message}. A directory gives the files under it named *_test.rb, *_spec.rb or test_*.rb."
end

.preflight_baseline!(path) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

A missing/unreadable/unparseable baseline is a usage error (exit 2), mirroring --output/--since preflight, so CI sees "bad invocation," not a backtrace mid-run. Validating up front = attempting the load (it raises ConfigError/SystemCallError; the actual diff reloads in execute).

Parameters:

  • path (String) —

    baseline file path.



947
948
949
950
951
952
# File 'lib/mutineer/cli.rb', line 947

def self.preflight_baseline!(path)
  Baseline.load(path)
rescue Mutineer::ConfigError, SystemCallError => e
  warn "mutineer: #{e.message}"
  exit 2
end

.preflight_output!(path, config) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Preflights an output path. A missing parent is a usage error (exit 2), except the cache directory: the documented --output .mutineer/run.json must work on a fresh checkout. It is created here, before the run, so a failure to create it exits 2 up front. A later failed check can leave the empty cache directory behind (a real run creates it anyway). A human dry run writes no report, so it creates nothing; --dry-run --format json writes the candidate list and may create the cache dir (#362).

Parameters:

  • path (String) —

    output file path.

  • config (Mutineer::Config) —

    run configuration (for the cache directory).



988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
# File 'lib/mutineer/cli.rb', line 988

def self.preflight_output!(path, config)
  dir = File.dirname(File.expand_path(path))
  if !File.exist?(dir) && dir == File.expand_path(config.cache_dir, config.project_root)
    return if config.dry_run && config.format != "json"

    begin
      FileUtils.mkdir_p(dir)
    rescue SystemCallError => e
      warn "mutineer: cannot write to #{path}: #{e.message}"
      exit 2
    end
  end
  return if File.directory?(dir) && File.writable?(dir)

  reason = File.directory?(dir) ? "directory is not writable" : "no such directory"
  warn "mutineer: cannot write to #{path}: #{reason}"
  exit 2
end

.preflight_same_file!(config) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

#281: a report written over its own baseline turns a failed gate into the next baseline. Same check as the Action's guard (action.yml); the message is that guard's text adapted for the CLI, so keep the two in step. The output is expanded the way Reporter#report writes it, so x/../b.json with a missing x/ still matches b.json. File.identical? is false when either file is missing, so a new output path never matches. Unlike the Action's guard, a human dry run skips this check: it writes no report. JSON dry runs write --output, so they call this guard (#362).

Parameters:



966
967
968
969
970
971
972
973
974
# File 'lib/mutineer/cli.rb', line 966

def self.preflight_same_file!(config)
  output = File.expand_path(config.output)
  return unless File.identical?(output, config.baseline)

  warn "mutineer: --output and #{config.origin(:baseline)} are the same file ('#{File.realpath(output)}'). " \
       "A failing run would replace the baseline. Write the report to a separate path. " \
       "Copy that file onto the baseline only when the run exits 0."
  exit 2
end

.prepare_test_map!(config) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Warn or resolve the optional tests: map before pairing. With --test and a non-empty map, print one line that the map has no effect (R9) and resolve nothing. Otherwise expand every pattern; an unmatched pattern is exit 2 (R5). The resolved map is stashed for autopair! and convention_pairs. Dry-run still runs this check (R12) even though it skips autopair.

Parameters:



877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
# File 'lib/mutineer/cli.rb', line 877

def self.prepare_test_map!(config)
  @resolved_test_map = nil
  return if config.test_map.empty?

  if config.explicit?(:tests)
    warn "[mutineer] #{config.origin(:test_map)} has no effect when --test is given"
    return
  end

  resolved = Pairing.resolve_test_map(config.test_map, project_root: config.project_root)
  unless resolved[:unmatched].empty?
    miss = resolved[:unmatched].first
    # Prefer the loaded path: find_file can pick a home or parent config,
    # and basename-only text hides which file failed the map check.
    label = Config.find_file || CONFIG_FILE
    warn "mutineer: #{label}: tests entry #{miss[:entry]}: " \
         "#{miss[:key]} pattern #{miss[:pattern].inspect} matched no file"
    exit 2
  end
  @resolved_test_map = resolved
end

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Prints the value run would use for one setting, resolved from the same flags and .mutineer.yml, and exits 0. An unset value prints nothing. Read-only: it creates no folder and writes no file. Other arguments, such as sources, are ignored, so a caller can pass a run's arguments as they are. An unknown or missing key is a usage error (exit 2).

Parameters:

  • config (Mutineer::Config) —

    the resolved configuration.

  • key (String, nil) —

    the setting name.



334
335
336
337
338
339
340
341
342
343
344
# File 'lib/mutineer/cli.rb', line 334

def self.print_setting(config, key)
  unless PRINTABLE_SETTINGS.include?(key)
    warn "mutineer: config needs one of #{PRINTABLE_SETTINGS.join(', ')}#{" (got '#{key}')" if key}"
    exit 2
  end
  value = config[key.to_sym]
  # Exactly one newline, even after a value that ends in one (puts would
  # add none), so a caller can strip it and keep the value whole.
  print value, "\n" unless value.nil?
  exit 0
end

.replace_file(path, contents) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Replaces path with contents without truncating the original first. The new bytes go to a temporary file in the same directory. That file is closed before it is renamed over the target, and it keeps the target's mode. A symlink is followed, so the target file changes and the link stays. If the write fails, the temporary file is removed and the original file is left as it was.

Parameters:

  • path (String) —

    the configuration file to replace.

  • contents (String) —

    the full new text.



397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
# File 'lib/mutineer/cli.rb', line 397

def self.replace_file(path, contents)
  target = File.symlink?(path) ? File.realpath(path) : path
  directory = File.dirname(target)
  base = File.basename(target)
  temp = nil
  100.times do
    candidate = File.join(directory, ".#{base}.migrate-#{Process.pid}-#{rand(1_000_000_000)}.tmp")
    next if File.exist?(candidate)

    temp = candidate
    break
  end
  raise Errno::EEXIST, target unless temp

  mode = File.stat(target).mode & 0o7777
  # `perm` is still masked by the umask, so chmod restores the exact mode.
  File.write(temp, contents, perm: mode)
  File.chmod(mode, temp)
  File.rename(temp, target)
rescue StandardError
  File.unlink(temp) if temp && File.exist?(temp)
  raise
end

.run(config) ⇒ void

This method returns an undefined value.

Runs the requested command after validation.

Parameters:



436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
# File 'lib/mutineer/cli.rb', line 436

def self.run(config)
  if config.sources.empty?
    warn "mutineer: run requires at least one source file"
    exit 2
  end
  validate!(config)
  Config.warn_rails_default_change(config)

  config.dry_run ? dry_run(config) : execute(config)
rescue ArgumentError => e
  # Unknown --operators value surfaces here; no backtrace reaches the user.
  warn "mutineer: #{Redaction.text(e.message)}"
  exit 2
rescue Mutineer::ConfigError => e
  # A config value that only the booted app can check (`shared_databases`
  # naming the primary database). A usage error, raised before any mutant runs.
  warn "mutineer: #{e.message}"
  exit 2
rescue SystemCallError => e
  # A missing/unreadable path reaches here as Errno::ENOENT etc. A plain
  # message and usage exit, never a raw backtrace.
  warn "mutineer: #{Redaction.text(e.message)}"
  exit 2
rescue SyntaxError => e
  # Boot, source and require files report a SyntaxError as ProjectLoadError
  # below. This covers a file loaded on any other path; report it cleanly
  # rather than dumping a backtrace.
  warn "mutineer: cannot load source: #{Redaction.text(e.message)}"
  exit 1
rescue Mutineer::ParseError => e
  warn "mutineer: error reading: #{Redaction.text(e.message)}"
  exit 1
rescue Mutineer::SmokeCheckError => e
  # The unmutated suite is not green under --test-command: a broken
  # environment, not weak tests. Runtime error (exit 1), not usage (exit 2).
  warn "mutineer: #{Redaction.text(e.message)}"
  exit 1
rescue Mutineer::ConcurrentRunError => e
  # Another process owns a source file. Runtime error (exit 1), not a
  # backtrace: the working tree is still the other run's responsibility.
  warn "mutineer: #{Redaction.text(e.message)}"
  exit 1
rescue Mutineer::CoverageFromError => e
  warn "mutineer: #{Redaction.text(e.message)}"
  exit 2
rescue Mutineer::DaemonBootError => e
  # The daemon is gone for good, so the run ended rather than scoring the rest
  # against it. A deliberate stop deserves a message, not a raw backtrace.
  warn "mutineer: #{Redaction.text(e.message)}"
  exit 1
rescue Mutineer::ProjectLoadError => e
  # A boot file, source or --require file failed to load. The message is
  # already redacted; --verbose adds the backtrace and the cause chain.
  # A source NameError with no boot file adds one line that points at
  # boot: (#376). The hint is static text, so it needs no redaction.
  warn "mutineer: #{e.message}"
  warn "mutineer: #{e.hint}" if e.hint
  if config.verbose
    (e.backtrace || []).each { |frame| warn "\t#{Redaction.text(frame)}" }
    e.causes.each { |cause| warn "mutineer: caused by: #{cause}" }
  else
    warn "mutineer: re-run with --verbose for the backtrace and causes"
  end
  exit 1
end

.start(argv) ⇒ void

This method returns an undefined value.

Parses arguments, executes the command, and exits.

Parameters:

  • argv (Array<String>) —

    raw command-line arguments.



141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
# File 'lib/mutineer/cli.rb', line 141

def self.start(argv)
  # Reports and warnings name paths. Under an ASCII locale the stdio
  # encoding is US-ASCII, so a non-ASCII path cannot be written.
  # Binary mode writes each string's own bytes: UTF-8 text stays UTF-8,
  # and a path that is not valid UTF-8 does not raise on the way out (#346).
  [$stdout, $stderr].each(&:binmode)

  # Set before any exit: the method's ensure reads it, and exit runs ensure.
  filter_owned = false
  previous_urls = nil
  if argv.first == "triage"
    exit Triage.run(argv[1..])
  end

  if argv.first == "init"
    exit Init.run(argv[1..])
  end

  # The CLI layer holds only the fields the user typed, so Config.resolve
  # can tell a typed `false`/`nil` from an absent flag by whether the key exists.
  opts = {}
  show_operators = false

  parser = OptionParser.new do |o|
    o.banner = BANNER
    o.on("--version") do
      puts Mutineer::VERSION
      exit 0
    end
    o.on("--help") do
      puts BANNER
      exit 0
    end
    o.on("--list-operators") { show_operators = true }
    o.on("--dry-run") { opts[:dry_run] = true }
    # A typed --no-* beats the .mutineer.yml key, so a file key that
    # conflicts with another flag can be turned off for one run.
    o.on("--[no-]fail-fast") { |on| opts[:fail_fast] = on }
    o.on("--[no-]matrix") { |on| opts[:matrix] = on }
    o.on("--[no-]allow-empty") { |on| opts[:allow_empty] = on }
    o.on("--only NAME") { |v| opts[:only] = v }
    o.on("--since REF") { |v| opts[:since] = Config.parse(:since, v) }
    # A typed "no" must beat a .mutineer.yml `since:` key: the key is present
    # with a nil value, and nil is a value.
    o.on("--no-since") { opts[:since] = nil }
    o.on("--test PATH") { |v| (opts[:tests] ||= []) << v }
    o.on("--operators LIST") do |v|
      opts[:operators] = Config.parse(:operators, v.split(",").map(&:strip))
    end
    o.on("--threshold FLOAT") { |v| opts[:threshold] = Config.parse(:threshold, v) }
    o.on("--jobs N") { |v| opts[:jobs] = Config.parse(:jobs, v) }
    o.on("--timeout SECONDS") { |v| opts[:timeout] = Config.parse(:timeout, v) }
    o.on("--capture-timeout SECONDS") { |v| opts[:capture_timeout] = Config.parse(:capture_timeout, v) }
    o.on("--cache-dir DIR") { |v| opts[:cache_dir] = Config.parse(:cache_dir, v) }
    o.on("--coverage-from FILE") { |v| opts[:coverage_from] = Config.parse(:coverage_from, v) }
    o.on("--strategy STRAT") { |v| opts[:strategy] = Config.parse(:strategy, v) }
    o.on("--framework NAME") { |v| opts[:framework] = Config.parse(:framework, v) }
    o.on("--boot FILE") { |v| opts[:boot] = v }
    o.on("--rails") { opts[:rails] = true }
    o.on("--verbose") { opts[:verbose] = true }
    o.on("--debug") { opts[:verbose] = true } # alias of --verbose
    o.on("--format FORMAT") { |v| opts[:format] = Config.parse(:format, v) }
    o.on("--output FILE") { |v| opts[:output] = v }
    # --baseline-epsilon is CLI-only.
    o.on("--baseline FILE") { |v| opts[:baseline] = v }
    o.on("--baseline-epsilon FLOAT") { |v| opts[:baseline_epsilon] = Config.parse(:baseline_epsilon, v) }
    # Run the target suite as a subprocess in the app's OWN runtime so
    # mutineer (Ruby >= 3.4) can mutation-test apps pinned to an older Ruby.
    o.on("--test-command CMD") { |v| opts[:test_command] = v }
    # Boot the app ONCE in a persistent daemon and fork per mutant, with
    # per-worker DB isolation so --jobs N is safe under Rails.
    # A typed --no-daemon beats a .mutineer.yml `daemon: true`, and pins the
    # serial --rails path before 2.0 makes the daemon the default.
    o.on("--[no-]daemon") { |on| opts[:daemon] = on }
  end

  begin
    parser.parse!(argv)
  rescue OptionParser::ParseError, Mutineer::ConfigError => e
    warn "mutineer: #{e.message}"
    exit 2
  end

  if show_operators
    list_operators
    exit 0
  end

  if argv.empty?
    puts BANNER
    exit 0
  end

  begin
    file_path = Config.find_file
    file_hash = file_path ? Config.from_file(file_path, defer_operators: opts.key?(:operators)) : {}
    config = Config.resolve(opts, file_hash)
  rescue Mutineer::ConfigError => e
    # The lib layer raises instead of killing the host; the CLI maps a
    # config (usage) error to exit 2.
    warn "mutineer: #{e.message}"
    exit 2
  end

  case argv.first
  when "run"
    warn_config_root_mismatch(file_path, config.project_root) if file_path
    # Matrix conflicts first — same order as validate! — so a --matrix
    # clash is not hidden by a shape or expansion error (#407 OCR).
    # Expand --test before the guard. The guard reads config.tests.
    # migrate and config do not call this (#380).
    # A bad --test-command is reported next, not hidden by a --test error.
    validate_matrix!(config) if config.matrix
    validate_test_command_shape!(config) if config.test_command
    expand_tests!(config) if config.explicit?(:tests)
    tests_as_sources = argv[1..].select do |arg|
      Pairing.test_given_as_source?(arg, project_root: config.project_root, tests: config.tests)
    end
    if config.explicit?(:tests) && tests_as_sources.any?
      warn "mutineer: #{tests_as_sources.join(', ')} looks like a test file, not a source. " \
           "A shell expands an unquoted glob into many files. " \
           "Quote the glob (--test 'test/**/*_test.rb'), pass the directory (--test test), " \
           "or repeat --test for each file"
      exit 2
    end
    # A directory source expands to its **/*.rb files; a file inside the
    # project becomes its root-relative path (#104). Test inference (when --test is omitted) happens in validate!.
    config.sources = Pairing.expand_sources(argv[1..], project_root: config.project_root)
    # Direct writes from the app, a fork, or a subprocess inherit these
    # pipes (#341). Dotenv files are merged with any URLs the caller
    # already set, and that list is restored when start returns.
    previous_urls = Redaction.extra_urls
    Redaction.extra_urls = (previous_urls + DatabaseUrls.from_files(config.project_root)).uniq
    case OutputFilter.install
    when :started
      filter_owned = true
    when :failed
      warn "mutineer: cannot redirect stdout and stderr, so a database password would be printed"
      exit 1
    end
    run(config)
  when "migrate"
    warn_config_root_mismatch(file_path, config.project_root) if file_path
    unless file_path
      warn "mutineer: migrate needs a .mutineer.yml (none found from #{Dir.pwd})"
      exit 2
    end
    if argv[1..].empty?
      warn "mutineer: migrate requires at least one source file"
      exit 2
    end
    config.sources = Pairing.expand_sources(argv[1..], project_root: config.project_root)
    migrate(config, file_path)
  when "config"
    print_setting(config, argv[1])
  else
    warn "mutineer: unknown command '#{argv.first}'"
    exit 2
  end
rescue StandardError, ScriptError => e
  # Last resort (#341): an error no handler above expects would otherwise
  # reach Ruby's default printer, which shows its message unredacted. Same
  # exit 1 as that printer, with the message and backtrace redacted. A
  # message that raises while it is built is not shown at all.
  details = begin
    e.full_message(highlight: false)
  rescue StandardError, ScriptError
    Redaction::FAILED
  end
  warn "mutineer: #{Redaction.text(details)}"
  exit 1
ensure
  # Flush after the report is printed and before the process exits, while
  # extra_urls is still set. Then drop them so a later in-process call
  # does not keep this project's passwords.
  OutputFilter.uninstall if filter_owned
  Redaction.extra_urls = previous_urls unless previous_urls.nil?
end

.store_test_path(tests, seen, root, path) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Keep the first spelling of one absolute test path.

Parameters:

  • tests (Array<String>) —

    paths kept so far.

  • seen (Hash{String => true}) —

    absolute paths already kept.

  • root (String) —

    project root.

  • path (String) —

    path as it should be stored.



859
860
861
862
863
864
865
# File 'lib/mutineer/cli.rb', line 859

def self.store_test_path(tests, seen, root, path)
  key = File.expand_path(path, root)
  return if seen[key]

  seen[key] = true
  tests << path
end

.tier2_hint(active) ⇒ String?

The tier-2 operators not in the active set, as a one-line hint (or nil when they are all already enabled). active nil means the default (Tier-1) set.

Parameters:

  • active (Array<String>, nil) —

    active operator names.

Returns:

  • (String, nil) —

    hint text or nil.



1161
1162
1163
1164
1165
1166
1167
1168
# File 'lib/mutineer/cli.rb', line 1161

def self.tier2_hint(active)
  active ||= MutatorRegistry::DEFAULT_NAMES
  unused = MutatorRegistry::TIER2_NAMES - active
  return if unused.empty?

  "#{unused.size} tier-2 operators available (#{unused.join(', ')}) — " \
    "enable with --operators <list>."
end

.unmatched_ignore_ids(config, extras) ⇒ Array<String>

ignore: ids that match no mutant in this run's sources and operators. The set is the new ids and old-format ids from JobPlan.collect_jobs (id_map and dropped_id_map), including sources pairing skipped (JobPlan.unpaired_counts), so a dropped repeat of an edit counts as matched (#275) and an old-format id that still matches is not listed (the legacy warning names it). Matching happens before --since narrows the jobs, so an entry for a mutant outside the diff is not listed. --only returns an empty list: methods are narrowed before matching, so a miss there would not mean the entry is stale. File order, each id once.

Parameters:

Returns:

  • (Array<String>) —

    unmatched ids.



1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
# File 'lib/mutineer/cli.rb', line 1203

def self.unmatched_ignore_ids(config, extras)
  return [] if config.only

  known = {}
  [extras[:id_map], extras[:dropped_id_map]].each do |map|
    map&.each do |new_id, old_id|
      known[new_id] = true
      known[old_id] = true
    end
  end
  seen = {}
  Array(config.ignore).each_with_object([]) do |id, out|
    next if known[id] || seen[id]

    seen[id] = true
    out << id
  end
end

.unmutated_summary(unmutated, subjects, since:) ⇒ String

Formats the dry run's count of methods with no mutants (#386). Under --since the count is already narrowed to methods whose def intersects the diff (#420).

Parameters:

  • unmutated (Integer) —

    methods the selected operators did not mutate.

  • subjects (Integer) —

    methods discovered (in scope).

  • since (String, nil) —

    unused; kept for call-site symmetry with declined_summary.

Returns:

  • (String) —

    e.g. no mutants in 1 of 2 methods.



1409
1410
1411
# File 'lib/mutineer/cli.rb', line 1409

def self.unmutated_summary(unmutated, subjects, since:) # rubocop:disable Lint/UnusedMethodArgument
  "no mutants in #{unmutated} of #{subjects} methods"
end

.validate!(config) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Flag validation: every flag/usage failure exits 2, consistent with the taxonomy above. CI can tell "mistyped flag" from "tests too weak."

Parameters:



508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
# File 'lib/mutineer/cli.rb', line 508

def self.validate!(config)
  # First, so a conflict is reported before another check rewrites the config.
  validate_matrix!(config) if config.matrix
  validate_test_command!(config) if config.test_command

  validate_since!(config) if config.since
  # Non-JSON dry runs ignore --output (warn_unused_dry_run_settings); skip
  # the path check so a missing parent does not exit 2 before that warning.
  if config.output && (!config.dry_run || config.format == "json")
    preflight_output!(config.output, config)
  end
  preflight_baseline!(config.baseline) if config.baseline
  # Human dry runs write nothing; JSON dry runs write --output (#362), so
  # they need the same-file guard that blocks overwriting a baseline (#281).
  if config.output && config.baseline && (!config.dry_run || config.format == "json")
    preflight_same_file!(config)
  end

  # Resolve / warn for the tests: map before autopair. Dry-run skips
  # autopair but still checks unmatched patterns (#382 R5, R12).
  prepare_test_map!(config)

  # When --test is omitted, infer each source's test by convention. Autopair
  # also re-detects framework from inferred tests when --framework was not set.
  autopair!(config) unless config.dry_run

  # Daemon validation runs AFTER autopair so auto-inferred *_spec.rb tests
  # cannot bypass the RSpec rejection (framework would still be minitest if we
  # validated before discovery).
  validate_daemon!(config) if config.daemon
  warn_unused_coverage_from(config)
  warn_unused_dry_run_settings(config)

  # Boot mode needs at least one --test file (nothing to select from otherwise).
  if config.boot && config.tests.empty?
    warn "mutineer: --boot/--rails requires at least one --test file"
    exit 2
  end

  validate_paths!(config)
end

.validate_daemon!(config) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

--daemon selects the persistent-daemon backend (boot once, fork per mutant, per-worker DB isolation on SQLite, Postgres, and MySQL). Usage errors exit 2: cannot combine with --test-command; requires --rails or --boot; minitest only; reload strategy only (redefine needs a shared VM surgical path the daemon does not ship).

Parameters:



605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
# File 'lib/mutineer/cli.rb', line 605

def self.validate_daemon!(config)
  if config.test_command
    warn "mutineer: choose one backend — --daemon and --test-command cannot be combined"
    exit 2
  end
  unless config.rails || config.boot
    warn "mutineer: --daemon needs an app to boot; add --rails (or --boot FILE)"
    exit 2
  end
  if config.framework == "rspec"
    warn "mutineer: --daemon supports only --framework minitest " \
         "(rspec is not implemented on the daemon path yet)"
    exit 2
  end
  warn_unused_settings(config, "--daemon", %i[timeout])
  return if config.strategy == "reload"

  # --rails defaults strategy to redefine; daemon always whole-file loads.
  warn "[mutineer] --daemon uses --strategy reload " \
       "(redefine is not supported on the daemon path); forcing reload."
  config.strategy = "reload"
end

.validate_matrix!(config) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

--matrix runs on the in-process backend and needs every mutant's whole covering run, so a backend that cannot name the failing test, or a run that stops early, is a usage error (exit 2), never a quietly partial matrix.

Parameters:



696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
# File 'lib/mutineer/cli.rb', line 696

def self.validate_matrix!(config)
  conflict, reason =
    if config.dry_run
      [:dry_run, "a dry run runs no tests, so it has no matrix"]
    elsif config.daemon
      [:daemon, "the kill matrix runs on the in-process backend only"]
    elsif config.test_command
      [:test_command, "the external suite reports pass or fail, not which test failed"]
    elsif config.fail_fast
      [:fail_fast, "a fail-fast run is partial, so blind and redundant tests would be wrong"]
    end
  return unless conflict

  # Say how to turn off whichever side came from the file, for this run.
  hint =
    if config.origin(:matrix) != "--matrix"
      "; pass --no-matrix to run without it"
    elsif conflict == :fail_fast && config.origin(:fail_fast) != "--fail-fast"
      "; pass --no-fail-fast to run without it"
    else
      ""
    end
  warn "mutineer: #{config.origin(:matrix)} cannot be combined with #{config.origin(conflict)} (#{reason}#{hint})"
  exit 2
end

.validate_paths!(config) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Validate path existence up front so a typo is a clean usage error (exit 2), not an Errno::ENOENT backtrace from deep in the run. Flag checks run first so a bad flag still reports the flag, not the missing file.

Parameters:



753
754
755
756
757
758
759
760
# File 'lib/mutineer/cli.rb', line 753

def self.validate_paths!(config)
  missing = (config.sources + config.tests)
            .reject { |p| File.exist?(File.expand_path(p, config.project_root)) }
  return if missing.empty?

  warn "mutineer: no such file: #{missing.join(', ')}"
  exit 2
end

.validate_since!(config) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

--since needs a real git repo and a resolvable ref; either failure is a usage error (exit 2) so CI sees "bad invocation," not "tests too weak."

Parameters:



728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
# File 'lib/mutineer/cli.rb', line 728

def self.validate_since!(config)
  _out, _err, status = Open3.capture3(
    "git", "-C", config.project_root, "rev-parse", "--verify", "--quiet",
    "#{config.since}^{commit}"
  )
  return if status.success?

  inside, = Open3.capture3(
    "git", "-C", config.project_root, "rev-parse", "--is-inside-work-tree"
  )
  msg = inside.strip == "true" ? "unknown git ref: #{config.since}" : "--since requires a git repository"
  warn "mutineer: #{msg}"
  exit 2
rescue Errno::ENOENT
  warn "mutineer: --since requires git on PATH"
  exit 2
end

.validate_test_command!(config) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

--test-command runs the target suite in the app's own runtime. Validate its shape up front (usage errors → exit 2) and force serial execution: each subprocess boots the app and opens its own fixture transaction against the same DB, so --jobs > 1 would corrupt results (fixture-contention hazard). Unlike --rails, this path has NO per-worker DB isolation to opt into, so an explicit --jobs N is forced to 1 rather than honored.

Parameters:



560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
# File 'lib/mutineer/cli.rb', line 560

def self.validate_test_command!(config)
  validate_test_command_shape!(config)
  if config.boot
    warn "mutineer: --test-command cannot be combined with --boot/--rails " \
         "(the external subprocess boots the app itself)"
    exit 2
  end
  if config.strategy == "redefine"
    warn "mutineer: --test-command supports only --strategy reload " \
         "(surgical redefine needs a shared VM; the subprocess has its own)"
    exit 2
  end
  warn_unused_settings(config, "--test-command", %i[timeout capture_timeout cache_dir])
  return unless config.jobs > 1

  warn "[mutineer] --test-command runs serially (no per-worker DB isolation yet); forcing --jobs 1."
  config.jobs = 1
end

.validate_test_command_shape!(config) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

The --test-command text must not be blank and must contain %files. It prints nothing when the text is valid, so a second call is safe.

Parameters:



585
586
587
588
589
590
591
592
593
594
# File 'lib/mutineer/cli.rb', line 585

def self.validate_test_command_shape!(config)
  if config.test_command.strip.empty?
    warn "mutineer: --test-command must not be empty"
    exit 2
  end
  return if config.test_command.include?("%{files}")

  warn "mutineer: --test-command must contain %{files} (where the --test paths are substituted)"
  exit 2
end

.warn_config_root_mismatch(file_path, project_root) ⇒ void

This method returns an undefined value.

Warns once when the loaded .mutineer.yml sits outside the run directory (#126). Mutant ids hash each file's path relative to the run directory, but the config is found by walking up, so a run from a subdirectory loads the same ignore list while its ids no longer match. A config in the home directory is a personal default, not a project root, so it never warns.

Parameters:

  • file_path (String) —

    the .mutineer.yml that was loaded.

  • project_root (String) —

    the run directory ids are relative to.



1179
1180
1181
1182
1183
1184
1185
1186
1187
# File 'lib/mutineer/cli.rb', line 1179

def self.warn_config_root_mismatch(file_path, project_root)
  config_dir = ProjectPath.root_real(File.dirname(file_path))
  return if config_dir == ProjectPath.root_real(project_root)
  return if config_dir == ProjectPath.root_real(Dir.home)

  warn "[mutineer] loaded #{file_path}, but mutant ids are relative to the run directory " \
       "#{project_root}, not to #{config_dir}. Ignore ids and baselines written from " \
       "#{config_dir} will not match this run. Run mutineer from #{config_dir}."
end

.warn_empty_run(config, extras, unpaired = {}) ⇒ void

This method returns an undefined value.

Says why a run has no mutants, on stderr for every format. A --since run whose sources had mutants before scoping is a stated success: the changes held no mutable Ruby code. Any other empty run is a likely mistake (wrong path, operators that never match), which 2.0 fails unless --allow-empty says it is expected.

Parameters:

  • config (Mutineer::Config) —

    run configuration.

  • extras (Hash) —

    the run extras; :unscoped_mutants counts the mutants (run and suppressed) before --since, :declined the candidates each operator did not mutate, and :subjects the methods found (#386).

  • unpaired (Hash{String => Integer, nil}) (defaults to: {}) —

    file => mutant count for sources pairing skipped. nil means the count failed.



1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
# File 'lib/mutineer/cli.rb', line 1103

def self.warn_empty_run(config, extras, unpaired = {})
  known = unpaired.each_value.sum { |count| count.is_a?(Integer) ? count : 0 }
  if known.positive?
    body = if known == 1
             "1 mutant is in a source with no paired test"
           else
             "#{known} mutants are in sources with no paired test"
           end
    warn "mutineer: no mutant ran. #{body} (unpaired_sources[] in --format json). #{UNPAIRED_RUN_HINT}"
    return
  end

  # No positive unpaired count, and at least one count failed: mutants may
  # still exist, so do not call the run empty. Name every unpaired source;
  # say how many of those counts are unavailable.
  unknown = unpaired.count { |_file, count| count.nil? }
  if unknown.positive?
    total = unpaired.size
    sources = total == 1 ? "1 source has" : "#{total} sources have"
    unavailable = unknown == 1 ? "1 of them" : "#{unknown} of them"
    warn "mutineer: no mutant ran. #{sources} no paired test; the mutant count is unavailable for " \
         "#{unavailable} (unpaired_sources[] in --format json). #{UNPAIRED_RUN_HINT}"
    return
  end

  # Mutants existed before --since narrowed them: the changes held none.
  if config.since && extras[:unscoped_mutants].to_i.positive?
    warn "mutineer: nothing to test in the changes since #{config.since}"
  elsif !config.allow_empty
    declined = extras.fetch(:declined, {}).values.sum
    methods = extras.fetch(:subjects, 0)
    causes = []
    if declined.positive?
      causes << "#{declined} #{declined == 1 ? 'candidate was' : 'candidates were'} declined " \
                "(--dry-run shows the count per operator)."
    end
    # Name the methods the operators passed over (#386), so an empty run on
    # real code points at the operator set, not at the paths.
    if methods.positive?
      found = if methods == 1
                "1 method was found, and the selected operators made no mutant in it"
              else
                "#{methods} methods were found, and the selected operators made no mutant in any of them"
              end
      causes << "#{found} (--list-operators shows the others)."
    end
    causes << "Check that the sources contain code the operators mutate." if causes.empty?
    cause = causes.join(" ")
    warn "mutineer: no mutants were generated. #{cause} The run exits 0, and #{BECOMES_ERROR_IN_2_0}. " \
         "Pass --allow-empty (or allow_empty: true) if an empty run is expected."
  end
end

.warn_legacy_baseline ⇒ void

This method returns an undefined value.

Warns once that the --baseline file stores old-format ids (#126), so the diff fell back to matching on them. Called only when a survivor matched through an old id alone.



1283
1284
1285
1286
1287
1288
# File 'lib/mutineer/cli.rb', line 1283

def self.warn_legacy_baseline
  warn "[mutineer] the baseline uses the old id format, which did not include the file " \
       "path, so survivors were matched on their old ids and files. Please generate a new " \
       "baseline with `--format json`, but only after every gate that reads it runs this " \
       "mutineer version or later. #{BECOMES_ERROR_IN_2_0}."
end

.warn_legacy_ignore_matches(matches) ⇒ void

This method returns an undefined value.

Warns once per old-format ignore: entry (#126), naming each new id it matched with that mutant's file and subject. mutineer cannot tell a full run from a narrowed one, so the text always says the list covers only this run's mutants. An entry that matched more than one distinct mutant (in other files, or same-named methods in one file) over-matched: the old id could not tell them apart, so replacing it with every new id would keep suppressing the mutants it hid by accident.

Parameters:

  • matches (Hash{String => Array<Hash{Symbol => String}>}) —

    old-format entry => one {id:, file:, subject:} hash per matched mutant.



1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
# File 'lib/mutineer/cli.rb', line 1261

def self.warn_legacy_ignore_matches(matches)
  matches.each do |old, hits|
    listed = hits.map { |h| "#{h[:id]} (#{h[:file]}, #{h[:subject]})" }.join(", ")
    advice = if hits.map { |h| h[:id] }.uniq.size > 1
               "#{old} over-matched: the old format could not tell these mutants apart. " \
                 "Replace #{old} and keep only the ids for the mutant you meant to ignore, not all of them."
             else
               "Replace #{old} with the new ids in your ignore list."
             end
    warn "[mutineer] ignore entry #{old} uses the old id format, which did not include the " \
         "file path. It matched these new ids: #{listed}. This list covers only mutants in " \
         "this run's sources and operators; a run over every source gives the complete " \
         "replacement. #{advice} To update the file, run `mutineer migrate`. " \
         "#{BECOMES_ERROR_IN_2_0}."
  end
end

.warn_unmatched_ignores(ids) ⇒ void

This method returns an undefined value.

Warns once per ignore: entry that matched no mutant (#377). The text says the list covers only this run, so a run of some files does not claim an entry is stale in the rest of the project. The exit code does not change. --only passes an empty list (unmatched_ignore_ids).

Parameters:

  • ids (Array<String>) —

    unmatched ids, in file order.



1243
1244
1245
1246
1247
1248
# File 'lib/mutineer/cli.rb', line 1243

def self.warn_unmatched_ignores(ids)
  ids.each do |id|
    warn "[mutineer] ignore entry #{id} matched no mutant in this run's sources and operators. " \
         "If those cover its code, the entry is stale: remove it."
  end
end

.warn_unpaired_count_failures(failures) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Prints one stderr line per source whose mutant count failed. The report still lists that source with no count. The run continues.

Parameters:



1391
1392
1393
1394
1395
1396
1397
1398
1399
# File 'lib/mutineer/cli.rb', line 1391

def self.warn_unpaired_count_failures(failures)
  failures.each do |failure|
    warn Redaction.text(
      "[mutineer] could not count the mutants in #{failure[:file]} (#{failure[:error]}). " \
      "The report lists it with no count.",
      env: ENV
    )
  end
end

.warn_unused_coverage_from(config) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Warns when --coverage-from is set on a run that captures no coverage.

Parameters:



641
642
643
644
645
646
647
648
# File 'lib/mutineer/cli.rb', line 641

def self.warn_unused_coverage_from(config)
  mode = if config.test_command then "--test-command"
         elsif config.daemon then "--daemon"
         elsif config.dry_run then "--dry-run"
         elsif !config.boot then "a run without --rails/--boot"
         end
  warn_unused_settings(config, mode, %i[coverage_from]) if mode
end

.warn_unused_dry_run_settings(config) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

--dry-run prints a candidate list; --format html never renders one, and --output only writes when --format json builds that list (#362).

Parameters:



656
657
658
659
660
661
662
663
664
665
666
667
# File 'lib/mutineer/cli.rb', line 656

def self.warn_unused_dry_run_settings(config)
  return unless config.dry_run

  if config.explicit?(:format) && config.format == "html"
    warn "[mutineer] --format html has no effect with --dry-run " \
         "(it applies to a completed run; use --format json for candidates); ignoring it."
  end
  return unless config.explicit?(:output) && config.format != "json"

  warn "[mutineer] #{config.origin(:output)} has no effect with --dry-run " \
       "(it applies to --format json dry runs); ignoring it."
end

.warn_unused_settings(config, backend, keys) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

A backend that never reads a setting the user set would silently do nothing with it, so say so. --test-command builds no coverage map and has its own runtime, so it reads none of UNUSED_SETTING_SCOPE; the daemon reads the capture limit and the cache directory but keeps its own per-mutant limit.

Parameters:

  • config (Mutineer::Config) —

    run configuration.

  • backend (String) —

    the backend's flag.

  • keys (Array<Symbol>) —

    the settings that backend ignores.



680
681
682
683
684
685
686
687
# File 'lib/mutineer/cli.rb', line 680

def self.warn_unused_settings(config, backend, keys)
  keys.each do |key|
    next unless config.explicit?(key)

    applies = UNUSED_SETTING_SCOPE.fetch(key)
    warn "[mutineer] #{config.origin(key)} has no effect with #{backend} (it applies to #{applies}); ignoring it."
  end
end