Skip to content

Commit 7f39201

Browse files
amanagrtimabbott
authored andcommitted
lint: Use zulint as wrapper for running different linters.
1 parent 2646322 commit 7f39201

File tree

3 files changed

+131
-221
lines changed

3 files changed

+131
-221
lines changed

requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,4 @@ pytest
77
-e ./zulip
88
-e ./zulip_bots
99
-e ./zulip_botserver
10+
-e git+https://github.com/zulip/zulint@aaed679f1ad38b230090eadd3870b7682500f60c#egg=zulint==1.0.0

tools/custom_check.py

Lines changed: 90 additions & 196 deletions
Original file line numberDiff line numberDiff line change
@@ -1,126 +1,36 @@
11
from __future__ import print_function
22
from __future__ import absolute_import
33

4-
import os
5-
import re
6-
import traceback
7-
8-
from server_lib.printer import print_err, colors
9-
10-
from typing import cast, Any, Callable, Dict, List, Optional, Tuple
11-
12-
def build_custom_checkers(by_lang):
13-
# type: (Dict[str, List[str]]) -> Tuple[Callable[[], bool], Callable[[], bool]]
14-
RuleList = List[Dict[str, Any]]
15-
16-
def custom_check_file(fn, identifier, rules, skip_rules=None, max_length=None):
17-
# type: (str, str, RuleList, Optional[Any], Optional[int]) -> bool
18-
failed = False
19-
color = next(colors)
20-
21-
line_tups = []
22-
for i, line in enumerate(open(fn)):
23-
line_newline_stripped = line.strip('\n')
24-
line_fully_stripped = line_newline_stripped.strip()
25-
skip = False
26-
for rule in skip_rules or []:
27-
if re.match(rule, line):
28-
skip = True
29-
if line_fully_stripped.endswith(' # nolint'):
30-
continue
31-
if skip:
32-
continue
33-
tup = (i, line, line_newline_stripped, line_fully_stripped)
34-
line_tups.append(tup)
35-
36-
rules_to_apply = []
37-
fn_dirname = os.path.dirname(fn)
38-
for rule in rules:
39-
exclude_list = rule.get('exclude', set())
40-
if fn in exclude_list or fn_dirname in exclude_list:
41-
continue
42-
if rule.get("include_only"):
43-
found = False
44-
for item in rule.get("include_only", set()):
45-
if item in fn:
46-
found = True
47-
if not found:
48-
continue
49-
rules_to_apply.append(rule)
50-
51-
for rule in rules_to_apply:
52-
exclude_lines = {
53-
line for
54-
(exclude_fn, line) in rule.get('exclude_line', set())
55-
if exclude_fn == fn
56-
}
57-
58-
pattern = rule['pattern']
59-
for (i, line, line_newline_stripped, line_fully_stripped) in line_tups:
60-
if line_fully_stripped in exclude_lines:
61-
exclude_lines.remove(line_fully_stripped)
62-
continue
63-
try:
64-
line_to_check = line_fully_stripped
65-
if rule.get('strip') is not None:
66-
if rule['strip'] == '\n':
67-
line_to_check = line_newline_stripped
68-
else:
69-
raise Exception("Invalid strip rule")
70-
if re.search(pattern, line_to_check):
71-
print_err(identifier, color, '{} at {} line {}:'.format(
72-
rule['description'], fn, i+1))
73-
print_err(identifier, color, line)
74-
failed = True
75-
except Exception:
76-
print("Exception with %s at %s line %s" % (rule['pattern'], fn, i+1))
77-
traceback.print_exc()
78-
79-
if exclude_lines:
80-
print('Please remove exclusions for file %s: %s' % (fn, exclude_lines))
81-
82-
lastLine = None
83-
for (i, line, line_newline_stripped, line_fully_stripped) in line_tups:
84-
if isinstance(line, bytes):
85-
line_length = len(line.decode("utf-8"))
86-
else:
87-
line_length = len(line)
88-
if (max_length is not None and line_length > max_length and
89-
'# type' not in line and 'test' not in fn and 'example' not in fn and
90-
not re.match("\[[ A-Za-z0-9_:,&()-]*\]: http.*", line) and
91-
not re.match("`\{\{ external_api_uri_subdomain \}\}[^`]+`", line) and
92-
"#ignorelongline" not in line and 'migrations' not in fn):
93-
print("Line too long (%s) at %s line %s: %s" % (len(line), fn, i+1, line_newline_stripped))
94-
failed = True
95-
lastLine = line
96-
97-
if lastLine and ('\n' not in lastLine):
98-
print("No newline at the end of file. Fix with `sed -i '$a\\' %s`" % (fn,))
99-
failed = True
100-
101-
return failed
102-
103-
whitespace_rules = [
104-
# This linter should be first since bash_rules depends on it.
105-
{'pattern': '\s+$',
106-
'strip': '\n',
107-
'description': 'Fix trailing whitespace'},
108-
{'pattern': '\t',
109-
'strip': '\n',
110-
'description': 'Fix tab-based whitespace'},
111-
] # type: RuleList
112-
markdown_whitespace_rules = list([rule for rule in whitespace_rules if rule['pattern'] != '\s+$']) + [
113-
# Two spaces trailing a line with other content is okay--it's a markdown line break.
114-
# This rule finds one space trailing a non-space, three or more trailing spaces, and
115-
# spaces on an empty line.
116-
{'pattern': '((?<!\s)\s$)|(\s\s\s+$)|(^\s+$)',
117-
'strip': '\n',
118-
'description': 'Fix trailing whitespace'},
119-
{'pattern': '^#+[A-Za-z0-9]',
120-
'strip': '\n',
121-
'description': 'Missing space after # in heading'},
122-
] # type: RuleList
123-
python_rules = cast(RuleList, [
4+
from typing import cast, Any, Dict, List, Tuple
5+
from zulint.custom_rules import RuleList
6+
7+
Rule = List[Dict[str, Any]]
8+
9+
whitespace_rules = [
10+
# This linter should be first since bash_rules depends on it.
11+
{'pattern': '\s+$',
12+
'strip': '\n',
13+
'description': 'Fix trailing whitespace'},
14+
{'pattern': '\t',
15+
'strip': '\n',
16+
'description': 'Fix tab-based whitespace'},
17+
] # type: Rule
18+
19+
markdown_whitespace_rules = list([rule for rule in whitespace_rules if rule['pattern'] != '\s+$']) + [
20+
# Two spaces trailing a line with other content is okay--it's a markdown line break.
21+
# This rule finds one space trailing a non-space, three or more trailing spaces, and
22+
# spaces on an empty line.
23+
{'pattern': '((?<!\s)\s$)|(\s\s\s+$)|(^\s+$)',
24+
'strip': '\n',
25+
'description': 'Fix trailing whitespace'},
26+
{'pattern': '^#+[A-Za-z0-9]',
27+
'strip': '\n',
28+
'description': 'Missing space after # in heading'},
29+
] # type: Rule
30+
31+
python_rules = RuleList(
32+
langs=['py'],
33+
rules=cast(Rule, [
12434
{'pattern': '".*"%\([a-z_].*\)?$',
12535
'description': 'Missing space around "%"'},
12636
{'pattern': "'.*'%\([a-z_].*\)?$",
@@ -186,84 +96,68 @@ def custom_check_file(fn, identifier, rules, skip_rules=None, max_length=None):
18696
'bad_lines': ['class TestSomeBot(DefaultTests, BotTestCase):'],
18797
'good_lines': ['class TestSomeBot(BotTestCase, DefaultTests):'],
18898
'description': 'Bot test cases should inherit from BotTestCase before DefaultTests.'},
189-
]) + whitespace_rules
190-
bash_rules = [
99+
]) + whitespace_rules,
100+
max_length=140,
101+
)
102+
103+
bash_rules = RuleList(
104+
langs=['sh'],
105+
rules=cast(Rule, [
191106
{'pattern': '#!.*sh [-xe]',
192107
'description': 'Fix shebang line with proper call to /usr/bin/env for Bash path, change -x|-e switches'
193108
' to set -x|set -e'},
194-
] + whitespace_rules[0:1] # type: RuleList
195-
prose_style_rules = [
196-
{'pattern': '[^\/\#\-\"]([jJ]avascript)', # exclude usage in hrefs/divs
197-
'description': "javascript should be spelled JavaScript"},
198-
{'pattern': '[^\/\-\.\"\'\_\=\>]([gG]ithub)[^\.\-\_\"\<]', # exclude usage in hrefs/divs
199-
'description': "github should be spelled GitHub"},
200-
{'pattern': '[oO]rganisation', # exclude usage in hrefs/divs
201-
'description': "Organization is spelled with a z"},
202-
{'pattern': '!!! warning',
203-
'description': "!!! warning is invalid; it's spelled '!!! warn'"},
204-
{'pattern': '[^-_]botserver(?!rc)|bot server',
205-
'description': "Use Botserver instead of botserver or Botserver."},
206-
] # type: RuleList
207-
json_rules = [] # type: RuleList # fix newlines at ends of files
208-
# It is okay that json_rules is empty, because the empty list
209-
# ensures we'll still check JSON files for whitespace.
210-
markdown_rules = markdown_whitespace_rules + prose_style_rules + [
109+
]) + whitespace_rules[0:1],
110+
)
111+
112+
113+
json_rules = RuleList(
114+
langs=['json'],
115+
# Here, we don't check tab-based whitespace, because the tab-based
116+
# whitespace rule flags a lot of third-party JSON fixtures
117+
# under zerver/webhooks that we want preserved verbatim. So
118+
# we just include the trailing whitespace rule and a modified
119+
# version of the tab-based whitespace rule (we can't just use
120+
# exclude in whitespace_rules, since we only want to ignore
121+
# JSON files with tab-based whitespace, not webhook code).
122+
rules= whitespace_rules[0:1],
123+
)
124+
125+
prose_style_rules = [
126+
{'pattern': '[^\/\#\-\"]([jJ]avascript)', # exclude usage in hrefs/divs
127+
'description': "javascript should be spelled JavaScript"},
128+
{'pattern': '[^\/\-\.\"\'\_\=\>]([gG]ithub)[^\.\-\_\"\<]', # exclude usage in hrefs/divs
129+
'description': "github should be spelled GitHub"},
130+
{'pattern': '[oO]rganisation', # exclude usage in hrefs/divs
131+
'description': "Organization is spelled with a z"},
132+
{'pattern': '!!! warning',
133+
'description': "!!! warning is invalid; it's spelled '!!! warn'"},
134+
{'pattern': '[^-_]botserver(?!rc)|bot server',
135+
'description': "Use Botserver instead of botserver or Botserver."},
136+
] # type: Rule
137+
138+
markdown_docs_length_exclude = {
139+
"zulip_bots/zulip_bots/bots/converter/doc.md",
140+
"tools/server_lib/README.md",
141+
}
142+
143+
markdown_rules = RuleList(
144+
langs=['md'],
145+
rules=markdown_whitespace_rules + prose_style_rules + cast(Rule, [
211146
{'pattern': '\[(?P<url>[^\]]+)\]\((?P=url)\)',
212147
'description': 'Linkified markdown URLs should use cleaner <http://example.com> syntax.'}
213-
]
214-
help_markdown_rules = markdown_rules + [
215-
{'pattern': '[a-z][.][A-Z]',
216-
'description': "Likely missing space after end of sentence"},
217-
{'pattern': '[rR]ealm',
218-
'description': "Realms are referred to as Organizations in user-facing docs."},
219-
]
220-
txt_rules = whitespace_rules
221-
222-
def check_custom_checks_py():
223-
# type: () -> bool
224-
failed = False
225-
226-
for fn in by_lang['py']:
227-
if 'custom_check.py' in fn:
228-
continue
229-
if custom_check_file(fn, 'py', python_rules, max_length=140):
230-
failed = True
231-
return failed
232-
233-
def check_custom_checks_nonpy():
234-
# type: () -> bool
235-
failed = False
236-
237-
for fn in by_lang['sh']:
238-
if custom_check_file(fn, 'sh', bash_rules):
239-
failed = True
240-
241-
for fn in by_lang['json']:
242-
if custom_check_file(fn, 'json', json_rules):
243-
failed = True
244-
245-
markdown_docs_length_exclude = {
246-
"zulip_bots/zulip_bots/bots/converter/doc.md",
247-
"tools/server_lib/README.md",
248-
}
249-
for fn in by_lang['md']:
250-
max_length = None
251-
if fn not in markdown_docs_length_exclude:
252-
max_length = 120
253-
rules = markdown_rules
254-
if fn.startswith("templates/zerver/help"):
255-
rules = help_markdown_rules
256-
if custom_check_file(fn, 'md', rules, max_length=max_length):
257-
failed = True
258-
259-
for fn in by_lang['txt'] + by_lang['text']:
260-
if custom_check_file(fn, 'txt', txt_rules):
261-
failed = True
262-
263-
for fn in by_lang['yaml']:
264-
if custom_check_file(fn, 'yaml', txt_rules):
265-
failed = True
266-
267-
return failed
268-
269-
return (check_custom_checks_py, check_custom_checks_nonpy)
148+
]),
149+
max_length=120,
150+
length_exclude=markdown_docs_length_exclude,
151+
)
152+
153+
txt_rules = RuleList(
154+
langs=['txt'],
155+
rules=whitespace_rules,
156+
)
157+
158+
non_py_rules = [
159+
json_rules,
160+
markdown_rules,
161+
bash_rules,
162+
txt_rules,
163+
]

tools/lint

Lines changed: 40 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,54 @@
11
#! /usr/bin/env python
22

3-
from pep8 import check_pep8
4-
from custom_check import build_custom_checkers
5-
from server_lib import lister
3+
from __future__ import print_function
4+
from __future__ import absolute_import
5+
import argparse
6+
7+
from zulint.command import add_default_linter_arguments, LinterConfig
68

7-
import sys
8-
import optparse
9-
from typing import cast, Callable, Dict, Iterator, List
9+
from custom_check import python_rules, non_py_rules
10+
from pep8 import check_pep8
1011

1112
EXCLUDED_FILES = [
1213
# This is an external file that doesn't comply with our codestyle
1314
'zulip/integrations/perforce/git_p4.py',
1415
]
1516

16-
def lint_all(args, options):
17-
18-
by_lang = cast(Dict[str, List[str]],
19-
lister.list_files(args, modified_only=options.modified,
20-
ftypes=['py', 'sh', 'js', 'pp', 'css', 'handlebars',
21-
'html', 'json', 'md', 'txt', 'text', 'yaml'],
22-
use_shebang=True, group_by_ftype=True, exclude=EXCLUDED_FILES))
23-
check_custom_checks_py, check_custom_checks_nonpy = build_custom_checkers(by_lang)
24-
return any([check_pep8(by_lang['py']),
25-
check_custom_checks_py(),
26-
check_custom_checks_nonpy()])
27-
2817
def run():
2918
# type: () -> None
30-
parser = optparse.OptionParser()
31-
parser.add_option('--modified', '-m',
32-
action='store_true',
33-
help='Only check modified files')
34-
(options, args) = parser.parse_args()
35-
failed = lint_all(args, options)
36-
sys.exit(1 if failed else 0)
19+
parser = argparse.ArgumentParser()
20+
add_default_linter_arguments(parser)
21+
args = parser.parse_args()
22+
23+
linter_config = LinterConfig(args)
24+
25+
by_lang = linter_config.list_files(file_types=['py', 'sh', 'json', 'md', 'txt'],
26+
exclude=EXCLUDED_FILES)
27+
28+
@linter_config.lint
29+
def custom_py():
30+
# type: () -> int
31+
"""Runs custom checks for python files (config: tools/linter_lib/custom_check.py)"""
32+
failed = python_rules.check(by_lang, verbose=args.verbose)
33+
return 1 if failed else 0
34+
35+
@linter_config.lint
36+
def custom_nonpy():
37+
# type: () -> int
38+
"""Runs custom checks for non-python files (config: tools/linter_lib/custom_check.py)"""
39+
failed = False
40+
for rule in non_py_rules:
41+
failed = failed or rule.check(by_lang, verbose=args.verbose)
42+
return 1 if failed else 0
43+
44+
@linter_config.lint
45+
def pep8():
46+
# type: () -> int
47+
"""Standard Python style linter on 50% of files (config: tools/linter_lib/pep8.py)"""
48+
failed = check_pep8(by_lang['py'])
49+
return 1 if failed else 0
50+
51+
linter_config.do_lint()
3752

3853
if __name__ == '__main__':
3954
run()

0 commit comments

Comments
 (0)