blob: ec42d31c650932fb823ef855429e90908020a771 [file] [log] [blame]
Mike Frysingerf1ba7ad2022-09-12 05:42:57 -04001# Copyright 2022 The ChromiumOS Authors
Ryan Beltran1f2dd082022-04-25 18:42:32 +00002# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""This script emerges packages and retrieves their lints.
6
7Currently support is provided for both general and differential linting of C++
8with Clang Tidy and Rust with Cargo Clippy for all packages within platform2.
9"""
10
11import json
Ryan Beltran378934c2022-11-23 00:44:26 +000012import os
13from pathlib import Path
Ryan Beltran1f2dd082022-04-25 18:42:32 +000014import sys
Ryan Beltrance85d0f2022-08-09 21:36:39 +000015from typing import List, Text
Ryan Beltran1f2dd082022-04-25 18:42:32 +000016
17from chromite.lib import build_target_lib
18from chromite.lib import commandline
19from chromite.lib import cros_build_lib
Ryan Beltranb2175862022-04-28 19:55:57 +000020from chromite.lib import portage_util
Ryan Beltrance85d0f2022-08-09 21:36:39 +000021from chromite.lib import terminal
Ryan Beltran5514eab2022-04-28 21:40:24 +000022from chromite.lib import workon_helper
Ryan Beltran1f2dd082022-04-25 18:42:32 +000023from chromite.lib.parser import package_info
24from chromite.service import toolchain
25from chromite.utils import file_util
26
27
Alex Klein1699fab2022-09-08 08:46:06 -060028def parse_packages(
29 build_target: build_target_lib.BuildTarget, packages: List[str]
30) -> List[package_info.PackageInfo]:
31 """Parse packages and insert the category if none is given.
Ryan Beltranb2175862022-04-28 19:55:57 +000032
Alex Klein1699fab2022-09-08 08:46:06 -060033 Args:
34 build_target: build_target to find ebuild for
35 packages: user input package names to parse
Ryan Beltranb2175862022-04-28 19:55:57 +000036
Alex Klein1699fab2022-09-08 08:46:06 -060037 Returns:
38 A list of parsed PackageInfo objects
39 """
40 package_infos: List[package_info.PackageInfo] = []
41 for package in packages:
42 parsed = package_info.parse(package)
43 if not parsed.category:
44 # If a category is not specified, we can get it from the ebuild path.
45 if build_target.is_host():
46 ebuild_path = portage_util.FindEbuildForPackage(
47 package, build_target.root
48 )
49 else:
50 ebuild_path = portage_util.FindEbuildForBoardPackage(
51 package, build_target.name, build_target.root
52 )
53 ebuild_data = portage_util.EBuild(ebuild_path)
54 parsed = package_info.parse(ebuild_data.package)
55 package_infos.append(parsed)
56 return package_infos
Ryan Beltranb2175862022-04-28 19:55:57 +000057
58
Ryan Beltrance85d0f2022-08-09 21:36:39 +000059def format_lint(lint: toolchain.LinterFinding) -> Text:
Alex Klein1699fab2022-09-08 08:46:06 -060060 """Formats a lint for human readable printing.
Ryan Beltrance85d0f2022-08-09 21:36:39 +000061
Alex Klein1699fab2022-09-08 08:46:06 -060062 Example output:
63 [ClangTidy] In 'path/to/file.c' on line 36:
64 Also in 'path/to/file.c' on line 40:
65 Also in 'path/to/file.c' on lines 50-53:
66 You did something bad, don't do it.
Ryan Beltrance85d0f2022-08-09 21:36:39 +000067
Alex Klein1699fab2022-09-08 08:46:06 -060068 Args:
69 lint: A linter finding from the toolchain service.
Ryan Beltrance85d0f2022-08-09 21:36:39 +000070
Alex Klein1699fab2022-09-08 08:46:06 -060071 Returns:
72 A correctly formatted string ready to be displayed to the user.
73 """
Ryan Beltrance85d0f2022-08-09 21:36:39 +000074
Alex Klein1699fab2022-09-08 08:46:06 -060075 color = terminal.Color(True)
76 lines = []
77 linter_prefix = color.Color(
78 terminal.Color.YELLOW,
79 f"[{lint.linter}]",
80 background_color=terminal.Color.BLACK,
81 )
82 for loc in lint.locations:
83 if not lines:
84 location_prefix = f"\n{linter_prefix} In"
85 else:
86 location_prefix = " and in"
87 if loc.line_start != loc.line_end:
88 lines.append(
89 f"{location_prefix} '{loc.filepath}' "
90 f"lines {loc.line_start}-{loc.line_end}:"
91 )
92 else:
93 lines.append(
94 f"{location_prefix} '{loc.filepath}' line {loc.line_start}:"
95 )
96 message_lines = lint.message.split("\n")
97 for line in message_lines:
98 lines.append(f" {line}")
99 lines.append("")
100 return "\n".join(lines)
Ryan Beltrance85d0f2022-08-09 21:36:39 +0000101
102
Ryan Beltrana32a1a12022-09-28 06:03:45 +0000103def json_format_lint(lint: toolchain.LinterFinding) -> Text:
104 """Formats a lint in json for machine parsing.
105
106 Args:
107 lint: A linter finding from the toolchain service.
108
109 Returns:
110 A correctly formatted json string ready to be displayed to the user.
111 """
112
113 def _dictify(original):
114 """Turns namedtuple's to dictionaries recursively."""
115 # Handle namedtuples
116 if isinstance(original, tuple) and hasattr(original, "_asdict"):
117 return _dictify(original._asdict())
118 # Handle collection types
119 elif hasattr(original, "__iter__"):
120 # Handle strings
121 if isinstance(original, (str, bytes)):
122 return original
123 # Handle dictionaries
124 elif isinstance(original, dict):
125 return {k: _dictify(v) for k, v in original.items()}
126 # Handle lists, sets, etc.
127 else:
128 return [_dictify(x) for x in original]
129 # Handle everything else
130 return original
131
132 return json.dumps(_dictify(lint))
133
134
Ryan Beltran378934c2022-11-23 00:44:26 +0000135def get_all_sysroots() -> List[Text]:
136 """Gets all available sysroots for both host and boards."""
137 host_root = Path(build_target_lib.BuildTarget(None).root)
138 roots = [str(host_root)]
139 build_dir = host_root / "build"
140 for board in os.listdir(build_dir):
141 if board != "bin":
142 board_root = build_dir / board
143 if board_root.is_dir():
144 roots.append(str(board_root))
145 return roots
146
147
Ryan Beltran1f2dd082022-04-25 18:42:32 +0000148def get_arg_parser() -> commandline.ArgumentParser:
Alex Klein1699fab2022-09-08 08:46:06 -0600149 """Creates an argument parser for this script."""
150 default_board = cros_build_lib.GetDefaultBoard()
151 parser = commandline.ArgumentParser(description=__doc__)
Ryan Beltrandbd7b812022-06-08 23:36:16 +0000152
Ryan Beltran378934c2022-11-23 00:44:26 +0000153 board_group = parser.add_mutually_exclusive_group()
Alex Klein1699fab2022-09-08 08:46:06 -0600154 board_group.add_argument(
155 "-b",
156 "--board",
157 "--build-target",
158 dest="board",
159 default=default_board,
160 help="The board to emerge packages for",
161 )
162 board_group.add_argument(
163 "--host", action="store_true", help="emerge for host instead of board."
164 )
Ryan Beltran378934c2022-11-23 00:44:26 +0000165 parser.add_argument(
Alex Klein1699fab2022-09-08 08:46:06 -0600166 "--fetch-only",
167 action="store_true",
168 help="Fetch lints from previous run without reseting or calling emerge.",
169 )
Alex Klein1699fab2022-09-08 08:46:06 -0600170 parser.add_argument(
171 "--differential",
172 action="store_true",
173 help="only lint lines touched by the last commit",
174 )
175 parser.add_argument(
176 "-o",
177 "--output",
178 default=sys.stdout,
179 help="File to use instead of stdout.",
180 )
181 parser.add_argument(
182 "--json", action="store_true", help="Output lints in JSON format."
183 )
184 parser.add_argument(
185 "--no-clippy",
186 dest="clippy",
187 action="store_false",
188 help="Disable cargo clippy linter.",
189 )
190 parser.add_argument(
191 "--no-tidy",
192 dest="tidy",
193 action="store_false",
194 help="Disable clang tidy linter.",
195 )
196 parser.add_argument(
197 "--no-golint",
198 dest="golint",
199 action="store_false",
200 help="Disable golint linter.",
201 )
202 parser.add_argument(
Ryan Beltran378934c2022-11-23 00:44:26 +0000203 "--iwyu",
204 action="store_true",
205 help="Enable include-what-you-use linter.",
206 )
207 parser.add_argument(
Alex Klein1699fab2022-09-08 08:46:06 -0600208 "packages",
209 nargs="*",
210 help="package(s) to emerge and retrieve lints for",
211 )
212 return parser
Ryan Beltran1f2dd082022-04-25 18:42:32 +0000213
214
215def parse_args(argv: List[str]):
Alex Klein1699fab2022-09-08 08:46:06 -0600216 """Parses arguments in argv and returns the options."""
217 parser = get_arg_parser()
218 opts = parser.parse_args(argv)
219 opts.Freeze()
Ryan Beltrandbd7b812022-06-08 23:36:16 +0000220
Alex Klein1699fab2022-09-08 08:46:06 -0600221 # A package must be specified unless we are in fetch-only mode
222 if not (opts.fetch_only or opts.packages):
Ryan Beltran378934c2022-11-23 00:44:26 +0000223 parser.error("Emerge mode requires specified package(s).")
Alex Klein1699fab2022-09-08 08:46:06 -0600224 if opts.fetch_only and opts.packages:
225 parser.error("Cannot specify packages for fetch-only mode.")
Ryan Beltrandbd7b812022-06-08 23:36:16 +0000226
Ryan Beltran378934c2022-11-23 00:44:26 +0000227 # A board must be specified unless we are in fetch-only mode
228 if not (opts.fetch_only or opts.board or opts.host):
229 parser.error("Emerge mode requires either --board or --host.")
230
Alex Klein1699fab2022-09-08 08:46:06 -0600231 return opts
Ryan Beltran1f2dd082022-04-25 18:42:32 +0000232
233
234def main(argv: List[str]) -> None:
Alex Klein1699fab2022-09-08 08:46:06 -0600235 cros_build_lib.AssertInsideChroot()
236 opts = parse_args(argv)
Ryan Beltran1f2dd082022-04-25 18:42:32 +0000237
Alex Klein1699fab2022-09-08 08:46:06 -0600238 if opts.host:
239 # BuildTarget interprets None as host target
240 build_target = build_target_lib.BuildTarget(None)
Ryan Beltrandbd7b812022-06-08 23:36:16 +0000241 else:
Alex Klein1699fab2022-09-08 08:46:06 -0600242 build_target = build_target_lib.BuildTarget(opts.board)
243 packages = parse_packages(build_target, opts.packages)
244 package_atoms = [x.atom for x in packages]
Ryan Beltran1f2dd082022-04-25 18:42:32 +0000245
Alex Klein1699fab2022-09-08 08:46:06 -0600246 with workon_helper.WorkonScope(build_target, package_atoms):
247 build_linter = toolchain.BuildLinter(
248 packages, build_target.root, opts.differential
249 )
250 if opts.fetch_only:
Ryan Beltran378934c2022-11-23 00:44:26 +0000251 if opts.host or opts.board:
252 roots = [build_target.root]
253 else:
254 roots = get_all_sysroots()
255 lints = []
256 for root in roots:
257 build_linter.sysroot = root
258 lints.extend(
259 build_linter.fetch_findings(
260 use_clippy=opts.clippy,
261 use_tidy=opts.tidy,
262 use_golint=opts.golint,
263 use_iwyu=opts.iwyu,
264 )
265 )
Alex Klein1699fab2022-09-08 08:46:06 -0600266 else:
267 lints = build_linter.emerge_with_linting(
268 use_clippy=opts.clippy,
269 use_tidy=opts.tidy,
270 use_golint=opts.golint,
Ryan Beltran378934c2022-11-23 00:44:26 +0000271 use_iwyu=opts.iwyu,
Alex Klein1699fab2022-09-08 08:46:06 -0600272 )
Ryan Beltrance85d0f2022-08-09 21:36:39 +0000273
Alex Klein1699fab2022-09-08 08:46:06 -0600274 if opts.json:
Ryan Beltrana32a1a12022-09-28 06:03:45 +0000275 formatted_output_inner = ",\n".join(json_format_lint(l) for l in lints)
276 formatted_output = f"[{formatted_output_inner}]"
Alex Klein1699fab2022-09-08 08:46:06 -0600277 else:
Ryan Beltrana32a1a12022-09-28 06:03:45 +0000278 formatted_output = "\n".join(format_lint(l) for l in lints)
Alex Klein1699fab2022-09-08 08:46:06 -0600279
280 with file_util.Open(opts.output, "w") as output_file:
281 output_file.write(formatted_output)
282 if not opts.json:
283 output_file.write(f"\nFound {len(lints)} lints.")
284 output_file.write("\n")