Add --check support to EOF and Trailing Whitespace fixers

This change adds an advisory mode via `--check` that only warns of
formatting issues with files, but does not address them.

This support is desirable because--while I don't mind the automagic
changes when done in a mechanical way--some individuals who I
described the current behavior of these fixers to were a bit uneasy
about the magic that went along with them. Adding `--check` so
others can opt out (similar to `black --check`) is a compromise on
this front.

Signed-off-by: Enji Cooper <yaneurabeya@gmail.com>
This commit is contained in:
Enji Cooper 2019-12-18 17:25:07 -08:00
parent 5df1a4bf6f
commit a17514d55e
4 changed files with 65 additions and 20 deletions

View file

@ -9,7 +9,7 @@ from typing import Optional
from typing import Sequence
def fix_file(file_obj): # type: (IO[bytes]) -> int
def fix_file(file_obj, apply_fixes=True): # type: (IO[bytes], bool) -> int
# Test for newline at end of file
# Empty files will throw IOError here
try:
@ -20,8 +20,9 @@ def fix_file(file_obj): # type: (IO[bytes]) -> int
# last_character will be '' for an empty file
if last_character not in {b'\n', b'\r'} and last_character != b'':
# Needs this seek for windows, otherwise IOError
file_obj.seek(0, os.SEEK_END)
file_obj.write(b'\n')
if apply_fixes:
file_obj.seek(0, os.SEEK_END)
file_obj.write(b'\n')
return 1
while last_character in {b'\n', b'\r'}:
@ -29,8 +30,9 @@ def fix_file(file_obj): # type: (IO[bytes]) -> int
if file_obj.tell() == 1:
# If we've reached the beginning of the file and it is all
# linebreaks then we can make this file empty
file_obj.seek(0)
file_obj.truncate()
if apply_fixes:
file_obj.seek(0)
file_obj.truncate()
return 1
# Go back two bytes and read a character
@ -45,8 +47,9 @@ def fix_file(file_obj): # type: (IO[bytes]) -> int
if remaining == sequence:
return 0
elif remaining.startswith(sequence):
file_obj.seek(position + len(sequence))
file_obj.truncate()
if apply_fixes:
file_obj.seek(position + len(sequence))
file_obj.truncate()
return 1
return 0
@ -54,6 +57,11 @@ def fix_file(file_obj): # type: (IO[bytes]) -> int
def main(argv=None): # type: (Optional[Sequence[str]]) -> int
parser = argparse.ArgumentParser()
parser.add_argument(
'--check', action='store_true',
help="Don't write the files back. Returns a non-zero code if changes "
'would be applied. Returns zero if no changes are required.',
)
parser.add_argument('filenames', nargs='*', help='Filenames to fix')
args = parser.parse_args(argv)
@ -62,9 +70,12 @@ def main(argv=None): # type: (Optional[Sequence[str]]) -> int
for filename in args.filenames:
# Read as binary so we can read byte-by-byte
with open(filename, 'rb+') as file_obj:
ret_for_file = fix_file(file_obj)
ret_for_file = fix_file(file_obj, apply_fixes=not args.check)
if ret_for_file:
print('Fixing {}'.format(filename))
if args.check:
print('Would fix {}'.format(filename))
else:
print('Fixing {}'.format(filename))
retv |= ret_for_file
return retv