Welcome to mirror list, hosted at ThFree Co, Russian Federation.

doclinter.py « utils - github.com/sphinx-doc/sphinx.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 6ef8cbe10a708932e388192e414ce22ec363aae2 (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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
"""A linter for Sphinx docs"""

import os
import re
import sys
from typing import List

MAX_LINE_LENGTH = 85
LONG_INTERPRETED_TEXT = re.compile(r'^\s*\W*(:(\w+:)+)?`.*`\W*$')
CODE_BLOCK_DIRECTIVE = re.compile(r'^(\s*)\.\. code-block::')
LEADING_SPACES = re.compile(r'^(\s*)')


def lint(path: str) -> int:
    with open(path) as f:
        document = f.readlines()

    errors = 0
    in_code_block = False
    code_block_depth = 0
    for i, line in enumerate(document):
        if line.endswith(' '):
            print('%s:%d: the line ends with whitespace.' %
                  (path, i + 1))
            errors += 1

        matched = CODE_BLOCK_DIRECTIVE.match(line)
        if matched:
            in_code_block = True
            code_block_depth = len(matched.group(1))
        elif in_code_block:
            if line.strip() == '':
                pass
            else:
                spaces = LEADING_SPACES.match(line).group(1)
                if len(spaces) <= code_block_depth:
                    in_code_block = False
        elif LONG_INTERPRETED_TEXT.match(line):
            pass
        elif len(line) > MAX_LINE_LENGTH:
            if re.match(r'^\s*\.\. ', line):
                # ignore directives and hyperlink targets
                pass
            elif re.match(r'^\s*__ ', line):
                # ignore anonymous hyperlink targets
                pass
            elif re.match(r'^\s*``[^`]+``$', line):
                # ignore a very long literal string
                pass
            else:
                print('%s:%d: the line is too long (%d > %d).' %
                      (path, i + 1, len(line), MAX_LINE_LENGTH))
                errors += 1

    return errors


def main(args: List[str]) -> int:
    errors = 0
    for path in args:
        if os.path.isfile(path):
            errors += lint(path)
        elif os.path.isdir(path):
            for root, _dirs, files in os.walk(path):
                for filename in files:
                    if filename.endswith('.rst'):
                        path = os.path.join(root, filename)
                        errors += lint(path)

    if errors:
        return 1
    else:
        return 0


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