check_docstring_first.py 2.1 KB
Newer Older
1
from __future__ import absolute_import
2
from __future__ import print_function
3
4
5
6
7
from __future__ import unicode_literals

import argparse
import io
import tokenize
8
9
from typing import Optional
from typing import Sequence
10
11
12
13
14
15
16
17


NON_CODE_TOKENS = frozenset((
    tokenize.COMMENT, tokenize.ENDMARKER, tokenize.NEWLINE, tokenize.NL,
))


def check_docstring_first(src, filename='<unknown>'):
18
    # type: (str, str) -> int
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
    """Returns nonzero if the source has what looks like a docstring that is
    not at the beginning of the source.

    A string will be considered a docstring if it is a STRING token with a
    col offset of 0.
    """
    found_docstring_line = None
    found_code_line = None

    tok_gen = tokenize.generate_tokens(io.StringIO(src).readline)
    for tok_type, _, (sline, scol), _, _ in tok_gen:
        # Looks like a docstring!
        if tok_type == tokenize.STRING and scol == 0:
            if found_docstring_line is not None:
                print(
Anthony Sottile's avatar
Anthony Sottile 已提交
34
35
                    '{}:{} Multiple module docstrings '
                    '(first docstring on line {}).'.format(
36
                        filename, sline, found_docstring_line,
37
                    ),
38
39
40
41
                )
                return 1
            elif found_code_line is not None:
                print(
Anthony Sottile's avatar
Anthony Sottile 已提交
42
43
                    '{}:{} Module docstring appears after code '
                    '(code seen on line {}).'.format(
44
                        filename, sline, found_code_line,
45
                    ),
46
47
48
49
50
51
52
53
54
55
                )
                return 1
            else:
                found_docstring_line = sline
        elif tok_type not in NON_CODE_TOKENS and found_code_line is None:
            found_code_line = sline

    return 0


56
def main(argv=None):  # type: (Optional[Sequence[str]]) -> int
57
58
59
60
61
62
63
    parser = argparse.ArgumentParser()
    parser.add_argument('filenames', nargs='*')
    args = parser.parse_args(argv)

    retv = 0

    for filename in args.filenames:
64
65
        with io.open(filename, encoding='UTF-8') as f:
            contents = f.read()
66
67
68
        retv |= check_docstring_first(contents, filename=filename)

    return retv