Last active
November 19, 2020 16:43
-
-
Save arika/9c945d9a452aed3eebff0bcd6f2b7f3d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require "yaml" | |
| require "json" | |
| require "tempfile" | |
| def run(*cmd) | |
| system(*cmd) | |
| raise "failed: #{cmd.join(' ')}" unless $?.success? | |
| end | |
| def run_rubocop(*args, on_failure: :raise) | |
| run("rubocop", *args) | |
| rescue => e | |
| warn "\n#{e}" | |
| abort if on_failure == :abort | |
| raise | |
| end | |
| def run_rubocop_for_check(*args) | |
| print "\n*** try to detect errors...\n\n" | |
| run_rubocop(*args, on_failure: :abort) | |
| end | |
| def run_git(*args) | |
| run("git", *args) | |
| rescue => e | |
| warn e | |
| abort | |
| end | |
| def work_tree_changed? | |
| run("git", "diff", "--quiet") | |
| false | |
| rescue | |
| true | |
| end | |
| sep_idx = ARGV.index("--") || 0 | |
| targets = ARGV[(sep_idx + 1)..-1] | |
| commit_log_prefix, = ARGV[0, sep_idx] | |
| args_base = [ | |
| "--only", "Layout", # or "Layout,Style", | |
| "--safe", | |
| ] | |
| args_auto_correct = [ | |
| *args_base, | |
| "--safe-auto-correct", | |
| "--fail-level", "E", | |
| ] | |
| args_check = [ | |
| *args_base, | |
| "--fail-level", "E", | |
| "--display-only-fail-level-offenses", | |
| ] | |
| print "*** calculate auto-correct plan...\n\n" | |
| begin | |
| output = Tempfile.open("correct_cop_names") do |tf| | |
| run_rubocop( | |
| *args_auto_correct, | |
| "--display-cop-names", | |
| "--format", "fuubar", | |
| "--format", "json", | |
| "--out", tf.path, | |
| *targets, | |
| ) | |
| tf.read | |
| end | |
| rescue | |
| run_rubocop_for_check(*args_check, *targets) | |
| abort | |
| end | |
| cop_names = JSON.parse(output)["files"] | |
| .map {|f| f["offenses"].select {|o| o["corrected"] } } | |
| .flatten | |
| .group_by {|o| o["cop_name"] } | |
| .transform_values(&:size) | |
| .sort_by {|_, v| -v } | |
| .map(&:first) | |
| run_git("restore", ".") | |
| cop_names.partition {|cop_name| /\ALayout/.match?(cop_name) }.each do |cns| | |
| cns.each do |cop_name| | |
| print "\n*** auto-correct by #{cop_name}...\n\n" | |
| args_base = ["--only", cop_name, "--safe"] | |
| begin | |
| run_rubocop( | |
| *args_auto_correct, | |
| "--format", "autogenconf", | |
| *targets, | |
| ) | |
| rescue | |
| run_rubocop_for_check(*args_check, *targets) | |
| abort | |
| end | |
| if work_tree_changed? | |
| run_git("add", ".") | |
| run_git("commit", "-q", "-m", "#{commit_log_prefix}auto-correct by RuboCop #{cop_name}") | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment