1use std::path::PathBuf;
3
4use clap::builder::{ArgPredicate, BoolishValueParser, FalseyValueParser};
6use clap::{value_parser, Arg, ArgAction, ArgGroup, ArgMatches, Command};
7
8mod structs;
9pub use structs::{ClangParams, Cli, FeedbackInput, LinesChangedOnly, ThreadComments};
10
11pub fn get_arg_parser() -> Command {
13 Command::new("cpp-linter")
14 .subcommand(
15 Command::new("version")
16 .about("Display the cpp-linter version and exit.")
17 )
18 .arg(
19 Arg::new("verbosity")
20 .long("verbosity")
21 .short('v')
22 .default_value("info")
23 .value_parser(["debug", "info"])
24 .help(
25 "This controls the action's verbosity in the workflow's logs.
26This option does not affect the verbosity of resulting
27thread comments or file annotations.\n\n",
28 ),
29 )
30 .arg(
31 Arg::new("database")
32 .long("database")
33 .short('p')
34 .value_parser(value_parser!(PathBuf))
35 .help_heading("clang-tidy options")
36 .help(
37 "The path that is used to read a compile command database.
38For example, it can be a CMake build directory in which a file named
39compile_commands.json exists (set `CMAKE_EXPORT_COMPILE_COMMANDS` to `ON`).
40When no build path is specified, a search for compile_commands.json will be
41attempted through all parent paths of the first input file. See [LLVM docs about
42setup tooling](https://clang.llvm.org/docs/HowToSetupToolingForLLVM.html)
43for an example of setting up Clang Tooling on a source tree.",
44 )
45 )
46 .arg(
47 Arg::new("style")
48 .short('s')
49 .long("style")
50 .default_value("llvm")
51 .help_heading("clang-format options")
52 .help(
53 "The style rules to use.
54
55- Set this to `file` to have clang-format use the closest relative
56 .clang-format file.
57- Set this to a blank string (`''`) to disable using clang-format
58 entirely.
59
60> [!NOTE]
61> If this is not a blank string, then it is also passed to clang-tidy
62> (if [`--tidy_checks`](#-c-tidy-checks) is not `-*`).
63> This is done to ensure suggestions from both clang-tidy and
64> clang-format are consistent.\n\n",
65 ),
66 )
67 .arg(
68 Arg::new("tidy-checks")
69 .short('c')
70 .long("tidy-checks")
71 .default_value(
72 "boost-*,bugprone-*,performance-*,readability-*,portability-*,modernize-*,clang-analyzer-*,cppcoreguidelines-*",
73 )
74 .help_heading("clang-tidy options")
75 .help(
76 "A comma-separated list of globs with optional `-` prefix.
77Globs are processed in order of appearance in the list.
78Globs without `-` prefix add checks with matching names to the set,
79globs with the `-` prefix remove checks with matching names from the set of
80enabled checks. This option's value is appended to the value of the 'Checks'
81option in a .clang-tidy file (if any).
82
83- It is possible to disable clang-tidy entirely by setting this option to
84 `'-*'`.
85- It is also possible to rely solely on a .clang-tidy config file by
86 specifying this option as a blank string (`''`).
87
88See also clang-tidy docs for more info.\n\n",
89 ),
90 )
91 .arg(
92 Arg::new("version")
93 .short('V')
94 .long("version")
95 .default_missing_value("NO-VERSION")
96 .num_args(0..=1)
97 .require_equals(true)
98 .default_value("")
99 .help(
100 "The desired version of the clang tools to use. Accepted options are
101strings which can be 8, 9, 10, 11, 12, 13, 14, 15, 16, 17.
102
103- Set this option to a blank string (`''`) to use the
104 platform's default installed version.
105- This value can also be a path to where the clang tools are
106 installed (if using a custom install location). All paths specified
107 here are converted to absolute.\n\n",
108 ),
109 )
110 .arg(
111 Arg::new("extensions")
112 .short('e')
113 .long("extensions")
114 .value_delimiter(',')
115 .default_value("c,h,C,H,cpp,hpp,cc,hh,c++,h++,cxx,hxx")
116 .help_heading("Source options")
117 .help("A comma-separated list of file extensions to analyze.\n"),
118 )
119 .arg(
120 Arg::new("repo-root")
121 .short('r')
122 .long("repo-root")
123 .default_value(".")
124 .help_heading("Source options")
125 .help(
126 "The relative path to the repository root directory. This path is
127relative to the runner's `GITHUB_WORKSPACE` environment variable (or
128the current working directory if not using a CI runner).\n\n",
129 ),
130 )
131 .arg(
132 Arg::new("ignore")
133 .short('i')
134 .long("ignore")
135 .value_delimiter('|')
136 .default_value(".github|target")
137 .help_heading("Source options")
138 .help(
139 "Set this option with path(s) to ignore (or not ignore).
140
141- In the case of multiple paths, you can use `|` to separate each path.
142- There is no need to use `./` for each entry; a blank string (`''`)
143 represents the repo-root path.
144- This can also have files, but the file's path (relative to
145 the [`--repo-root`](#-r-repo-root)) has to be specified with the filename.
146- Submodules are automatically ignored. Hidden directories (beginning
147 with a `.`) are also ignored automatically.
148- Prefix a path with `!` to explicitly not ignore it. This can be
149 applied to a submodule's path (if desired) but not hidden directories.
150- Glob patterns are supported here. Path separators in glob patterns should
151 use `/` because `\\` represents an escaped literal.\n\n",
152 ),
153 )
154 .arg(
155 Arg::new("ignore-tidy")
156 .short('D')
157 .long("ignore-tidy")
158 .value_delimiter('|')
159 .help_heading("clang-tidy options")
160 .help(
161 "Similar to [`--ignore`](#-i-ignore) but applied
162exclusively to files analyzed by clang-tidy.\n\n",
163 ),
164 )
165 .arg(
166 Arg::new("ignore-format")
167 .short('M')
168 .long("ignore-format")
169 .value_delimiter('|')
170 .help_heading("clang-format options")
171 .help(
172 "Similar to [`--ignore`](#-i-ignore) but applied
173exclusively to files analyzed by clang-format.\n\n",
174 ),
175 )
176 .arg(
177 Arg::new("lines-changed-only")
178 .short('l')
179 .long("lines-changed-only")
180 .value_parser(["true", "on", "1", "false", "off", "0", "diff"])
181 .default_value("true")
182 .help_heading("Source options")
183 .help(
184 "This controls what part of the files are analyzed.
185The following values are accepted:
186
187- `false`: All lines in a file are analyzed.
188- `true`: Only lines in the diff that contain additions are analyzed.
189- `diff`: All lines in the diff are analyzed (including unchanged
190 lines but not subtractions).\n\n",
191 ),
192 )
193 .arg(
194 Arg::new("files-changed-only")
195 .short('f')
196 .long("files-changed-only")
197 .default_value_if("lines-changed-only", ArgPredicate::Equals("true".into()), "true")
198 .default_value("false")
199 .value_parser(FalseyValueParser::new())
200 .help_heading("Source options")
201 .help(
202 "Set this option to false to analyze any source files in the repo.
203This is automatically enabled if
204[`--lines-changed-only`](#-l-lines-changed-only) is enabled.
205
206> [!NOTE]
207> The `GITHUB_TOKEN` should be supplied when running on a
208> private repository with this option enabled, otherwise the runner
209> does not not have the privilege to list the changed files for an event.
210>
211> See [Authenticating with the `GITHUB_TOKEN`](
212> https://docs.github.com/en/actions/reference/authentication-in-a-workflow).\n\n",
213 ),
214 )
215 .arg(
216 Arg::new("extra-arg")
217 .long("extra-arg")
218 .short('x')
219 .action(ArgAction::Append)
220 .help_heading("clang-tidy options")
221 .help(
222 r#"A string of extra arguments passed to clang-tidy for use as
223compiler arguments. This can be specified more than once for each
224additional argument. Recommend using quotes around the value and
225avoid using spaces between name and value (use `=` instead):
226
227```shell
228cpp-linter --extra-arg="-std=c++17" --extra-arg="-Wall"
229```"#,
230 ),
231 )
232 .arg(
233 Arg::new("thread-comments")
234 .long("thread-comments")
235 .short('g')
236 .value_parser(["true", "on", "1", "false", "off", "0", "update"])
237 .default_value("false")
238 .help_heading("feedback options")
239 .help(
240 "Set this option to true to enable the use of thread comments as feedback.
241Set this to `update` to update an existing comment if one exists;
242the value 'true' will always delete an old comment and post a new one if necessary.
243
244> [!NOTE]
245> To use thread comments, the `GITHUB_TOKEN` (provided by
246> Github to each repository) must be declared as an environment
247> variable.
248>
249> See [Authenticating with the `GITHUB_TOKEN`](
250> https://docs.github.com/en/actions/reference/authentication-in-a-workflow).\n\n",
251 ),
252 )
253 .arg(
254 Arg::new("no-lgtm")
255 .long("no-lgtm")
256 .short('t')
257 .value_parser(FalseyValueParser::new())
258 .default_value("true")
259 .help_heading("feedback options")
260 .help(
261 "Set this option to true or false to enable or disable the use of a
262thread comment that basically says 'Looks Good To Me' (when all checks pass).
263
264> [!IMPORTANT]
265> The [`--thread-comments`](#-g-thread-comments)
266> option also notes further implications.\n\n",
267 ),
268 )
269 .arg(
270 Arg::new("step-summary")
271 .long("step-summary")
272 .short('w')
273 .value_parser(FalseyValueParser::new())
274 .default_value("false")
275 .help_heading("feedback options")
276 .help(
277 "Set this option to true or false to enable or disable the use of
278a workflow step summary when the run has concluded.\n\n",
279 ),
280 )
281 .arg(
282 Arg::new("file-annotations")
283 .long("file-annotations")
284 .short('a')
285 .value_parser(FalseyValueParser::new())
286 .default_value("true")
287 .help_heading("feedback options")
288 .help(
289 "Set this option to false to disable the use of
290file annotations as feedback.\n\n",
291 ),
292 )
293 .arg(
294 Arg::new("tidy-review")
295 .long("tidy-review")
296 .short('d')
297 .value_parser(BoolishValueParser::new())
298 .default_value("false")
299 .help_heading("feedback options")
300 .help(
301 "Set to `true` to enable Pull Request reviews from clang-tidy.\n\n",
302 ),
303 )
304 .arg(
305 Arg::new("format-review")
306 .long("format-review")
307 .short('m')
308 .value_parser(BoolishValueParser::new())
309 .default_value("false")
310 .help_heading("feedback options")
311 .help(
312 "Set to `true` to enable Pull Request reviews from clang-format.\n\n",
313 ),
314 )
315 .arg(
316 Arg::new("passive-reviews")
317 .long("passive-reviews")
318 .short('R')
319 .value_parser(BoolishValueParser::new())
320 .default_value("false")
321 .help_heading("feedback options")
322 .help(
323 "Set to `true` to prevent Pull Request reviews from
324approving or requesting changes.\n\n",
325 ),
326 )
327 .arg(
328 Arg::new("files")
329 .action(ArgAction::Append)
330 .help(
331 "An explicit path to a file.
332This can be specified zero or more times, resulting in a list of files.
333The list of files is appended to the internal list of 'not ignored' files.
334Further filtering can still be applied (see [Source options](#source-options)).",
335 )
336 )
337 .groups([
338 ArgGroup::new("Clang-tidy options")
339 .args(["tidy-checks", "database", "extra-arg", "ignore-tidy"]).multiple(true),
340 ArgGroup::new("Clang-format options").args(["style", "ignore-format"]).multiple(true),
341 ArgGroup::new("General options").args(["verbosity", "version"]).multiple(true),
342 ArgGroup::new("Source options").args(["extensions", "repo-root", "ignore", "lines-changed-only", "files-changed-only"]).multiple(true),
343 ArgGroup::new("Feedback options").args([
344 "thread-comments", "no-lgtm", "step-summary", "file-annotations", "tidy-review", "format-review", "passive-reviews"
345 ]).multiple(true),
346 ])
347 .next_line_help(true)
348}
349
350pub fn convert_extra_arg_val(args: &ArgMatches) -> Vec<String> {
370 let mut val = args.get_many::<String>("extra-arg").unwrap_or_default();
371 if val.len() == 1 {
372 return val
374 .next()
375 .unwrap()
376 .trim_matches('\'')
377 .trim_matches('"')
378 .split(' ')
379 .map(|i| i.to_string())
380 .collect();
381 } else {
382 val.map(|i| i.to_string()).collect()
384 }
385}
386
387#[cfg(test)]
388mod test {
389 use clap::ArgMatches;
390
391 use super::{convert_extra_arg_val, get_arg_parser};
392
393 fn parser_args(input: Vec<&str>) -> ArgMatches {
394 let arg_parser = get_arg_parser();
395 arg_parser.get_matches_from(input)
396 }
397
398 #[test]
399 fn extra_arg_0() {
400 let args = parser_args(vec!["cpp-linter"]);
401 let extras = convert_extra_arg_val(&args);
402 assert!(extras.is_empty());
403 }
404
405 #[test]
406 fn extra_arg_1() {
407 let args = parser_args(vec!["cpp-linter", "--extra-arg='-std=c++17 -Wall'"]);
408 let extra_args = convert_extra_arg_val(&args);
409 assert_eq!(extra_args.len(), 2);
410 assert_eq!(extra_args, ["-std=c++17", "-Wall"])
411 }
412
413 #[test]
414 fn extra_arg_2() {
415 let args = parser_args(vec![
416 "cpp-linter",
417 "--extra-arg=-std=c++17",
418 "--extra-arg=-Wall",
419 ]);
420 let extra_args = convert_extra_arg_val(&args);
421 assert_eq!(extra_args.len(), 2);
422 assert_eq!(extra_args, ["-std=c++17", "-Wall"])
423 }
424}