Tags: SergeKireev/pants
Tags
Format our python code with Black (pantsbuild#8391) ### Problem Our python code isn't very consistently formatted. More importantly, the formatting we do enforce involves manual steps which are a workflow painpoint. Also, we waste previous code review energy discussing stylistic things since a tool isn't holding our hand as we write the code. ### Solution Run `./pants fmt-v2 ::` on the pants repo. This formats every python code that is part of a target. Also homogenise the .isort.cfg setting files to avoid interferences. ### Result All the python code is consistently formatted and it will be trivial to keep it this way. Note: a couple of extra steps are required: * Enforce black formatting in a git hook * Add the sha1 of this commit to an exclude list so it doesn't appear in `git blame` These steps will be taken in a subsequent PR to avoid mixing business logic and automatic reformatting logic in this one. ### Note: on rebasing feature branches Note that this change touches most python files in the repository. If you have an ongoing feature branch that pre-dates the black commit, you can avoid the pain of manual conflict handling by automating the conflict resolutions that are related to formatting. Here is how to (note: this assumes your branch is named `feature_branch`, your remote is named `your_remote`, and there is a tag for the "black-formatting" commit called `black-formatting` - we will set this tag promptly after merging the PR) ``` # Checkout your feature branch git checkout feature_branch # The pre-commit check can be a little annoying when doing rebases (can't pass --no-verify). # Let's manually disable it for the time of our rebases mv ./.git/hooks/pre-commit ./.git/hooks/pre-commit.backup # Manually handle any (genuine) conflict pre_black git rebase black-formatting^ # Automatically format the code in each commit of your feature branch git rebase --interactive --exec './pants --owner-of="`git show --name-only --pretty=\"\" HEAD`" fmt-v2 && git add `git show --name-only --pretty="" HEAD` && git commit --amend --no-edit && git stash' black-formatting^ # Rebase your formatted code on top of the black commit. # Because of the previous step, and because the black commit only formats files, # This should not cause any conflict. # (Caveat: if you touched the isort config or one of the tests that were formatting dependent, # you may have a small amount of conflicts to handle) git rebase --interactive --strategy-option=theirs --exec './pants --changed-parent="HEAD^" fmt-v2 && git add `git show --name-only --pretty="" HEAD` && git commit --amend --no-edit' black-formatting # Handle any conflict since black (only genuine conflicts. formatting won't be part of it) git rebase master # Don't forget to re-enable the pre-commit hook mv ./.git/hooks/pre-commit.backup ./.git/hooks/pre-commit # All done. When you're ready, you may update your PR. git push -f your_remote feature_branch ```
PreviousNext