blob: 4e77c9452a67470831e10f073309bfd2747f6590 [file] [log] [blame]
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import os
import sys
from typing import IO
from typing import Optional
from typing import Sequence
def fix_file(file_obj): # type: (IO[bytes]) -> int
# Test for newline at end of file
# Empty files will throw IOError here
try:, os.SEEK_END)
except IOError:
return 0
last_character =
# 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, os.SEEK_END)
return 1
while last_character in {b'\n', b'\r'}:
# Deal with the beginning of the file
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
return 1
# Go back two bytes and read a character, os.SEEK_CUR)
last_character =
# Our current position is at the end of the file just before any amount of
# newlines. If we find extraneous newlines, then backtrack and trim them.
position = file_obj.tell()
remaining =
for sequence in (b'\n', b'\r\n', b'\r'):
if remaining == sequence:
return 0
elif remaining.startswith(sequence): + len(sequence))
return 1
return 0
def main(argv=None): # type: (Optional[Sequence[str]]) -> int
parser = argparse.ArgumentParser()
parser.add_argument('filenames', nargs='*', help='Filenames to fix')
args = parser.parse_args(argv)
retv = 0
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)
if ret_for_file:
print('Fixing {}'.format(filename))
retv |= ret_for_file
return retv
if __name__ == '__main__':