blob: 2f5c38732ff51e604a88b16fb0e573ba0368132a [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:
Alex Klein68b270c2023-04-14 14:42:50 -060034 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:
Alex Klein68b270c2023-04-14 14:42:50 -060038 A list of parsed PackageInfo objects
Alex Klein1699fab2022-09-08 08:46:06 -060039 """
40 package_infos: List[package_info.PackageInfo] = []
41 for package in packages:
42 parsed = package_info.parse(package)
43 if not parsed.category:
Alex Klein68b270c2023-04-14 14:42:50 -060044 # If a category is not specified, get it from the ebuild path.
Alex Klein1699fab2022-09-08 08:46:06 -060045 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 Klein68b270c2023-04-14 14:42:50 -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:
Alex Klein68b270c2023-04-14 14:42:50 -060069 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:
Alex Klein68b270c2023-04-14 14:42:50 -060072 A correctly formatted string ready to be displayed to the user.
Alex Klein1699fab2022-09-08 08:46:06 -060073 """
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",
Alex Klein68b270c2023-04-14 14:42:50 -0600168 help="Fetch lints from previous run without resetting or calling "
169 "emerge.",
Alex Klein1699fab2022-09-08 08:46:06 -0600170 )
Alex Klein1699fab2022-09-08 08:46:06 -0600171 parser.add_argument(
172 "--differential",
173 action="store_true",
174 help="only lint lines touched by the last commit",
175 )
176 parser.add_argument(
177 "-o",
178 "--output",
179 default=sys.stdout,
180 help="File to use instead of stdout.",
181 )
182 parser.add_argument(
183 "--json", action="store_true", help="Output lints in JSON format."
184 )
185 parser.add_argument(
186 "--no-clippy",
187 dest="clippy",
188 action="store_false",
189 help="Disable cargo clippy linter.",
190 )
191 parser.add_argument(
192 "--no-tidy",
193 dest="tidy",
194 action="store_false",
195 help="Disable clang tidy linter.",
196 )
197 parser.add_argument(
198 "--no-golint",
199 dest="golint",
200 action="store_false",
201 help="Disable golint linter.",
202 )
203 parser.add_argument(
Ryan Beltran378934c2022-11-23 00:44:26 +0000204 "--iwyu",
205 action="store_true",
206 help="Enable include-what-you-use linter.",
207 )
208 parser.add_argument(
Alex Klein1699fab2022-09-08 08:46:06 -0600209 "packages",
210 nargs="*",
211 help="package(s) to emerge and retrieve lints for",
212 )
213 return parser
Ryan Beltran1f2dd082022-04-25 18:42:32 +0000214
215
216def parse_args(argv: List[str]):
Alex Klein1699fab2022-09-08 08:46:06 -0600217 """Parses arguments in argv and returns the options."""
218 parser = get_arg_parser()
219 opts = parser.parse_args(argv)
220 opts.Freeze()
Ryan Beltrandbd7b812022-06-08 23:36:16 +0000221
Alex Klein1699fab2022-09-08 08:46:06 -0600222 # A package must be specified unless we are in fetch-only mode
223 if not (opts.fetch_only or opts.packages):
Ryan Beltran378934c2022-11-23 00:44:26 +0000224 parser.error("Emerge mode requires specified package(s).")
Alex Klein1699fab2022-09-08 08:46:06 -0600225 if opts.fetch_only and opts.packages:
226 parser.error("Cannot specify packages for fetch-only mode.")
Ryan Beltrandbd7b812022-06-08 23:36:16 +0000227
Ryan Beltran378934c2022-11-23 00:44:26 +0000228 # A board must be specified unless we are in fetch-only mode
229 if not (opts.fetch_only or opts.board or opts.host):
230 parser.error("Emerge mode requires either --board or --host.")
231
Alex Klein1699fab2022-09-08 08:46:06 -0600232 return opts
Ryan Beltran1f2dd082022-04-25 18:42:32 +0000233
234
235def main(argv: List[str]) -> None:
Alex Klein1699fab2022-09-08 08:46:06 -0600236 cros_build_lib.AssertInsideChroot()
237 opts = parse_args(argv)
Ryan Beltran1f2dd082022-04-25 18:42:32 +0000238
Alex Klein1699fab2022-09-08 08:46:06 -0600239 if opts.host:
240 # BuildTarget interprets None as host target
241 build_target = build_target_lib.BuildTarget(None)
Ryan Beltrandbd7b812022-06-08 23:36:16 +0000242 else:
Alex Klein1699fab2022-09-08 08:46:06 -0600243 build_target = build_target_lib.BuildTarget(opts.board)
244 packages = parse_packages(build_target, opts.packages)
245 package_atoms = [x.atom for x in packages]
Ryan Beltran1f2dd082022-04-25 18:42:32 +0000246
Alex Klein1699fab2022-09-08 08:46:06 -0600247 with workon_helper.WorkonScope(build_target, package_atoms):
248 build_linter = toolchain.BuildLinter(
249 packages, build_target.root, opts.differential
250 )
251 if opts.fetch_only:
Ryan Beltran378934c2022-11-23 00:44:26 +0000252 if opts.host or opts.board:
253 roots = [build_target.root]
254 else:
255 roots = get_all_sysroots()
256 lints = []
257 for root in roots:
258 build_linter.sysroot = root
259 lints.extend(
260 build_linter.fetch_findings(
261 use_clippy=opts.clippy,
262 use_tidy=opts.tidy,
263 use_golint=opts.golint,
264 use_iwyu=opts.iwyu,
265 )
266 )
Alex Klein1699fab2022-09-08 08:46:06 -0600267 else:
268 lints = build_linter.emerge_with_linting(
269 use_clippy=opts.clippy,
270 use_tidy=opts.tidy,
271 use_golint=opts.golint,
Ryan Beltran378934c2022-11-23 00:44:26 +0000272 use_iwyu=opts.iwyu,
Alex Klein1699fab2022-09-08 08:46:06 -0600273 )
Ryan Beltrance85d0f2022-08-09 21:36:39 +0000274
Alex Klein1699fab2022-09-08 08:46:06 -0600275 if opts.json:
Ryan Beltrana32a1a12022-09-28 06:03:45 +0000276 formatted_output_inner = ",\n".join(json_format_lint(l) for l in lints)
277 formatted_output = f"[{formatted_output_inner}]"
Alex Klein1699fab2022-09-08 08:46:06 -0600278 else:
Ryan Beltrana32a1a12022-09-28 06:03:45 +0000279 formatted_output = "\n".join(format_lint(l) for l in lints)
Alex Klein1699fab2022-09-08 08:46:06 -0600280
281 with file_util.Open(opts.output, "w") as output_file:
282 output_file.write(formatted_output)
283 if not opts.json:
284 output_file.write(f"\nFound {len(lints)} lints.")
285 output_file.write("\n")