check_docstring_first.py 1.9 KB
Newer Older
1
2
3
import argparse
import io
import tokenize
4
from tokenize import tokenize as tokenize_tokenize
5
6
from typing import Optional
from typing import Sequence
7

8
9
10
11
NON_CODE_TOKENS = frozenset((
    tokenize.COMMENT, tokenize.ENDMARKER, tokenize.NEWLINE, tokenize.NL,
    tokenize.ENCODING,
))
12
13


14
def check_docstring_first(src: bytes, filename: str = '<unknown>') -> int:
15
16
17
18
19
20
21
22
23
    """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

24
    tok_gen = tokenize_tokenize(io.BytesIO(src).readline)
25
26
27
28
29
    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(
30
31
                    f'{filename}:{sline} Multiple module docstrings '
                    f'(first docstring on line {found_docstring_line}).',
32
33
34
35
                )
                return 1
            elif found_code_line is not None:
                print(
36
37
                    f'{filename}:{sline} Module docstring appears after code '
                    f'(code seen on line {found_code_line}).',
38
39
40
41
42
43
44
45
46
47
                )
                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


48
def main(argv: Optional[Sequence[str]] = None) -> int:
49
50
51
52
53
54
55
    parser = argparse.ArgumentParser()
    parser.add_argument('filenames', nargs='*')
    args = parser.parse_args(argv)

    retv = 0

    for filename in args.filenames:
56
        with open(filename, 'rb') as f:
57
            contents = f.read()
58
59
60
        retv |= check_docstring_first(contents, filename=filename)

    return retv