15

Does the Python formatting tool Black have an option for undoing the formatting changes it made after it's been run? Or does it assume I'm using source control and making my own backups? This is as of December 2019 and Black version 19.3b0.

ruohola
  • 21,987
  • 6
  • 62
  • 97
Al Sweigart
  • 11,566
  • 10
  • 64
  • 92
  • 4
    It assumes you're using source control (as all of us should be). Well, strictly speaking it doesn't assume anything. It simply formats code. Use version control, or re-save open unmodified buffers in your editor, or restore from a backup, or refomat manually, or accept that you asked a tool to reformat your code and live with it. – ChrisGPT was on strike Dec 10 '19 at 01:05
  • 4
    However, there is `--diff` option (don't write the files back, just write on stdout). – wim Dec 10 '19 at 01:07

4 Answers4

12

No it does not. It does nothing more, but reformat the files it has been passed. It's simply a well behaved Unix tool and it expects you to handle your own version control.

Its --diff option is the best you can get:

--diff

Don't write the files back, just output a diff for each file on stdout.

Source: https://github.com/psf/black#command-line-options

Community
  • 1
  • 1
ruohola
  • 21,987
  • 6
  • 62
  • 97
3

Some text editors and IDEs like Pycharm allow you to simply hit cmd+Z (or whatever the undo command is within the editor) to revert back to the state before autoformatting. Also, before autoformatting you can test out what the results will be using Black Playground.

jmdeamer
  • 337
  • 2
  • 16
  • I use Pycharm as my main IDE, but it doesn't seem to know how to undo Black reformats. Would love to find out I'm wrong! – spen.smith May 31 '22 at 19:04
1

Using the --diff flag, it is possible to pipe the output to patch which then emits to stdout. A one-line shellscript can be used as a wrapper, where $1 is the file that is being formatted:

black --quiet --diff "$1" | patch --quiet -o - "$1"

alex
  • 11
  • 1
0

For case when you've accidentally formatted a lot of legacy code with black pre-commit (meaning https://pre-commit.com/) hook when you didn't wanted to.

Warning: think before you execute each of these commands to check if it is right thing to do in your case

  1. Copy list of reformatted files from black precommit hook output into separate file, named filelist for example
  2. export SKIP=black to temporarily disable black precommit hook
  3. Your original (unformatted) changes are already in index, commit them with git commit now.
  4. Now, unset SKIP to enable black precommit hook again

Now you can work with filelist on your own to undo formatting changes while your original changes are already committed.

featuredpeow
  • 2,061
  • 1
  • 19
  • 18