Source src/cli.rs
1//! Parse tool arguments without reinterpreting forwarded rustc arguments.2use clap::{Parser, error::ErrorKind};3use std::{4 ffi::OsString,5 path::{Path, PathBuf},6};78#[derive(Debug, Parser)]9#[command(name = "cargo clippy-html", version, about)]10pub struct RunOptions {11 #[arg(long, value_name = "DIR")]12 pub output: Option<PathBuf>,13 /// Write an optional machine-readable report navigation index.14 #[arg(long, value_name = "FILE")]15 pub metadata: Option<PathBuf>,16 #[arg(long)]17 pub open: bool,18 /// Use bundled category data without fetching it (Cargo flags go after --).19 #[arg(long)]20 pub offline: bool,21 #[arg(last = true, value_name = "CLIPPY_ARGS")]22 pub clippy_args: Vec<OsString>,23}2425pub fn parse_args(mut args: Vec<OsString>) -> Result<RunOptions, clap::Error> {26 if args.get(1).is_some_and(|a| a == "clippy-html") {27 args.remove(1);28 }29 let opts = RunOptions::try_parse_from(args)?;30 for arg in opts.clippy_args.iter().take_while(|a| *a != "--") {31 let text = arg.to_string_lossy();32 if text == "--fix"33 || text.starts_with("--fix=")34 || text == "--message-format"35 || text.starts_with("--message-format=")36 {37 return Err(clap::Error::raw(38 ErrorKind::ArgumentConflict,39 "--fix and --message-format cannot be forwarded to cargo clippy-html\n",40 ));41 }42 }43 Ok(opts)44}4546pub struct CargoContext {47 pub cwd: PathBuf,48 pub cargo_exe: OsString,49 pub metadata_args: Vec<OsString>,50 pub target_dir_override: Option<PathBuf>,51}5253pub fn cargo_context(54 opts: &RunOptions,55 cwd: &Path,56 cargo_exe: OsString,57) -> Result<CargoContext, String> {58 let mut context = CargoContext {59 cwd: cwd.to_owned(),60 cargo_exe,61 metadata_args: vec![],62 target_dir_override: None,63 };64 let args: Vec<_> = opts.clippy_args.iter().take_while(|a| *a != "--").collect();65 let mut i = 0;66 while i < args.len() {67 let text = args[i].to_string_lossy();68 let (name, inline) = text69 .split_once('=')70 .map_or((text.as_ref(), None), |(k, v)| (k, Some(v)));71 let has_value = matches!(72 name,73 "--manifest-path" | "--config" | "--features" | "-F" | "--target-dir"74 );75 if has_value {76 let value = if let Some(v) = inline {77 OsString::from(v)78 } else {79 i += 1;80 args.get(i) warning: clippy::implicit_clone81 .ok_or_else(|| format!("{name} requires a value"))? warning: clippy::implicit_clone82 .to_os_string() warning: clippy::implicit_clone83 };84 if name == "--target-dir" {85 context.target_dir_override = Some(cwd.join(value));86 } else {87 context.metadata_args.extend([OsString::from(name), value]);88 }89 } else if matches!(90 name,91 "--locked" | "--offline" | "--frozen" | "--all-features" | "--no-default-features"92 ) {93 context.metadata_args.push(args[i].to_os_string()); warning: clippy::implicit_clone94 }95 i += 1;96 }97 Ok(context)98}99100#[cfg(test)]101mod tests {102 use super::*;103 #[test]104 fn tool_and_cargo_offline_flags_are_independent() {105 for command in [106 vec!["cargo-clippy-html"],107 vec!["cargo-clippy-html", "--offline"],108 vec!["cargo-clippy-html", "--", "--offline"],109 vec!["cargo-clippy-html", "--offline", "--", "--offline"],110 ] {111 let opts = parse_args(args(&command)).unwrap();112 assert_eq!(opts.offline, command.get(1) == Some(&"--offline"));113 let forwarded = command.contains(&"--");114 assert_eq!(115 opts.clippy_args,116 if forwarded {117 vec![OsString::from("--offline")]118 } else {119 vec![]120 }121 );122 let context = cargo_context(&opts, Path::new("/demo"), "cargo".into()).unwrap();123 assert_eq!(124 context.metadata_args.contains(&OsString::from("--offline")),125 forwarded126 );127 }128 }129 fn args(s: &[&str]) -> Vec<OsString> {130 s.iter().map(OsString::from).collect()131 }132 #[test]133 fn cargo_invocation_preserves_second_separator() {134 let result = parse_args(args(&[135 "cargo-clippy-html",136 "clippy-html",137 "--output",138 "report",139 "--",140 "--all-targets",141 "--",142 "-W",143 "clippy::pedantic",144 ]))145 .unwrap();146 assert_eq!(result.output, Some(PathBuf::from("report")));147 assert_eq!(148 result.clippy_args,149 args(&["--all-targets", "--", "-W", "clippy::pedantic"])150 );151 }152 #[test]153 fn rejects_mutating_and_message_format_args() {154 for forwarded in [155 &["--fix"][..],156 &["--message-format=json"],157 &["--message-format", "short"],158 ] {159 let mut input = args(&["tool", "--"]);160 input.extend(args(forwarded));161 assert!(parse_args(input).is_err());162 }163 assert!(parse_args(args(&["tool", "--", "--", "--message-format=json"])).is_ok());164 }165 #[test]166 fn metadata_is_opt_in_and_requires_a_path() {167 assert!(parse_args(args(&["tool"])).unwrap().metadata.is_none());168 assert!(parse_args(args(&["tool", "--metadata"])).is_err());169 let opts = parse_args(args(&[170 "tool",171 "--metadata",172 "보고서 폴더/index.json",173 "--",174 "--all-targets",175 ]))176 .unwrap();177 assert_eq!(opts.metadata, Some(PathBuf::from("보고서 폴더/index.json")));178 assert_eq!(opts.clippy_args, args(&["--all-targets"]));179 assert_eq!(180 parse_args(args(&["tool", "--metadata=x.json"]))181 .unwrap()182 .metadata,183 Some(PathBuf::from("x.json"))184 );185 }186 #[test]187 fn unicode_os_paths_survive() {188 let r = parse_args(args(&[189 "tool",190 "--output",191 "보고서 폴더",192 "--",193 "--manifest-path=한글/Cargo.toml",194 ]))195 .unwrap();196 assert_eq!(r.output, Some(PathBuf::from("보고서 폴더")));197 assert_eq!(r.clippy_args, args(&["--manifest-path=한글/Cargo.toml"]));198 }199 #[test]200 fn help_needs_no_project() {201 assert_eq!(202 parse_args(args(&["tool", "--help"]))203 .unwrap_err()204 .exit_code(),205 0206 );207 assert_eq!(208 parse_args(args(&["tool", "--version"]))209 .unwrap_err()210 .exit_code(),211 0212 );213 }214 #[test]215 fn context_respects_equals_and_separate_paths() {216 let opts = parse_args(args(&[217 "tool",218 "--",219 "--manifest-path=한글/Cargo.toml",220 "--target-dir",221 "cache",222 "--offline",223 "--",224 "--config=not-cargo",225 ]))226 .unwrap();227 let c = cargo_context(&opts, Path::new("root"), "cargo".into()).unwrap();228 assert_eq!(c.target_dir_override, Some(Path::new("root").join("cache")));229 assert_eq!(230 c.metadata_args,231 args(&["--manifest-path", "한글/Cargo.toml", "--offline"])232 );233 }234}235Findings in this file§
warning clippy::implicit_clone §
warning clippy::implicit_clone §
Targets (1)
cargo-clippy-html (bin)
Primary: src/cli.rs:80:17
help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#implicit_clone
note: `-W clippy::implicit-clone` implied by `-W clippy::pedantic`
help: to override `-W clippy::pedantic` add `#[allow(clippy::implicit_clone)]`
help: consider using
Suggestion: consider using
--- "a/src/cli.rs"
+++ "b/src/cli.rs"
@@ -77,9 +77,8 @@
OsString::from(v)
} else {
i += 1;
- args.get(i)
- .ok_or_else(|| format!("{name} requires a value"))?
- .to_os_string()
+ (*args.get(i)
+ .ok_or_else(|| format!("{name} requires a value"))?).clone()
};
if name == "--target-dir" {
context.target_dir_override = Some(cwd.join(value));
Rendered diagnostic (text)
warning: implicitly cloning a `OsString` by calling `to_os_string` on its dereferenced type
--> src/cli.rs:80:17
|
80 | / args.get(i)
81 | | .ok_or_else(|| format!("{name} requires a value"))?
82 | | .to_os_string()
| |___________________________________^
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#implicit_clone
= note: `-W clippy::implicit-clone` implied by `-W clippy::pedantic`
= help: to override `-W clippy::pedantic` add `#[allow(clippy::implicit_clone)]`
help: consider using
|
80 ~ (*args.get(i)
81 + .ok_or_else(|| format!("{name} requires a value"))?).clone()
|
warning clippy::implicit_clone §
warning clippy::implicit_clone §
Targets (1)
cargo-clippy-html (bin)
Primary: src/cli.rs:93:40
help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#implicit_clone
help: consider using
Suggestion: consider using
--- "a/src/cli.rs"
+++ "b/src/cli.rs"
@@ -90,7 +90,7 @@
name,
"--locked" | "--offline" | "--frozen" | "--all-features" | "--no-default-features"
) {
- context.metadata_args.push(args[i].to_os_string());
+ context.metadata_args.push(args[i].clone());
}
i += 1;
}
Rendered diagnostic (text)
warning: implicitly cloning a `OsString` by calling `to_os_string` on its dereferenced type --> src/cli.rs:93:40 | 93 | context.metadata_args.push(args[i].to_os_string()); | ^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `args[i].clone()` | = help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#implicit_clone