summaryrefslogtreecommitdiff
path: root/tests/source/whitespace.py
blob: 2d979fdd47884edb23bbb8d78af3577fa34b85ad (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""Helper for checking whitespace.

These operations aren't easy to do in pure shell.
"""

from __future__ import print_function

import sys


def check(path):
    with open(path, 'rb') as fp:
        # Skip 0 byte files.
        first_byte = fp.read(1)
        if not first_byte:
            return 0

        # Check for leading blank lines.
        if b'\n' == first_byte:
            print('%s: trim leading blank lines' % (path,), file=sys.stderr)
            return 1

        # Check for missing trailing new line.
        fp.seek(-1, 2)
        if b'\n' != fp.read(1):
            print('%s: missing trailing new line' % (path,), file=sys.stderr)
            return 1
        elif fp.tell() == 1:
            print('%s: dummy file' % (path,), file=sys.stderr)
            return 1

        # Check for trailing blank lines.
        fp.seek(-2, 2)
        if b'\n\n' == fp.read(2):
            print('%s: trim trailing blank lines' % (path,), file=sys.stderr)
            return 1

    return 0


def main(argv):
    ret = 0
    for path in argv:
        ret |= check(path)
    return ret


if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))