2019-05-12 03:57:25 -05:00
|
|
|
"""
|
|
|
|
utils.doclinter
|
|
|
|
~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
A linter for Sphinx docs
|
|
|
|
|
|
|
|
:copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
|
|
|
|
:license: BSD, see LICENSE for details.
|
|
|
|
"""
|
|
|
|
|
|
|
|
import os
|
|
|
|
import re
|
|
|
|
import sys
|
|
|
|
from typing import List
|
|
|
|
|
2019-05-29 11:07:05 -05:00
|
|
|
MAX_LINE_LENGTH = 85
|
2019-05-21 08:42:57 -05:00
|
|
|
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*)')
|
2019-05-12 03:57:25 -05:00
|
|
|
|
|
|
|
|
|
|
|
def lint(path: str) -> int:
|
|
|
|
with open(path) as f:
|
|
|
|
document = f.readlines()
|
|
|
|
|
|
|
|
errors = 0
|
2019-05-21 08:42:57 -05:00
|
|
|
in_code_block = False
|
|
|
|
code_block_depth = 0
|
2019-05-12 03:57:25 -05:00
|
|
|
for i, line in enumerate(document):
|
|
|
|
if line.endswith(' '):
|
|
|
|
print('%s:%d: the line ends with whitespace.' %
|
|
|
|
(path, i + 1))
|
|
|
|
errors += 1
|
|
|
|
|
2019-05-21 08:42:57 -05:00
|
|
|
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)
|
2021-06-05 22:52:44 -05:00
|
|
|
if len(spaces) <= code_block_depth:
|
2019-05-21 08:42:57 -05:00
|
|
|
in_code_block = False
|
|
|
|
elif LONG_INTERPRETED_TEXT.match(line):
|
|
|
|
pass
|
|
|
|
elif len(line) > MAX_LINE_LENGTH:
|
2019-05-12 03:57:25 -05:00
|
|
|
if re.match(r'^\s*\.\. ', line):
|
|
|
|
# ignore directives and hyperlink targets
|
|
|
|
pass
|
2021-07-05 10:52:11 -05:00
|
|
|
elif re.match(r'^\s*__ ', line):
|
|
|
|
# ignore anonymous hyperlink targets
|
|
|
|
pass
|
2020-07-24 09:09:54 -05:00
|
|
|
elif re.match(r'^\s*``[^`]+``$', line):
|
|
|
|
# ignore a very long literal string
|
|
|
|
pass
|
2019-05-12 03:57:25 -05:00
|
|
|
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
|
2019-05-21 08:59:53 -05:00
|
|
|
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)
|
2019-05-12 03:57:25 -05:00
|
|
|
|
|
|
|
if errors:
|
|
|
|
return 1
|
|
|
|
else:
|
|
|
|
return 0
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
sys.exit(main(sys.argv[1:]))
|