Correctly remove newline at end of file on Windows

The code for removing a newline at the end of a file was assuming that each
`eol` in `possible_eols` would be 1 character in length. This assumption
doesn't hold on Windows, where a newline is 2 characters long (`\r\n`). As a
result, auto-formatting files that have a Windows-style line ending would
result in the file's last line being terminated by `\r` (the full EOL cut in
half, essentially).

With this patch, we not only check that the last character of `stdoutdata`
matches the candidate `eol`, but instead check the full sequence of
characters depending on the length of `eol`.
This commit is contained in:
lethal-guitar 2019-07-08 20:57:07 +02:00
parent 4f993fad63
commit a7009a9688

View File

@ -225,8 +225,9 @@ else:
# However, extra newlines are almost never required, while there are linters that complain # However, extra newlines are almost never required, while there are linters that complain
# about superfluous newlines, so we remove one empty newline at the end of the file. # about superfluous newlines, so we remove one empty newline at the end of the file.
for eol in possible_eols: for eol in possible_eols:
if len(stdoutdata) > 0 and stdoutdata[-1] == eol: eol_len = len(eol)
stdoutdata = stdoutdata[:-1] if len(stdoutdata) > 0 and stdoutdata[-eol_len:] == eol:
stdoutdata = stdoutdata[:-eol_len]
lines = [stdoutdata] lines = [stdoutdata]
for eol in possible_eols: for eol in possible_eols:
@ -288,8 +289,9 @@ else:
# However, extra newlines are almost never required, while there are linters that complain # However, extra newlines are almost never required, while there are linters that complain
# about superfluous newlines, so we remove one empty newline at the end of the file. # about superfluous newlines, so we remove one empty newline at the end of the file.
for eol in possible_eols: for eol in possible_eols:
if len(stdoutdata) > 0 and stdoutdata[-1] == eol: eol_len = len(eol)
stdoutdata = stdoutdata[:-1] if len(stdoutdata) > 0 and stdoutdata[-eol_len:] == eol:
stdoutdata = stdoutdata[:-eol_len]
lines = [stdoutdata] lines = [stdoutdata]
for eol in possible_eols: for eol in possible_eols: