How to run Rubocop only on the changed files in a pull request?

martins picture martins · Sep 13, 2015 · Viewed 8k times · Source

I have created spec/lint/rubocop_spec.rb which runs Rubocop style checker on the files changed between current branch and master. This works when I test locally but not when the test run on the build server Circle.ci. I suspect it is because only the branch in question is downloaded, so it does not find any differences between master. Is there a better way than git co master && git pull origin master? Can I query the Github API perhaps to get the files changed listed?

require 'spec_helper'

describe 'Check that the files we have changed have correct syntax' do
  before do
    current_sha = `git rev-parse --verify HEAD`.strip!
    files = `git diff master #{current_sha} --name-only | grep .rb`
    files.tr!("\n", ' ')
    @report = 'nada'
    if files.present?
      puts "Changed files: #{files}"

      @report = `rubocop #{files}`
      puts "Report: #{@report}"
    end
  end

  it { @report.match('Offenses').should_not be true }
end

Answer

Tim Diggins picture Tim Diggins · Mar 27, 2017

You don't have to use github api, or even ruby (unless you want to wrap the responses) you can just run:

git fetch && git diff-tree -r --no-commit-id --name-only master@\{u\} head | xargs ls -1 2>/dev/null | xargs rubocop --force-exclusion

see http://www.red56.uk/2017/03/26/running-rubocop-on-changed-files/ for longer write-up of this