-
Notifications
You must be signed in to change notification settings - Fork 33
/
lint
executable file
·360 lines (295 loc) · 9.79 KB
/
lint
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
#!/usr/bin/env python3
# Copyright 2019 The ChromiumOS Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Lint our source files."""
import fnmatch
import logging
import os
from pathlib import Path
import sys
from typing import List
import libdot
# All checks except strictMissingRequire.
DEFAULT_CLOSURE_ARGS = ("--jscomp_error=*", "--jscomp_off=strictMissingRequire")
# Options passed when invoking eslint.
ESLINT_ARGS = (
"--cache",
"--cache-location",
libdot.LIBAPPS_DIR / ".eslintcache",
)
def kokoro_comments_path(path, tool):
"""Expand % markers that might exist in |path|."""
if not path:
return None
else:
return path.replace("%(tool)", tool)
def is_generated_path(path):
"""Return True if |path| is generated.
Useful for filtering out comments for files not in the tree.
"""
return fnmatch.fnmatch(path, "*.concat.js") or fnmatch.fnmatch(
path, "*.rollup.js"
)
def get_known_files(basedir: Path) -> List[Path]:
"""Return list of files committed to the tree."""
# -z appends \0 to each path, it doesn't delimit them. So strip off the
# trailing \0 to avoid a spurious '' entry at the end.
all_files = (
libdot.run(
["git", "ls-tree", "--name-only", "-r", "-z", "HEAD"],
cwd=basedir,
capture_output=True,
encoding="utf-8",
)
.stdout[:-1]
.split("\0")
)
return [basedir / x for x in all_files if (basedir / x).exists()]
def get_known_sources(basedir: Path) -> List[Path]:
"""Get list of committed files that we could possibly lint."""
return (
x
for x in get_known_files(basedir)
if x.suffix
not in {
".bz2",
".gz",
".log",
".jpg",
".ogg",
".patch",
".png",
".webp",
".xz",
}
)
def lint_whitespace_data(path: Path, data: str) -> bool:
"""Basic whitespace checks on text files."""
ret = True
if "\r" in data:
ret = False
logging.error(r"%s: \r not allowed in text files", path)
if data.startswith("\n"):
ret = False
logging.error("%s: No leading blank lines allowed", path)
if not data.endswith("\n"):
ret = False
logging.error("%s: Files must end with a newline", path)
return ret
def lint_whitespace_files(paths: List[Path]) -> bool:
"""Basic whitespace checks on text files."""
ret = True
for path in paths:
with open(path, mode="r", encoding="utf-8") as fp:
data = fp.read()
ret &= lint_whitespace_data(path, data)
return ret
def lint_html_files(paths: List[Path]) -> bool:
"""Basic lint checks on HTML files."""
logging.info("Linting HTML files %s", libdot.cmdstr(paths))
ret = True
META_CHARSET_TAG = "<meta charset='utf-8'/>"
for path in paths:
with open(path, mode="r", encoding="utf-8") as fp:
data = fp.read()
if META_CHARSET_TAG not in data:
ret = False
logging.error("%s: <head>: missing %s tag", path, META_CHARSET_TAG)
ret &= lint_whitespace_data(path, data)
return ret
def lint_text_files(paths: List[Path]) -> bool:
"""Basic lint checks on HTML files."""
logging.info("Linting text files %s", libdot.cmdstr(paths))
return lint_whitespace_files(paths)
def _get_default_paths(basedir: Path) -> List[Path]:
"""Get list of paths to lint by default."""
most_files = sorted(
x for x in get_known_sources(basedir) if x.suffix not in {".js"}
)
# All files in js/*.js excluding generated files.
# Use relpath for nicer default output.
# Sort to ensure lib.js comes before lib_array.js, etc.
js_files = sorted(
list((libdot.DIR / "html").glob("*.html"))
+ [libdot.DIR / "index.js"]
+ list((libdot.DIR / "js").glob("*.js"))
)
return [os.path.relpath(x) for x in most_files + js_files]
def get_parser():
"""Get a command line parser."""
parser = libdot.ArgumentParser(description=__doc__)
parser.add_argument(
"--version", action="store_true", help="Show linter versions."
)
parser.add_argument(
"--fix",
action="store_true",
help="Run linters with --fix setting if possible.",
)
parser.add_argument(
"--gerrit-comments-file",
help="Save errors for posting files to Gerrit.",
)
parser.add_argument(
"--skip-mkdeps",
dest="run_mkdeps",
action="store_false",
default=True,
help="Skip (re)building of dependencies.",
)
group = parser.add_argument_group(
"File selection/filtering",
description="All files are linted by default",
)
group.add_argument("--cpp", action="store_true", help="Lint C/C++ files.")
group.add_argument(
"--js", action="store_true", help="Lint JavaScript files."
)
group.add_argument("--json", action="store_true", help="Lint JSON files.")
group.add_argument("--md", action="store_true", help="Lint Markdown files.")
group.add_argument("--py", action="store_true", help="Lint Python files.")
group.add_argument("--txt", action="store_true", help="Lint text files.")
parser.add_argument("paths", nargs="*", help="Paths to lint.")
return parser
def main(
argv,
get_default_paths=get_known_sources,
basedir=None,
mkdeps=None,
closure_args=DEFAULT_CLOSURE_ARGS,
):
"""The common main func for all linters.
Args:
argv: The command line to process.
paths: The default set of files to lint. If the user doesn't specify
any, we'll use these instead.
basedir: The base source tree to search for default set of files to lint.
mkdeps: Callback to build dependencies after we've initialized.
closure_args: Extra arguments to pass to closure-compiler.
"""
parser = get_parser()
opts = parser.parse_args(argv)
libdot.node_and_npm_setup()
if opts.version:
for func in (
libdot.eslint.run,
libdot.closure_compiler.run,
libdot.black.run,
libdot.pylint.run,
):
func(["--version"])
return 0
if not opts.paths:
opts.paths = [str(x) for x in get_default_paths(basedir)]
if not opts.paths:
print("No files to lint.")
return 0
if mkdeps:
if opts.run_mkdeps:
mkdeps(opts)
else:
logging.info("Skipping building dependencies due to --skip-mkdeps")
lint_groups = {"cpp", "js", "json", "md", "py", "txt"}
lint_all = all(not getattr(opts, x) for x in lint_groups)
for group in lint_groups:
setattr(opts, group, lint_all or getattr(opts, group))
tolint_paths = set(opts.paths)
kwargs = {
"fix": opts.fix,
"gerrit_comments_file": opts.gerrit_comments_file,
}
checks = []
html_files = [
x for x in opts.paths if x.endswith(".html") or x.endswith(".html.in")
]
js_files = [x for x in opts.paths if x.endswith(".js")]
tolint_paths -= set(js_files)
if js_files and opts.js:
js_kwargs = {"paths": js_files, **kwargs}
html_js_kwargs = {"paths": html_files + js_files, **kwargs}
checks += [
libdot.eslint.perform(argv=ESLINT_ARGS, **html_js_kwargs),
libdot.closure_compiler.perform(argv=closure_args, **js_kwargs),
]
py_files = libdot.pylint.filter_known_files(opts.paths)
tolint_paths -= set(py_files)
if py_files and opts.py:
py_kwargs = {"paths": py_files, **kwargs}
checks += [
libdot.black.perform(**py_kwargs),
libdot.pylint.perform(**py_kwargs),
]
cpp_files = libdot.cpplint.filter_known_files(opts.paths)
tolint_paths -= set(cpp_files)
if cpp_files and opts.cpp:
cpp_kwargs = {"paths": cpp_files, **kwargs}
checks += [libdot.cpplint.perform(**cpp_kwargs)]
tolint_paths -= set(html_files)
if html_files and opts.txt:
checks += [lint_html_files(html_files)]
md_files = libdot.mdlint.filter_known_files(opts.paths)
tolint_paths -= set(md_files)
if md_files and opts.md:
md_kwargs = {"paths": md_files, **kwargs}
checks += [
lint_whitespace_files(md_files),
libdot.mdlint.perform(**md_kwargs),
]
json_files = libdot.jsonlint.filter_known_files(opts.paths)
tolint_paths -= set(json_files)
if json_files and opts.json:
json_kwargs = {"paths": json_files, **kwargs}
checks += [
lint_whitespace_files(json_files),
libdot.jsonlint.perform(**json_kwargs),
]
TEXT_FILENAMES = {
".clang-format",
".eslintrc.js",
".gitignore",
".markdownlintrc",
".npmrc",
".pylintrc",
"DIR_METADATA",
"Dockerfile",
"LICENSE",
"Makefile",
"METADATA",
"OWNERS",
}
TEXT_EXTENSIONS = {
".cfg",
".concat",
".css",
".el",
".sh",
".svg",
".toml",
".txt",
".vim",
".xml",
".yaml",
}
text_files = [
x
for x in opts.paths
if (
os.path.basename(x) in TEXT_FILENAMES
or os.path.splitext(x)[1] in TEXT_EXTENSIONS
)
]
tolint_paths -= set(text_files)
if text_files and opts.txt:
checks += [lint_text_files(text_files)]
if tolint_paths:
logging.warning("Linting skipped:\n%s", " ".join(sorted(tolint_paths)))
return 0 if all(checks) else 1
if __name__ == "__main__":
sys.exit(
main(
sys.argv[1:],
basedir=libdot.DIR,
get_default_paths=_get_default_paths,
)
)