Class: Lumin::Autocorrector
- Inherits:
-
Object
- Object
- Lumin::Autocorrector
- Defined in:
- lib/lumin/autocorrector.rb
Defined Under Namespace
Classes: CorrectionError, Result
Instance Method Summary collapse
- #call(path, unsafe: false, dry_run: false) ⇒ Object
-
#initialize(worker, max_iterations: 5) ⇒ Autocorrector
constructor
A new instance of Autocorrector.
Constructor Details
#initialize(worker, max_iterations: 5) ⇒ Autocorrector
Returns a new instance of Autocorrector.
15 16 17 18 |
# File 'lib/lumin/autocorrector.rb', line 15 def initialize(worker, max_iterations: 5) @worker = worker @max_iterations = max_iterations end |
Instance Method Details
#call(path, unsafe: false, dry_run: false) ⇒ Object
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
# File 'lib/lumin/autocorrector.rb', line 20 def call(path, unsafe: false, dry_run: false) snapshot = SourceSnapshot.read(path) original = snapshot.source current = original warnings = [] iterations = 0 source = parse(current, path) @max_iterations.times do iterations += 1 break unless source.valid? offenses = @worker.lint_source(source) corrections = offenses.select { |offense| offense.correctable? && (offense.safe || unsafe) } break if corrections.empty? rewriter = Astel::Rewriter.new(source) corrections.each do |offense| begin offense.correction.call(rewriter) rescue Astel::Rewriter::ConflictError warnings << "#{path}: skipped conflicting correction for #{offense.rule_name}" end end break if rewriter.edits.empty? rewritten = rewriter.rewrite break if rewritten == current parsed = parse(rewritten, path) raise CorrectionError, "autocorrection produced invalid Ruby for #{path}" unless parsed.valid? current = rewritten source = parsed end final_offenses = @worker.lint_source(source) remaining = final_offenses.any? { |offense| offense.correctable? && (offense.safe || unsafe) } if iterations == @max_iterations && remaining warnings << "#{path}: autocorrection did not converge after #{@max_iterations} iterations" end corrected = current != original fingerprint = if corrected && !dry_run write_atomically(path, current, expected_fingerprint: snapshot.fingerprint) elsif corrected nil else snapshot.fingerprint end Result.new( offenses: final_offenses, corrected: corrected, diff: corrected && dry_run ? unified_diff(path, original, current) : nil, warnings: warnings.uniq.freeze, content_digest: Digest::SHA256.hexdigest(current), fingerprint: fingerprint ) end |