mutineer 1.6.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +680 -0
  3. data/README.md +210 -499
  4. data/lib/mutineer/baseline.rb +1 -1
  5. data/lib/mutineer/changed_lines.rb +2 -1
  6. data/lib/mutineer/child_coverage.rb +53 -0
  7. data/lib/mutineer/cli.rb +293 -42
  8. data/lib/mutineer/concern_blocks.rb +243 -0
  9. data/lib/mutineer/config.rb +154 -8
  10. data/lib/mutineer/coverage_map.rb +265 -27
  11. data/lib/mutineer/daemon_backend.rb +244 -75
  12. data/lib/mutineer/daemon_client.rb +73 -10
  13. data/lib/mutineer/daemon_server.rb +226 -42
  14. data/lib/mutineer/external_backend.rb +159 -15
  15. data/lib/mutineer/init.rb +124 -0
  16. data/lib/mutineer/isolation.rb +78 -24
  17. data/lib/mutineer/job_plan.rb +234 -44
  18. data/lib/mutineer/kill_channel.rb +24 -14
  19. data/lib/mutineer/migrate.rb +707 -0
  20. data/lib/mutineer/minitest_integration/in_test_database_error.rb +184 -0
  21. data/lib/mutineer/minitest_integration/kill_recorder.rb +25 -17
  22. data/lib/mutineer/minitest_integration.rb +44 -14
  23. data/lib/mutineer/mutator_registry.rb +6 -2
  24. data/lib/mutineer/mutators/array_literal.rb +4 -2
  25. data/lib/mutineer/mutators/base.rb +36 -7
  26. data/lib/mutineer/mutators/call_to_receiver.rb +148 -0
  27. data/lib/mutineer/mutators/chain_link.rb +6 -6
  28. data/lib/mutineer/mutators/condition_forcing.rb +6 -3
  29. data/lib/mutineer/mutators/operand_removal.rb +4 -2
  30. data/lib/mutineer/mutators/range_literal.rb +105 -4
  31. data/lib/mutineer/mutators/return_nil.rb +1 -0
  32. data/lib/mutineer/orphan_guard.rb +84 -0
  33. data/lib/mutineer/pairing.rb +62 -1
  34. data/lib/mutineer/project.rb +302 -14
  35. data/lib/mutineer/rails_run_env.rb +73 -0
  36. data/lib/mutineer/rails_worker_db.rb +1596 -57
  37. data/lib/mutineer/redaction.rb +199 -0
  38. data/lib/mutineer/reporter.rb +173 -31
  39. data/lib/mutineer/result.rb +52 -15
  40. data/lib/mutineer/runner.rb +148 -28
  41. data/lib/mutineer/statement_lines.rb +24 -11
  42. data/lib/mutineer/subject.rb +30 -4
  43. data/lib/mutineer/test_runners/minitest.rb +2 -1
  44. data/lib/mutineer/test_runners/rspec.rb +15 -3
  45. data/lib/mutineer/test_runners.rb +5 -2
  46. data/lib/mutineer/triage.rb +111 -0
  47. data/lib/mutineer/version.rb +1 -1
  48. data/lib/mutineer/worker_pool.rb +2 -1
  49. data/lib/mutineer.rb +4 -0
  50. data/skills/mutineer/SKILL.md +84 -0
  51. metadata +13 -1
@@ -0,0 +1,707 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "set"
4
+ require "yaml"
5
+ require_relative "job_plan"
6
+ require_relative "mutator_registry"
7
+
8
+ module Mutineer
9
+ # Rewrites old-format mutant ids in a `.mutineer.yml` `ignore:` list to the
10
+ # current id format. The map is the inverse of the `id_map` and
11
+ # `dropped_id_map` from {JobPlan.collect_jobs}: each old id goes to every new
12
+ # id that still hashes to it, reported ids first, each group in collection
13
+ # order. A dropped repeat of an edit is not reported, but its id is still
14
+ # current (#275). The map covers only the configured operators and the
15
+ # sources on the command line. Ids are static hashes, so this runs no tests.
16
+ #
17
+ # The file is edited as text. A YAML load and dump would drop comments and
18
+ # reorder keys. Only a bare id inside `ignore:` is replaced. A flow list may
19
+ # span lines. A scalar changes only when its whole value is an id. A block
20
+ # scalar under `ignore:` raises ArgumentError. In a `{ id:, reason: }`
21
+ # mapping the id is replaced in place: `- id: x` lines, `- { id: x }` items,
22
+ # and `{ id: x }` entries inside `ignore: [...]`. Comments and reason text
23
+ # are never touched. An old id that now matches several mutants cannot fit
24
+ # one mapping, so it is left in place and reported for a hand edit. A
25
+ # baseline file is never read.
26
+ module Migrate
27
+ # One old id and the new ids that replace it, in {Migrate.id_maps} order.
28
+ Replacement = Data.define(:old_id, :new_ids)
29
+
30
+ # The outcome of rewriting one file in memory. `text` is what to write.
31
+ # It equals the input when nothing changed. `unmapped` holds bare ids that
32
+ # matched no mutant, in file order, each once.
33
+ #
34
+ # `split` holds old ids in a mapping entry that now match several new ids,
35
+ # as {Replacement}s: one mapping holds one id, so the user splits it by hand.
36
+ Outcome = Data.define(:replacements, :unmapped, :split, :text)
37
+
38
+ # Builds the id maps for `config`'s sources and operators.
39
+ #
40
+ # @param config [Mutineer::Config] run configuration, with sources set.
41
+ # @return [Array(Set<String>, Hash{String => Array<String>})]
42
+ # the current new ids, and each old id => its new ids.
43
+ def self.id_maps(config)
44
+ names = config.operators || MutatorRegistry::DEFAULT_NAMES
45
+ _jobs, _ignored, _source_map, extras = JobPlan.collect_jobs(config, MutatorRegistry.resolve(names))
46
+ all = extras[:id_map].merge(extras[:dropped_id_map])
47
+ old_to_new = {}
48
+ all.each do |new_id, old_id|
49
+ list = (old_to_new[old_id] ||= [])
50
+ list << new_id unless list.include?(new_id)
51
+ end
52
+ [all.keys.to_set, old_to_new]
53
+ end
54
+
55
+ # Rewrites `ignore:` ids in `text`. An id that is already a current new id
56
+ # stays, so a second run does not change the file. An old id is replaced by
57
+ # every new id it maps to. Any other bare id stays and is listed in
58
+ # {Outcome#unmapped}.
59
+ #
60
+ # A flow list may span lines. Only a scalar whose whole value is an id
61
+ # changes. A block scalar under `ignore:` raises ArgumentError, and so
62
+ # does a flow list this rewrite cannot read safely. The caller writes
63
+ # nothing in that case.
64
+ #
65
+ # @param text [String] the `.mutineer.yml` contents.
66
+ # @param current [Set<String>] new-format ids in this run.
67
+ # @param old_to_new [Hash{String => Array<String>}] old id => new ids.
68
+ # @return [Outcome]
69
+ # @raise [ArgumentError] when an `ignore:` shape cannot be rewritten safely.
70
+ def self.rewrite(text, current, old_to_new)
71
+ replacements = []
72
+ unmapped = []
73
+ split = []
74
+ lines = []
75
+ pending = text.lines
76
+ while (line = pending.shift)
77
+ case line_kind(line)
78
+ when :flow
79
+ lines << rewrite_flow(collect_flow(line, pending), current, old_to_new, replacements, unmapped, split)
80
+ when :scalar
81
+ lines.concat(rewrite_scalar(line, current, old_to_new, replacements, unmapped))
82
+ when :block_scalar
83
+ reject_block_scalar
84
+ when :block
85
+ lines << line
86
+ lines.concat(rewrite_block(pending, current, old_to_new, replacements, unmapped, split))
87
+ else
88
+ lines << line
89
+ end
90
+ end
91
+ out = lines.join
92
+ verify_rewrite!(text, out, current, old_to_new, split)
93
+ Outcome.new(replacements: replacements, unmapped: unmapped, split: split, text: out)
94
+ end
95
+
96
+ # Reads both texts as YAML and checks the text edit did what it claims.
97
+ # An id that still maps to a new id, and was not left for a hand split,
98
+ # means an entry shape the line edit missed (a mapping over several
99
+ # lines, a quoted key). A changed reason means the edit touched reason
100
+ # text. Either is refused, so nothing is written and nothing passes
101
+ # silently.
102
+ #
103
+ # @param before [String] the original file text.
104
+ # @param after [String] the rewritten text.
105
+ # @param current [Set<String>] new-format ids in this run.
106
+ # @param old_to_new [Hash{String => Array<String>}] old id => new ids.
107
+ # @param split [Array<Replacement>] mapping ids left for a hand split.
108
+ # @return [void]
109
+ # @raise [ArgumentError] when an old id was missed or a reason changed.
110
+ def self.verify_rewrite!(before, after, current, old_to_new, split)
111
+ old_ids, old_reasons = ignore_entries(before) || [[], []]
112
+ parsed = ignore_entries(after)
113
+ raise ArgumentError, "migrate would write a .mutineer.yml that is not valid YAML. Edit the ignore ids by hand." unless parsed
114
+
115
+ new_ids, new_reasons = parsed
116
+ left = split.map(&:old_id)
117
+ missed = (new_ids & old_ids).find { |id| old_to_new.key?(id) && !current.include?(id) && !left.include?(id) }
118
+ if missed
119
+ raise ArgumentError, "ignore entry #{missed} is in a shape migrate cannot edit. " \
120
+ "Write it as \"- id: #{missed}\" on its own line, or as a bare id."
121
+ end
122
+ return if old_reasons == new_reasons
123
+
124
+ raise ArgumentError, "migrate would change the text of an ignore: reason. Edit those ids by hand."
125
+ end
126
+
127
+ # The ids and reasons in a `.mutineer.yml` `ignore:` value, read as YAML,
128
+ # in file order. Ids are read as {Config.ignore_id_text} reads them.
129
+ #
130
+ # @param text [String] the file text.
131
+ # @return [Array(Array<String>, Array<String>), nil] ids and reasons, or nil when the text is not valid YAML.
132
+ def self.ignore_entries(text)
133
+ doc = YAML.safe_load(text)
134
+ value = doc.is_a?(Hash) ? doc["ignore"] : nil
135
+ items = value.is_a?(Array) ? value : [value].compact
136
+ ids = []
137
+ reasons = []
138
+ items.each do |item|
139
+ if item.is_a?(Hash)
140
+ ids << Config.ignore_id_text(item["id"])
141
+ reasons << item["reason"].to_s
142
+ else
143
+ ids << Config.ignore_id_text(item)
144
+ end
145
+ end
146
+ [ids.compact, reasons]
147
+ rescue Psych::Exception
148
+ nil
149
+ end
150
+ private_class_method :verify_rewrite!, :ignore_entries
151
+
152
+ class << self
153
+ private
154
+
155
+ # A block-list item whose value is one bare id.
156
+ ITEM = /\A([ \t]*-[ \t]+)(['"]?)([0-9a-f]{12})\2([ \t]*(?:\#.*)?)(\r?\n)?\z/
157
+
158
+ # A block-mapping line whose whole value is the `id:` key: `- id: x` or
159
+ # an indented `id: x`. Comments and reason text never match.
160
+ MAPPING_ID_LINE = /\A([ \t]*(?:-[ \t]+)?)(id[ \t]*:[ \t]*)(['"]?)([0-9a-f]{12})\3([ \t]*(?:\#.*)?)(\r?\n)?\z/
161
+
162
+ # A block-list item whose value is a flow mapping, `- { id: x, ... }`.
163
+ FLOW_MAPPING_ITEM = /\A([ \t]*-[ \t]+)(\{.*\})([ \t]*(?:\#.*)?)(\r?\n)?\z/
164
+
165
+ # Told to the user when a flow mapping's `id` cannot be located safely.
166
+ MAPPING_UNSUPPORTED_MESSAGE = "this ignore: { id:, reason: } entry is not supported. " \
167
+ "Write id: on its own line under the list item."
168
+
169
+ # `ignore:` followed by one bare id on the same line.
170
+ SCALAR = /\A(ignore:[ \t]*)(['"]?)([0-9a-f]{12})\2([ \t]*(?:\#.*)?)(\r?\n)?\z/
171
+
172
+ # `ignore: |` or `ignore: >`, including chomp and indent markers.
173
+ KEY_BLOCK_SCALAR = /\Aignore:[ \t]*[|>]/
174
+
175
+ # A list item whose value is a block scalar, such as `- |`.
176
+ ITEM_BLOCK_SCALAR = /\A[ \t]*-[ \t]+[|>]/
177
+
178
+ # An indented `|` or `>` that is the whole `ignore:` value.
179
+ VALUE_BLOCK_SCALAR = /\A[ \t]+[|>]/
180
+
181
+ # Told to the user when `ignore:` is a YAML block scalar. Exit 2.
182
+ BLOCK_SCALAR_MESSAGE = "a block scalar under ignore: is not supported. " \
183
+ "Write ignore as a list of ids, one per line."
184
+
185
+ # Told to the user when a flow `ignore:` list cannot be rewritten safely.
186
+ FLOW_UNSUPPORTED_MESSAGE = "this ignore: flow list is not supported. " \
187
+ "Write ignore as a list of ids, one per line."
188
+
189
+ # Told to the user when `ignore: [` never finds its closing bracket.
190
+ UNCLOSED_FLOW_MESSAGE = "an ignore: flow list has no closing ]. " \
191
+ "Write ignore as a list of ids, one per line."
192
+
193
+ # Which `ignore:` shape this line opens, or nil when it is some other line.
194
+ #
195
+ # @param line [String] one line of the file, its terminator included.
196
+ # @return [Symbol, nil] `:flow`, `:block_scalar`, `:block`, `:scalar`, or nil.
197
+ def line_kind(line)
198
+ return :flow if line.match?(/\Aignore:[ \t]*\[/)
199
+ return :block_scalar if line.match?(KEY_BLOCK_SCALAR)
200
+ return :block if line.match?(/\Aignore:[ \t]*(?:\#.*)?\r?\n?\z/)
201
+ return :scalar if line.match?(/\Aignore:[ \t]*\S/)
202
+
203
+ nil
204
+ end
205
+
206
+ # Whether `line` still belongs to a block-style `ignore:` value.
207
+ # A later root key does not. A blank line, a comment, an indented line,
208
+ # or a list item (indented or at column 0) does.
209
+ #
210
+ # @param line [String] the next line.
211
+ # @return [Boolean]
212
+ def inside_block?(line)
213
+ line.match?(/\A[ \t]*(?:\#.*)?\r?\n?\z/) || line.match?(/\A[ \t]*-[ \t]/) || line.match?(/\A[ \t]+\S/)
214
+ end
215
+
216
+ # The ids to write for one bare id. Records a replacement or an unmapped
217
+ # id. An id that is already current is returned unchanged and unrecorded,
218
+ # even when it also equals some other mutant's old id.
219
+ #
220
+ # @param id [String] the id in the file.
221
+ # @param current [Set<String>] new-format ids in this run.
222
+ # @param old_to_new [Hash{String => Array<String>}] old id => new ids.
223
+ # @param replacements [Array<Replacement>] recorded changes, in file order.
224
+ # @param unmapped [Array<String>] bare ids that matched nothing.
225
+ # @return [Array<String>] the ids to write in this position.
226
+ def mapped_ids(id, current, old_to_new, replacements, unmapped)
227
+ return [id] if current.include?(id)
228
+
229
+ news = old_to_new[id]
230
+ if news
231
+ replacements << Replacement.new(old_id: id, new_ids: news.dup) unless news == [id]
232
+ news.dup
233
+ else
234
+ unmapped << id unless unmapped.include?(id)
235
+ [id]
236
+ end
237
+ end
238
+
239
+ # Lines from `ignore: [` through the line that closes the flow list.
240
+ # Quotes and comments do not hide the closing bracket, and they do not
241
+ # supply a false one.
242
+ #
243
+ # @param line [String] the opening line, its terminator included.
244
+ # @param pending [Array<String>] the lines still to read.
245
+ # @return [String] the whole flow value, newlines included.
246
+ # @raise [ArgumentError] when the closing bracket is missing.
247
+ def collect_flow(line, pending)
248
+ chunk = line.dup
249
+ return chunk if matching_index(chunk, chunk.index("["), "[", "]")
250
+
251
+ while (next_line = pending.shift)
252
+ chunk << next_line
253
+ return chunk if matching_index(chunk, chunk.index("["), "[", "]")
254
+ end
255
+ raise ArgumentError, UNCLOSED_FLOW_MESSAGE
256
+ end
257
+
258
+ # Index of the `closer` that matches the `opener` at `start`, or nil.
259
+ # Quoted text and comments are not structure.
260
+ #
261
+ # @param text [String]
262
+ # @param start [Integer] index of the opening bracket.
263
+ # @param opener [String] `[` or `{`.
264
+ # @param closer [String] `]` or `}`.
265
+ # @return [Integer, nil]
266
+ def matching_index(text, start, opener, closer)
267
+ index = start + 1
268
+ depth = 1
269
+ state = :plain
270
+ while index < text.length
271
+ char = text[index]
272
+ case state
273
+ when :plain
274
+ if char == "'"
275
+ state = :single
276
+ elsif char == '"'
277
+ state = :double
278
+ elsif comment_at?(text, index)
279
+ newline = text.index("\n", index)
280
+ return nil unless newline
281
+
282
+ index = newline + 1
283
+ next
284
+ elsif char == opener
285
+ depth += 1
286
+ elsif char == closer
287
+ depth -= 1
288
+ return index if depth.zero?
289
+ end
290
+ when :single
291
+ if char == "'"
292
+ if text[index + 1] == "'"
293
+ index += 1
294
+ else
295
+ state = :plain
296
+ end
297
+ end
298
+ when :double
299
+ if char == "\\"
300
+ return nil if index + 1 >= text.length
301
+
302
+ index += 1
303
+ elsif char == '"'
304
+ state = :plain
305
+ end
306
+ end
307
+ index += 1
308
+ end
309
+ nil
310
+ end
311
+
312
+ # Whether `index` starts a YAML comment. A `#` inside a token does not.
313
+ #
314
+ # @param text [String]
315
+ # @param index [Integer]
316
+ # @return [Boolean]
317
+ def comment_at?(text, index)
318
+ return false unless text[index] == "#"
319
+
320
+ index.zero? || text[index - 1].match?(/\s/)
321
+ end
322
+
323
+ # Rewrites whole id scalars between the brackets of a flow list.
324
+ # The list may span lines. A scalar that only contains an id is kept.
325
+ # A `{ ... }` entry is kept. Nested lists and other shapes raise.
326
+ #
327
+ # @param chunk [String] `ignore: [` through the closing bracket.
328
+ # @param current [Set<String>] new-format ids in this run.
329
+ # @param old_to_new [Hash{String => Array<String>}] old id => new ids.
330
+ # @param replacements [Array<Replacement>] recorded changes.
331
+ # @param unmapped [Array<String>] bare ids that matched nothing.
332
+ # @param split [Array<Replacement>] mapping ids that now match several mutants.
333
+ # @return [String] the text to write.
334
+ # @raise [ArgumentError] when the list is not a flat list of scalars.
335
+ def rewrite_flow(chunk, current, old_to_new, replacements, unmapped, split)
336
+ open = chunk.index("[")
337
+ close = matching_index(chunk, open, "[", "]")
338
+ raise ArgumentError, UNCLOSED_FLOW_MESSAGE unless close
339
+
340
+ inner = rewrite_flow_items(chunk[(open + 1)...close], current, old_to_new, replacements, unmapped, split)
341
+ "#{chunk[0..open]}#{inner}#{chunk[close..]}"
342
+ end
343
+
344
+ # Rewrites the text between the flow brackets.
345
+ #
346
+ # @param inner [String] text between `[` and `]`.
347
+ # @param current [Set<String>] new-format ids in this run.
348
+ # @param old_to_new [Hash{String => Array<String>}] old id => new ids.
349
+ # @param replacements [Array<Replacement>] recorded changes.
350
+ # @param unmapped [Array<String>] bare ids that matched nothing.
351
+ # @param split [Array<Replacement>] mapping ids that now match several mutants.
352
+ # @return [String]
353
+ # @raise [ArgumentError] when an entry is not a scalar or a `{ ... }` entry.
354
+ def rewrite_flow_items(inner, current, old_to_new, replacements, unmapped, split)
355
+ out = +""
356
+ index = 0
357
+ while index < inner.length
358
+ char = inner[index]
359
+ if char.match?(/\s/) || char == ","
360
+ out << char
361
+ index += 1
362
+ elsif comment_at?(inner, index)
363
+ newline = inner.index("\n", index) || inner.length
364
+ out << inner[index...newline]
365
+ index = newline
366
+ else
367
+ raw, next_index = read_flow_item(inner, index)
368
+ raise ArgumentError, FLOW_UNSUPPORTED_MESSAGE if next_index <= index
369
+
370
+ out << if raw.start_with?("{")
371
+ rewrite_flow_mapping(raw, current, old_to_new, replacements, unmapped, split)
372
+ else
373
+ replace_flow_scalar(raw, current, old_to_new, replacements, unmapped)
374
+ end
375
+ index = next_index
376
+ end
377
+ end
378
+ out
379
+ end
380
+
381
+ # One flow entry starting at `index`: a quoted scalar, a plain scalar,
382
+ # or a whole `{ ... }` entry (its id is rewritten by {rewrite_flow_mapping}).
383
+ #
384
+ # @param text [String]
385
+ # @param index [Integer]
386
+ # @return [Array(String, Integer)] the raw entry and the index after it.
387
+ # @raise [ArgumentError] when the entry is not one of those shapes.
388
+ def read_flow_item(text, index)
389
+ case text[index]
390
+ when "'" then read_single_quoted(text, index)
391
+ when '"' then read_double_quoted(text, index)
392
+ when "{" then read_wrapped(text, index, "{", "}")
393
+ when "[", "|", ">", "!", "&", "*", "?"
394
+ raise ArgumentError, FLOW_UNSUPPORTED_MESSAGE
395
+ else
396
+ read_plain(text, index)
397
+ end
398
+ end
399
+
400
+ # A single-quoted scalar, including its quotes. `''` is an escaped quote.
401
+ #
402
+ # @param text [String]
403
+ # @param start [Integer] index of the opening quote.
404
+ # @return [Array(String, Integer)]
405
+ # @raise [ArgumentError] when the quote does not close.
406
+ def read_single_quoted(text, start)
407
+ index = start + 1
408
+ while index < text.length
409
+ if text[index] == "'"
410
+ if text[index + 1] == "'"
411
+ index += 2
412
+ next
413
+ end
414
+ return [text[start..index], index + 1]
415
+ end
416
+ index += 1
417
+ end
418
+ raise ArgumentError, FLOW_UNSUPPORTED_MESSAGE
419
+ end
420
+
421
+ # A double-quoted scalar, including its quotes. Backslash escapes are
422
+ # skipped so they cannot end the scalar early.
423
+ #
424
+ # @param text [String]
425
+ # @param start [Integer] index of the opening quote.
426
+ # @return [Array(String, Integer)]
427
+ # @raise [ArgumentError] when the quote does not close.
428
+ def read_double_quoted(text, start)
429
+ index = start + 1
430
+ while index < text.length
431
+ char = text[index]
432
+ if char == "\\"
433
+ raise ArgumentError, FLOW_UNSUPPORTED_MESSAGE if index + 1 >= text.length
434
+
435
+ index += 2
436
+ next
437
+ end
438
+ return [text[start..index], index + 1] if char == '"'
439
+
440
+ index += 1
441
+ end
442
+ raise ArgumentError, FLOW_UNSUPPORTED_MESSAGE
443
+ end
444
+
445
+ # The `{ ... }` or other wrapped entry starting at `start`, copied whole.
446
+ #
447
+ # @param text [String]
448
+ # @param start [Integer] index of the opener.
449
+ # @param opener [String]
450
+ # @param closer [String]
451
+ # @return [Array(String, Integer)]
452
+ # @raise [ArgumentError] when the closer is missing.
453
+ def read_wrapped(text, start, opener, closer)
454
+ stop = matching_index(text, start, opener, closer)
455
+ raise ArgumentError, FLOW_UNSUPPORTED_MESSAGE unless stop
456
+
457
+ [text[start..stop], stop + 1]
458
+ end
459
+
460
+ # A plain flow scalar. It ends at a comma, a comment, or a line break.
461
+ # A colon means the entry may be a mapping, which this rewrite does not
462
+ # split safely.
463
+ #
464
+ # @param text [String]
465
+ # @param start [Integer]
466
+ # @return [Array(String, Integer)]
467
+ # @raise [ArgumentError] when the entry is not a plain scalar.
468
+ def read_plain(text, start)
469
+ index = start
470
+ while index < text.length
471
+ char = text[index]
472
+ break if char == "," || char == "\n" || char == "\r"
473
+ break if comment_at?(text, index)
474
+ if char == ":" || char == "[" || char == "]" || char == "{" || char == "}" ||
475
+ char == "'" || char == '"'
476
+ raise ArgumentError, FLOW_UNSUPPORTED_MESSAGE
477
+ end
478
+
479
+ index += 1
480
+ end
481
+ [text[start...index], index]
482
+ end
483
+
484
+ # The quote, the id, and the gaps around it when `raw` is exactly one id.
485
+ # Nil when `raw` is any other scalar.
486
+ #
487
+ # @param raw [String] one flow entry, quotes included.
488
+ # @return [Array(String, String, String, String), nil]
489
+ def flow_scalar_id(raw)
490
+ if (match = raw.match(/\A([0-9a-f]{12})([ \t]*)\z/))
491
+ return ["", match[1], "", match[2]]
492
+ end
493
+ if raw.start_with?("'") && raw.end_with?("'")
494
+ value = raw[1..-2].gsub("''", "'")
495
+ return ["'", value, "", ""] if value.match?(/\A[0-9a-f]{12}\z/)
496
+ end
497
+ if raw.start_with?('"') && raw.end_with?('"')
498
+ value = raw[1..-2]
499
+ # A backslash can hide an id. Do not guess the decoded text.
500
+ raise ArgumentError, FLOW_UNSUPPORTED_MESSAGE if value.include?("\\")
501
+
502
+ return ['"', value, "", ""] if value.match?(/\A[0-9a-f]{12}\z/)
503
+ end
504
+ nil
505
+ end
506
+
507
+ # Replaces `raw` when its whole scalar value is an id. Several new ids
508
+ # become several entries. Any other entry is returned unchanged.
509
+ #
510
+ # @param raw [String] one flow entry.
511
+ # @param current [Set<String>] new-format ids in this run.
512
+ # @param old_to_new [Hash{String => Array<String>}] old id => new ids.
513
+ # @param replacements [Array<Replacement>] recorded changes.
514
+ # @param unmapped [Array<String>] bare ids that matched nothing.
515
+ # @return [String]
516
+ def replace_flow_scalar(raw, current, old_to_new, replacements, unmapped)
517
+ parts = flow_scalar_id(raw)
518
+ return raw unless parts
519
+
520
+ quote, value, lead, trail = parts
521
+ ids = mapped_ids(value, current, old_to_new, replacements, unmapped)
522
+ return raw if ids == [value]
523
+
524
+ "#{lead}#{ids.map { |id| "#{quote}#{id}#{quote}" }.join(", ")}#{trail}"
525
+ end
526
+
527
+ # The lines of a block-style `ignore:` value. A block scalar here is
528
+ # rejected. A `{ id:, reason: }` entry is rewritten by {rewrite_item}.
529
+ #
530
+ # @param pending [Array<String>] the lines still to read.
531
+ # @param current [Set<String>] new-format ids in this run.
532
+ # @param old_to_new [Hash{String => Array<String>}] old id => new ids.
533
+ # @param replacements [Array<Replacement>] recorded changes.
534
+ # @param unmapped [Array<String>] bare ids that matched nothing.
535
+ # @param split [Array<Replacement>] mapping ids that now match several mutants.
536
+ # @return [Array<String>]
537
+ # @raise [ArgumentError] when the value or a list item is a block scalar.
538
+ def rewrite_block(pending, current, old_to_new, replacements, unmapped, split)
539
+ written = []
540
+ saw_entry = false
541
+ while (next_line = pending.first) && inside_block?(next_line)
542
+ raise ArgumentError, BLOCK_SCALAR_MESSAGE if block_scalar_entry?(next_line, saw_entry)
543
+
544
+ saw_entry = true if next_line.match?(/\A[ \t]*[^ \t#\r\n]/)
545
+ written.concat(rewrite_item(pending.shift, current, old_to_new, replacements, unmapped, split))
546
+ end
547
+ written
548
+ end
549
+
550
+ # Rejects a block scalar `ignore:` value. The constant lives on this
551
+ # singleton, so {rewrite} calls this method instead of reading it.
552
+ #
553
+ # @return [void]
554
+ # @raise [ArgumentError] always.
555
+ def reject_block_scalar
556
+ raise ArgumentError, BLOCK_SCALAR_MESSAGE
557
+ end
558
+
559
+ # Whether `line` is a block scalar used as the ignore value or as one
560
+ # list item. A `|` under a later key, such as `reason: |`, is not.
561
+ #
562
+ # @param line [String]
563
+ # @param saw_entry [Boolean] true after the first real entry in the value.
564
+ # @return [Boolean]
565
+ def block_scalar_entry?(line, saw_entry)
566
+ line.match?(ITEM_BLOCK_SCALAR) || (!saw_entry && line.match?(VALUE_BLOCK_SCALAR))
567
+ end
568
+
569
+ # Rewrites a one-line `ignore: <id>`. Several new ids become a block list,
570
+ # so each id stays a bare string. The comment stays on the key line.
571
+ #
572
+ # @param line [String] an `ignore: <id>` line.
573
+ # @param current [Set<String>] new-format ids in this run.
574
+ # @param old_to_new [Hash{String => Array<String>}] old id => new ids.
575
+ # @param replacements [Array<Replacement>] recorded changes.
576
+ # @param unmapped [Array<String>] bare ids that matched nothing.
577
+ # @return [Array<String>] the lines to write.
578
+ def rewrite_scalar(line, current, old_to_new, replacements, unmapped)
579
+ match = SCALAR.match(line)
580
+ return [line] unless match
581
+
582
+ ids = mapped_ids(match[3], current, old_to_new, replacements, unmapped)
583
+ quote = match[2]
584
+ if ids.size == 1
585
+ ["#{match[1]}#{quote}#{ids.first}#{quote}#{match[4]}#{match[5]}"]
586
+ else
587
+ ending = match[5].to_s
588
+ ending = "\n" if ending.empty?
589
+ ["ignore:#{match[4]}#{ending}", *render_lines(" - ", quote, ids, "", ending)]
590
+ end
591
+ end
592
+
593
+ # Rewrites one block-list item, or returns the line unchanged when it is
594
+ # not a bare id (a comment, a blank line, or a `{ id:, reason: }` entry).
595
+ #
596
+ # @param line [String] one line inside an `ignore:` block.
597
+ # @param current [Set<String>] new-format ids in this run.
598
+ # @param old_to_new [Hash{String => Array<String>}] old id => new ids.
599
+ # @param replacements [Array<Replacement>] recorded changes.
600
+ # @param unmapped [Array<String>] bare ids that matched nothing.
601
+ # @param split [Array<Replacement>] mapping ids that now match several mutants.
602
+ # @return [Array<String>] the lines to write.
603
+ def rewrite_item(line, current, old_to_new, replacements, unmapped, split)
604
+ match = ITEM.match(line)
605
+ return [rewrite_mapping_id(line, current, old_to_new, replacements, unmapped, split)] unless match
606
+
607
+ ids = mapped_ids(match[3], current, old_to_new, replacements, unmapped)
608
+ render_lines(match[1], match[2], ids, match[4], match[5].to_s)
609
+ end
610
+
611
+ # Replaces the id in a block-mapping `id:` line or a `- { ... }` item,
612
+ # keeping the reason, quotes and comment. Other lines are returned as is.
613
+ #
614
+ # @param line [String] one line inside the `ignore:` block.
615
+ # @param current [Set<String>] new-format ids in this run.
616
+ # @param old_to_new [Hash{String => Array<String>}] old id => new ids.
617
+ # @param replacements [Array<Replacement>] recorded changes, in file order.
618
+ # @param unmapped [Array<String>] bare ids that matched nothing.
619
+ # @param split [Array<Replacement>] mapping ids that now match several mutants.
620
+ # @return [String] the line to write.
621
+ # @raise [ArgumentError] when a flow mapping's id cannot be located safely.
622
+ def rewrite_mapping_id(line, current, old_to_new, replacements, unmapped, split)
623
+ if (match = MAPPING_ID_LINE.match(line))
624
+ new_id = mapping_id(match[4], current, old_to_new, replacements, unmapped, split)
625
+ return "#{match[1]}#{match[2]}#{match[3]}#{new_id}#{match[3]}#{match[5]}#{match[6]}"
626
+ end
627
+ if (match = FLOW_MAPPING_ITEM.match(line))
628
+ mapping = rewrite_flow_mapping(match[2], current, old_to_new, replacements, unmapped, split)
629
+ return "#{match[1]}#{mapping}#{match[3]}#{match[4]}"
630
+ end
631
+ line
632
+ end
633
+
634
+ # Replaces the `id` value in one flow mapping, `{ id: x, reason: y }`.
635
+ # YAML reads the entry first, and the id is replaced only at a key
636
+ # position (after `{` or `,`), so an id quoted inside a reason stays.
637
+ # A mapping with no 12-hex `id` is returned unchanged.
638
+ #
639
+ # @param raw [String] the `{ ... }` text.
640
+ # @param current [Set<String>] new-format ids in this run.
641
+ # @param old_to_new [Hash{String => Array<String>}] old id => new ids.
642
+ # @param replacements [Array<Replacement>] recorded changes, in file order.
643
+ # @param unmapped [Array<String>] bare ids that matched nothing.
644
+ # @param split [Array<Replacement>] mapping ids that now match several mutants.
645
+ # @return [String]
646
+ # @raise [ArgumentError] when the entry does not parse or its id is not at exactly one key position.
647
+ def rewrite_flow_mapping(raw, current, old_to_new, replacements, unmapped, split)
648
+ parsed = begin
649
+ YAML.safe_load(raw)
650
+ rescue Psych::SyntaxError
651
+ raise ArgumentError, MAPPING_UNSUPPORTED_MESSAGE
652
+ end
653
+ id = parsed.is_a?(Hash) ? Config.ignore_id_text(parsed["id"]) : nil
654
+ return raw unless id&.match?(/\A[0-9a-f]{12}\z/)
655
+
656
+ key = /([{,][ \t\r\n]*id[ \t]*:[ \t]*)(['"]?)#{id}\2(?=[ \t\r\n]*[,}])/
657
+ raise ArgumentError, MAPPING_UNSUPPORTED_MESSAGE unless raw.scan(key).size == 1
658
+
659
+ new_id = mapping_id(id, current, old_to_new, replacements, unmapped, split)
660
+ raw.sub(key) { "#{Regexp.last_match(1)}#{Regexp.last_match(2)}#{new_id}#{Regexp.last_match(2)}" }
661
+ end
662
+
663
+ # The one id a mapping entry can hold. An old id that now matches several
664
+ # mutants stays and is recorded in `split` for a hand edit.
665
+ #
666
+ # @param id [String] the id in the file.
667
+ # @param current [Set<String>] new-format ids in this run.
668
+ # @param old_to_new [Hash{String => Array<String>}] old id => new ids.
669
+ # @param replacements [Array<Replacement>] recorded changes, in file order.
670
+ # @param unmapped [Array<String>] bare ids that matched nothing.
671
+ # @param split [Array<Replacement>] mapping ids that now match several mutants.
672
+ # @return [String]
673
+ def mapping_id(id, current, old_to_new, replacements, unmapped, split)
674
+ news = old_to_new[id]
675
+ if news && news.size > 1 && !current.include?(id)
676
+ split << Replacement.new(old_id: id, new_ids: news.dup)
677
+ return id
678
+ end
679
+
680
+ mapped_ids(id, current, old_to_new, replacements, unmapped).first
681
+ end
682
+
683
+ # One list item per id. The original comment stays on the first item.
684
+ # Only the last item keeps the original line ending, so a file that does
685
+ # not end in a newline still does not.
686
+ #
687
+ # @param prefix [String] the indentation and list marker.
688
+ # @param quote [String] `"` or `'` or `""`.
689
+ # @param ids [Array<String>] ids to write.
690
+ # @param suffix [String] the original trailing comment, spaces included.
691
+ # @param ending [String] the original line ending, or `""`.
692
+ # @return [Array<String>]
693
+ def render_lines(prefix, quote, ids, suffix, ending)
694
+ last = ids.size - 1
695
+ ids.each_with_index.map do |id, i|
696
+ tail = i.zero? ? suffix : ""
697
+ mark = if i == last
698
+ ending
699
+ else
700
+ ending.empty? ? "\n" : ending
701
+ end
702
+ "#{prefix}#{quote}#{id}#{quote}#{tail}#{mark}"
703
+ end
704
+ end
705
+ end
706
+ end
707
+ end