|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +import argparse |
| 4 | +import re |
| 5 | +import sys |
| 6 | + |
| 7 | +ANY_NEWLINE = re.compile(rb'(\r\n|\r|\n)') |
| 8 | + |
| 9 | +parser = argparse.ArgumentParser( |
| 10 | + prog='check-lineends.py', |
| 11 | + description='Line end checker for the MMTk project', |
| 12 | + epilog=''' |
| 13 | +This script checks if the file FILENAME has proper line ends: |
| 14 | +
|
| 15 | +1. it uses UNIX line ends, and |
| 16 | +2. it has a newline character at the end of the file |
| 17 | +
|
| 18 | +If you add the -f option, it will try to fix the line ends if wrong. |
| 19 | +''') |
| 20 | + |
| 21 | +parser.add_argument('-q', '--quiet', action='store_true', help='Quiet mode') |
| 22 | +parser.add_argument('-v', '--verbose', action='store_true', help='Verbose mode') |
| 23 | +parser.add_argument('-f', '--fix', action='store_true', help='Fix files with wrong line ends') |
| 24 | +parser.add_argument('filename', nargs='*', help='File name') |
| 25 | + |
| 26 | +verbosity = 1 |
| 27 | + |
| 28 | +def pv(level, *args, **kwargs): |
| 29 | + if verbosity >= level: |
| 30 | + print(*args, **kwargs) |
| 31 | + |
| 32 | +def process_file(filename, fix): |
| 33 | + pv(2, "Processing file:", filename) |
| 34 | + with open(filename, 'rb') as f: |
| 35 | + content = f.read() |
| 36 | + |
| 37 | + non_unix = b'\r' in content |
| 38 | + no_eol = not content.endswith(b'\n') |
| 39 | + wrong = non_unix or no_eol |
| 40 | + |
| 41 | + if non_unix: |
| 42 | + pv(1, "File contains non-UNIX line ends:", filename) |
| 43 | + if no_eol: |
| 44 | + pv(1, "File does not end with a newline character:", filename) |
| 45 | + |
| 46 | + if wrong and fix: |
| 47 | + pv(1, "Fixing file:", filename) |
| 48 | + fixed_content = ANY_NEWLINE.sub(b'\n', content) |
| 49 | + if no_eol: |
| 50 | + fixed_content += b'\n' |
| 51 | + with open(filename, 'wb') as f: |
| 52 | + f.write(fixed_content) |
| 53 | + |
| 54 | + return wrong |
| 55 | + |
| 56 | + |
| 57 | +def main(): |
| 58 | + args = parser.parse_args() |
| 59 | + |
| 60 | + global verbosity |
| 61 | + if args.quiet: |
| 62 | + verbosity = 0 |
| 63 | + if args.verbose: |
| 64 | + verbosity = 2 |
| 65 | + |
| 66 | + any_wrong = False |
| 67 | + |
| 68 | + for filename in args.filename: |
| 69 | + if process_file(filename, args.fix) == True: |
| 70 | + any_wrong = True |
| 71 | + |
| 72 | + if any_wrong: |
| 73 | + sys.exit(1) |
| 74 | + |
| 75 | +if __name__=='__main__': |
| 76 | + main() |
0 commit comments