pytorch/tools/linter/trailing_newlines.py
Rong Rong (AI Infra) 7e619b9588 First step to rearrange files in tools folder (#60473)
Summary:
Changes including:
- introduced `linter/`, `testing/`, `stats/` folders in `tools/`
- move appropriate scripts into these folders
- change grepped references in the pytorch/pytorch repo

Next step
- introduce `build/` folder for build scripts

Pull Request resolved: https://github.com/pytorch/pytorch/pull/60473

Test Plan:
- CI (this is important b/c pytorch/test-infra also rely on some script reference.
- tools/tests/

Reviewed By: albanD

Differential Revision: D29352716

Pulled By: walterddr

fbshipit-source-id: bad40b5ce130b35dfd9e59b8af34f9025f3285fd
2021-06-24 10:13:58 -07:00

38 lines
882 B
Python
Executable File

#!/usr/bin/env python3
import fileinput
import os
import sys
NEWLINE, = b'\n'
def correct_trailing_newlines(filename: str) -> bool:
with open(filename, 'rb') as f:
a = len(f.read(2))
if a == 0:
return True
elif a == 1:
# file is wrong whether or not the only byte is a newline
return False
else:
f.seek(-2, os.SEEK_END)
b, c = f.read(2)
# no ASCII byte is part of any non-ASCII character in UTF-8
return b != NEWLINE and c == NEWLINE
def main() -> int:
# mimic git grep exit code behavior
exit_code = 1
for line in fileinput.input():
stripped = line.rstrip()
if not correct_trailing_newlines(stripped):
exit_code = 0
print(stripped)
return exit_code
if __name__ == '__main__':
sys.exit(main())