blob: 9fc5db345761ebf2f3cf0b1e274ab4b748029add [file] [log] [blame]
Ryan Beltran1f2dd082022-04-25 18:42:32 +00001# Copyright 2022 The Chromium OS Authors. All rights reserved.
2# 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
12import sys
Ryan Beltrance85d0f2022-08-09 21:36:39 +000013from typing import List, Text
Ryan Beltran1f2dd082022-04-25 18:42:32 +000014
15from chromite.lib import build_target_lib
16from chromite.lib import commandline
17from chromite.lib import cros_build_lib
Ryan Beltranb2175862022-04-28 19:55:57 +000018from chromite.lib import portage_util
Ryan Beltrance85d0f2022-08-09 21:36:39 +000019from chromite.lib import terminal
Ryan Beltran5514eab2022-04-28 21:40:24 +000020from chromite.lib import workon_helper
Ryan Beltran1f2dd082022-04-25 18:42:32 +000021from chromite.lib.parser import package_info
22from chromite.service import toolchain
23from chromite.utils import file_util
24
25
Alex Klein1699fab2022-09-08 08:46:06 -060026def parse_packages(
27 build_target: build_target_lib.BuildTarget, packages: List[str]
28) -> List[package_info.PackageInfo]:
29 """Parse packages and insert the category if none is given.
Ryan Beltranb2175862022-04-28 19:55:57 +000030
Alex Klein1699fab2022-09-08 08:46:06 -060031 Args:
32 build_target: build_target to find ebuild for
33 packages: user input package names to parse
Ryan Beltranb2175862022-04-28 19:55:57 +000034
Alex Klein1699fab2022-09-08 08:46:06 -060035 Returns:
36 A list of parsed PackageInfo objects
37 """
38 package_infos: List[package_info.PackageInfo] = []
39 for package in packages:
40 parsed = package_info.parse(package)
41 if not parsed.category:
42 # If a category is not specified, we can get it from the ebuild path.
43 if build_target.is_host():
44 ebuild_path = portage_util.FindEbuildForPackage(
45 package, build_target.root
46 )
47 else:
48 ebuild_path = portage_util.FindEbuildForBoardPackage(
49 package, build_target.name, build_target.root
50 )
51 ebuild_data = portage_util.EBuild(ebuild_path)
52 parsed = package_info.parse(ebuild_data.package)
53 package_infos.append(parsed)
54 return package_infos
Ryan Beltranb2175862022-04-28 19:55:57 +000055
56
Ryan Beltrance85d0f2022-08-09 21:36:39 +000057def format_lint(lint: toolchain.LinterFinding) -> Text:
Alex Klein1699fab2022-09-08 08:46:06 -060058 """Formats a lint for human readable printing.
Ryan Beltrance85d0f2022-08-09 21:36:39 +000059
Alex Klein1699fab2022-09-08 08:46:06 -060060 Example output:
61 [ClangTidy] In 'path/to/file.c' on line 36:
62 Also in 'path/to/file.c' on line 40:
63 Also in 'path/to/file.c' on lines 50-53:
64 You did something bad, don't do it.
Ryan Beltrance85d0f2022-08-09 21:36:39 +000065
Alex Klein1699fab2022-09-08 08:46:06 -060066 Args:
67 lint: A linter finding from the toolchain service.
Ryan Beltrance85d0f2022-08-09 21:36:39 +000068
Alex Klein1699fab2022-09-08 08:46:06 -060069 Returns:
70 A correctly formatted string ready to be displayed to the user.
71 """
Ryan Beltrance85d0f2022-08-09 21:36:39 +000072
Alex Klein1699fab2022-09-08 08:46:06 -060073 color = terminal.Color(True)
74 lines = []
75 linter_prefix = color.Color(
76 terminal.Color.YELLOW,
77 f"[{lint.linter}]",
78 background_color=terminal.Color.BLACK,
79 )
80 for loc in lint.locations:
81 if not lines:
82 location_prefix = f"\n{linter_prefix} In"
83 else:
84 location_prefix = " and in"
85 if loc.line_start != loc.line_end:
86 lines.append(
87 f"{location_prefix} '{loc.filepath}' "
88 f"lines {loc.line_start}-{loc.line_end}:"
89 )
90 else:
91 lines.append(
92 f"{location_prefix} '{loc.filepath}' line {loc.line_start}:"
93 )
94 message_lines = lint.message.split("\n")
95 for line in message_lines:
96 lines.append(f" {line}")
97 lines.append("")
98 return "\n".join(lines)
Ryan Beltrance85d0f2022-08-09 21:36:39 +000099
100
Ryan Beltran1f2dd082022-04-25 18:42:32 +0000101def get_arg_parser() -> commandline.ArgumentParser:
Alex Klein1699fab2022-09-08 08:46:06 -0600102 """Creates an argument parser for this script."""
103 default_board = cros_build_lib.GetDefaultBoard()
104 parser = commandline.ArgumentParser(description=__doc__)
Ryan Beltrandbd7b812022-06-08 23:36:16 +0000105
Alex Klein1699fab2022-09-08 08:46:06 -0600106 board_group = parser.add_mutually_exclusive_group(
107 required=not default_board
108 )
109 board_group.add_argument(
110 "-b",
111 "--board",
112 "--build-target",
113 dest="board",
114 default=default_board,
115 help="The board to emerge packages for",
116 )
117 board_group.add_argument(
118 "--host", action="store_true", help="emerge for host instead of board."
119 )
120 board_group.add_argument(
121 "--fetch-only",
122 action="store_true",
123 help="Fetch lints from previous run without reseting or calling emerge.",
124 )
Ryan Beltrandbd7b812022-06-08 23:36:16 +0000125
Alex Klein1699fab2022-09-08 08:46:06 -0600126 parser.add_argument(
127 "--differential",
128 action="store_true",
129 help="only lint lines touched by the last commit",
130 )
131 parser.add_argument(
132 "-o",
133 "--output",
134 default=sys.stdout,
135 help="File to use instead of stdout.",
136 )
137 parser.add_argument(
138 "--json", action="store_true", help="Output lints in JSON format."
139 )
140 parser.add_argument(
141 "--no-clippy",
142 dest="clippy",
143 action="store_false",
144 help="Disable cargo clippy linter.",
145 )
146 parser.add_argument(
147 "--no-tidy",
148 dest="tidy",
149 action="store_false",
150 help="Disable clang tidy linter.",
151 )
152 parser.add_argument(
153 "--no-golint",
154 dest="golint",
155 action="store_false",
156 help="Disable golint linter.",
157 )
158 parser.add_argument(
159 "packages",
160 nargs="*",
161 help="package(s) to emerge and retrieve lints for",
162 )
163 return parser
Ryan Beltran1f2dd082022-04-25 18:42:32 +0000164
165
166def parse_args(argv: List[str]):
Alex Klein1699fab2022-09-08 08:46:06 -0600167 """Parses arguments in argv and returns the options."""
168 parser = get_arg_parser()
169 opts = parser.parse_args(argv)
170 opts.Freeze()
Ryan Beltrandbd7b812022-06-08 23:36:16 +0000171
Alex Klein1699fab2022-09-08 08:46:06 -0600172 # A package must be specified unless we are in fetch-only mode
173 if not (opts.fetch_only or opts.packages):
174 parser.error("Emerge requires specified package(s).")
175 if opts.fetch_only and opts.packages:
176 parser.error("Cannot specify packages for fetch-only mode.")
Ryan Beltrandbd7b812022-06-08 23:36:16 +0000177
Alex Klein1699fab2022-09-08 08:46:06 -0600178 return opts
Ryan Beltran1f2dd082022-04-25 18:42:32 +0000179
180
181def main(argv: List[str]) -> None:
Alex Klein1699fab2022-09-08 08:46:06 -0600182 cros_build_lib.AssertInsideChroot()
183 opts = parse_args(argv)
Ryan Beltran1f2dd082022-04-25 18:42:32 +0000184
Alex Klein1699fab2022-09-08 08:46:06 -0600185 if opts.host:
186 # BuildTarget interprets None as host target
187 build_target = build_target_lib.BuildTarget(None)
Ryan Beltrandbd7b812022-06-08 23:36:16 +0000188 else:
Alex Klein1699fab2022-09-08 08:46:06 -0600189 build_target = build_target_lib.BuildTarget(opts.board)
190 packages = parse_packages(build_target, opts.packages)
191 package_atoms = [x.atom for x in packages]
Ryan Beltran1f2dd082022-04-25 18:42:32 +0000192
Alex Klein1699fab2022-09-08 08:46:06 -0600193 with workon_helper.WorkonScope(build_target, package_atoms):
194 build_linter = toolchain.BuildLinter(
195 packages, build_target.root, opts.differential
196 )
197 if opts.fetch_only:
198 lints = build_linter.fetch_findings(
199 use_clippy=opts.clippy,
200 use_tidy=opts.tidy,
201 use_golint=opts.golint,
202 )
203 else:
204 lints = build_linter.emerge_with_linting(
205 use_clippy=opts.clippy,
206 use_tidy=opts.tidy,
207 use_golint=opts.golint,
208 )
Ryan Beltrance85d0f2022-08-09 21:36:39 +0000209
Alex Klein1699fab2022-09-08 08:46:06 -0600210 if opts.json:
211 formatted_output = json.dumps([lint._asdict() for lint in lints])
212 else:
213 formatted_output = "\n".join(format_lint(lint) for lint in lints)
214
215 with file_util.Open(opts.output, "w") as output_file:
216 output_file.write(formatted_output)
217 if not opts.json:
218 output_file.write(f"\nFound {len(lints)} lints.")
219 output_file.write("\n")