Review Just Your Changed Code

Review only the code in your current PR with Sourcery and incrementally improve the quality of your codebase.

Written by Reka Horvath on

Google Python Style Guide in Sourcery

In the last weeks, we learned that several teams are in a similar situation:

To review only changed code, we introduced a new feature in version 0.12.11: the --diff option in the Sourcery CLI. You can provide here any command that returns a diff.

For example, if you want Sourcery to review only the code you haven’t committed yet:

sourcery review --diff "git diff" .

If you want to review your changes compared to the main branch:

sourcery review --diff "git diff main" .

Continuous Integration & Improvement

The new --diff option is also the best way to configure Sourcery in CI environments. You probably want to review the changes compared to the branch you want to merge into.

For example, for PRs to the main branch, you could set up a script like that in your CI:

pip install sourcery
# Store your Sourcery token as a secret in your CI environment.
sourcery login --token $SOURCERY_TOKEN
sourcery review --check --diff "git diff main" .

Pre-commit

Another way to catch code quality issues early is a pre-commit hook. Again, the recommended way to set this up is with the --diff option:

repos:
    - repo: https://github.com/sourcery-ai/sourcery
      rev: v1.12.0
      hooks:
          - id: sourcery
            # The best way to use Sourcery in a pre-commit hook
            # is to review only changed lines:
            args: [--diff=git diff HEAD, --no-summary]

Review Your Code with a Built-in Rule Package

With the finetuning opportunities of the --diff option, you can also consider introducing more advanced rules to your codebase.

sourcery review --enable google-python-style-guide .

Do you have some feedback to the new features? Do you have some ideas how Sourcery could help you improve your code and make it more maintainable? We’d love to hear your thoughts. Reach out on Twitter or via email at hello@sourcery.ai

Updates