Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use argh for argument parsing (fixes #12) #51

Merged
merged 5 commits into from
Nov 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# Unreleased

- *Breaking*: Use `argh` for parsing. Now, paths of directories to scan must be passed in the last
position, when running from the command line (#51).
- Fix rare false positive and speed up most common case (#53).

# 0.4.0 (released on 2022-10-16)
Expand Down
36 changes: 36 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 4 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,17 @@ license = "MIT"
readme = "README.md"

[dependencies]
anyhow = "1.0.57"
argh = "0.1.9"
cargo_metadata = "0.14.2"
cargo_toml = "0.13.0"
grep = "0.2.8"
log = "0.4.16"
pretty_env_logger = "0.4.0"
walkdir = "2.3.2"
anyhow = "1.0.57"
rayon = "1.5.2"
cargo_metadata = "0.14.2"
serde = "1.0.136"
toml_edit = { version = "0.14.3", features = ["easy", "serde"] }
walkdir = "2.3.2"

# Uncomment this for profiling.
#[profile.release]
Expand Down
162 changes: 83 additions & 79 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,98 +1,70 @@
mod search_unused;

use crate::search_unused::{find_unused, UseCargoMetadata};
use crate::search_unused::find_unused;
use anyhow::Context;
use rayon::prelude::*;
use std::path::Path;
use std::str::FromStr;
use std::{fs, path::PathBuf};
use walkdir::WalkDir;

struct MacheteArgs {
fix: bool,
use_cargo_metadata: UseCargoMetadata,
paths: Vec<PathBuf>,
skip_target_dir: bool,
#[derive(Clone, Copy)]
pub(crate) enum UseCargoMetadata {
Yes,
No,
}

const HELP: &str = r#"cargo-machete: Helps find unused dependencies in a fast yet imprecise way.

Example usage: cargo-machete [PATH1] [PATH2] [--flags]?

Flags:

--help / -h: displays this help message.
#[cfg(test)]
impl UseCargoMetadata {
fn all() -> &'static [UseCargoMetadata] {
&[UseCargoMetadata::Yes, UseCargoMetadata::No]
}
}

--with-metadata: uses cargo-metadata to figure out the dependencies' names. May be useful if
some dependencies are renamed from their own Cargo.toml file (e.g. xml-rs
which gets renamed xml). Try it if you get false positives!
impl From<UseCargoMetadata> for bool {
fn from(v: UseCargoMetadata) -> bool {
matches!(v, UseCargoMetadata::Yes)
}
}

--skip-target-dir: don't analyze anything contained in any target/ directories encountered.
impl From<bool> for UseCargoMetadata {
fn from(b: bool) -> Self {
if b {
Self::Yes
} else {
Self::No
}
}
}

--fix: rewrite the Cargo.toml files to automatically remove unused dependencies.
Note: all dependencies flagged by cargo-machete will be removed, including false
positives.
#[derive(argh::FromArgs)]
#[argh(description = r#"
cargo-machete: Helps find unused dependencies in a fast yet imprecise way.

Exit code:

0: when no unused dependencies are found
1: when at least one unused (non-ignored) dependency is found
2: on error
"#;

fn parse_args() -> anyhow::Result<MacheteArgs> {
let mut fix = false;
let mut use_cargo_metadata = UseCargoMetadata::No;
let mut skip_target_dir = false;

let mut path_str = Vec::new();
let args = std::env::args();

for (i, arg) in args.into_iter().enumerate() {
// Ignore the binary name...
if i == 0 {
continue;
}
// ...and the "machete" command if ran as cargo subcommand.
if i == 1 && arg == "machete" {
continue;
}

if arg == "help" || arg == "-h" || arg == "--help" {
eprintln!("{}", HELP);
std::process::exit(0);
}

if arg == "--fix" {
fix = true;
} else if arg == "--with-metadata" {
use_cargo_metadata = UseCargoMetadata::Yes;
} else if arg == "--skip-target-dir" {
skip_target_dir = true;
} else if arg.starts_with('-') {
anyhow::bail!("invalid parameter {arg}. Usage:\n{HELP}");
} else {
path_str.push(arg);
}
}
"#)]
struct MacheteArgs {
/// uses cargo-metadata to figure out the dependencies' names. May be useful if some
/// dependencies are renamed from their own Cargo.toml file (e.g. xml-rs which gets renamed
/// xml). Try it if you get false positives!
#[argh(switch)]
with_metadata: bool,

/// don't analyze anything contained in any target/ directories encountered.
#[argh(switch)]
skip_target_dir: bool,

let paths = if path_str.is_empty() {
eprintln!("Analyzing dependencies of crates in this directory...");
vec![std::env::current_dir()?]
} else {
eprintln!(
"Analyzing dependencies of crates in {}...",
path_str.join(",")
);
path_str.into_iter().map(PathBuf::from).collect()
};
/// rewrite the Cargo.toml files to automatically remove unused dependencies.
/// Note: all dependencies flagged by cargo-machete will be removed, including false positives.
#[argh(switch)]
fix: bool,

Ok(MacheteArgs {
fix,
use_cargo_metadata,
paths,
skip_target_dir,
})
/// paths to directories that must be scanned.
#[argh(positional, greedy)]
paths: Vec<PathBuf>,
}

fn collect_paths(path: &Path, skip_target_dir: bool) -> Vec<PathBuf> {
Expand Down Expand Up @@ -120,13 +92,45 @@ fn collect_paths(path: &Path, skip_target_dir: bool) -> Vec<PathBuf> {
.collect()
}

/// Return true if this is run as `cargo machete`, false otherwise (`cargo-machete`, `cargo run -- ...`)
fn running_as_cargo_cmd() -> bool {
// If run under Cargo in general, a `CARGO` environment variable is set.
//
// But this is also set when running with `cargo run`, which we don't want to break! In that
// latter case, another set of cargo variables are defined, which aren't defined when just
// running as `cargo machete`. Picked `CARGO_PKG_NAME` as one of those variables.
//
// So we're running under cargo if `CARGO` is defined, but not `CARGO_PKG_NAME`.
std::env::var("CARGO").is_ok() && std::env::var("CARGO_PKG_NAME").is_err()
}

/// Runs `cargo-machete`.
/// Returns Ok with a bool whether any unused dependencies were found, or Err on errors.
fn run_machete() -> anyhow::Result<bool> {
pretty_env_logger::init();

let mut args: MacheteArgs = if running_as_cargo_cmd() {
argh::cargo_from_env()
} else {
argh::from_env()
};

if args.paths.is_empty() {
eprintln!("Analyzing dependencies of crates in this directory...");
args.paths.push(std::env::current_dir()?);
} else {
eprintln!(
"Analyzing dependencies of crates in {}...",
args.paths
.iter()
.cloned()
.map(|path| path.as_os_str().to_string_lossy().to_string())
.collect::<Vec<_>>()
.join(",")
);
}

let mut has_unused_dependencies = false;
let args = parse_args()?;

for path in args.paths {
let manifest_path_entries = collect_paths(&path, args.skip_target_dir);
Expand All @@ -135,8 +139,8 @@ fn run_machete() -> anyhow::Result<bool> {
// used by any Rust crate.
let results = manifest_path_entries
.par_iter()
.filter_map(
|manifest_path| match find_unused(manifest_path, args.use_cargo_metadata) {
.filter_map(|manifest_path| {
match find_unused(manifest_path, args.with_metadata.into()) {
Ok(Some(analysis)) => {
if analysis.unused.is_empty() {
None
Expand All @@ -157,8 +161,8 @@ fn run_machete() -> anyhow::Result<bool> {
eprintln!("error when handling {}: {}", manifest_path.display(), err);
None
}
},
)
}
})
.collect::<Vec<_>>();

// Display all the results.
Expand Down
20 changes: 1 addition & 19 deletions src/search_unused.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use std::{
};
use walkdir::WalkDir;

use crate::UseCargoMetadata;
#[cfg(test)]
use crate::TOP_LEVEL;

Expand Down Expand Up @@ -258,25 +259,6 @@ impl Search {
}
}

#[derive(Clone, Copy)]
pub(crate) enum UseCargoMetadata {
Yes,
No,
}

#[cfg(test)]
impl UseCargoMetadata {
fn all() -> &'static [UseCargoMetadata] {
&[UseCargoMetadata::Yes, UseCargoMetadata::No]
}
}

impl From<UseCargoMetadata> for bool {
fn from(v: UseCargoMetadata) -> bool {
matches!(v, UseCargoMetadata::Yes)
}
}

/// Read a manifest and try to find a workspace manifest to complete the data available in the
/// manifest.
///
Expand Down