psf / black

The uncompromising Python code formatter
https://black.readthedocs.io/en/stable/
MIT License
38.84k stars 2.45k forks source link

Error in Visual Studio when formatting with no newline at end of file #2542

Open AdamYoblick opened 3 years ago

AdamYoblick commented 3 years ago

Describe the bug

When trying to format a document in Visual Studio using the black formatter, an error is thrown when there is no newline at the end of the file. Please see https://github.com/microsoft/PTVS/issues/6752 for details.

To Reproduce

  1. Create a python application in Visual Studio
  2. Paste the following code (remove newline at end!)

# this is a comment
import os
import sys
spam(ham[1], {eggs: 2})
def foo(): pass

x = 1
y = 2
y = 2
# comment no newline
  1. Ensure black is the selected formatter (Tools -> Options -> Text Editor -> Python -> Formatting) is black
  2. Go to Edit -> Advanced -> Format Document
  3. Observe the following error:

image

Expected behavior

The file should be formatted correctly

Environment (please complete the following information):

JelleZijlstra commented 3 years ago

Is Visual Studio invoking black --diff? I think we print a special diff message saying "No newline at end of file".

AdamYoblick commented 3 years ago

I'm not sure, let me dig into the exact command VS is running and I'll report back.

AdamYoblick commented 3 years ago

Looks like the Python Tools extension invokes it, and indeed with --diff.

https://github.com/microsoft/PTVS/blob/main/Python/Product/PythonTools/PythonTools/Editor/Formatting/PythonFormatterBlack.cs#L30

JelleZijlstra commented 3 years ago

Thanks, then we're probably hitting this: https://github.com/psf/black/blob/b1d060101626aa1c332f52e4bdf0ae5e4cc07990/src/black/output.py#L72 . We added that in #1897 for some fairly involved reasons.

TBBle commented 1 year ago

This looks like a PTVS bug to me. \ is a valid patch mode, per the GNU diffutils docs.

Anyway, looks like this was resolved on the PTVS side (by ignoring that line of the diff and then manually doing newline fixups) so I think this should be closed.