Skip to content

Commit

Permalink
add --fix
Browse files Browse the repository at this point in the history
  • Loading branch information
Boshen committed Mar 16, 2024
1 parent e879a22 commit e80654d
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 4 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,4 @@ proc-macro2 = {version="1", features = ["span-locations"]}
syn = { version = "2", features = ["full", "visit", "extra-traits"] }
regex = "1.10.3"
rayon = "1.9.0"
toml_edit = { version = "0.22.7", features = ["parse"] }
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Detect and remove unused dependencies from `Cargo.toml` in Rust projects.

```bash
cargo install cargo-shear
cargo shear
cargo shear --fix
```


Expand All @@ -20,7 +20,7 @@ cargo shear
## TODO

- [ ] make the reporting more granular for `[dependencies]`, `[dev-dependencies]` and `[build-dependencies]`
- [ ] `--fix`
- [ ] `--fix` the root Cargot.toml
- [ ] add tests
- [ ] exit codes
- [ ] error recovery
Expand Down
32 changes: 30 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::{
collections::{HashMap, HashSet},
fs,
path::{Path, PathBuf},
str::FromStr,
};

use bpaf::Bpaf;
Expand All @@ -18,6 +19,9 @@ use crate::import_collector::collect_imports;
#[derive(Debug, Clone, Bpaf)]
#[bpaf(options("shear"))]
pub struct CargoShearOptions {
#[bpaf(long)]
fix: bool,

#[bpaf(positional("PATH"), fallback(PathBuf::from(".")))]
path: PathBuf,
}
Expand All @@ -43,7 +47,7 @@ impl CargoShear {
let workspace_root = metadata.workspace_root.as_std_path();

for package in metadata.workspace_packages() {
Self::shear_package(workspace_root, package);
self.shear_package(workspace_root, package);
}

Self::shear_workspace(&metadata);
Expand Down Expand Up @@ -72,7 +76,7 @@ impl CargoShear {
}
}

fn shear_package(workspace_root: &Path, package: &Package) {
fn shear_package(&self, workspace_root: &Path, package: &Package) {
let dir = package.manifest_path.parent().unwrap().as_std_path();

let rust_file_paths = package
Expand Down Expand Up @@ -122,6 +126,7 @@ impl CargoShear {
.map(|name| package_deps_map[name].clone())
.collect::<Vec<_>>();
println!("{:?}: {unused_dep_names:?}", dir.strip_prefix(workspace_root).unwrap());
self.try_fix_package(package.manifest_path.as_std_path(), &unused_dep_names);
}
}

Expand All @@ -133,4 +138,27 @@ impl CargoShear {
let source_text = fs::read_to_string(path).unwrap();
collect_imports(&source_text).ok()
}

fn try_fix_package(&self, cargo_toml_path: &Path, unused_dep_names: &[String]) {
if !self.options.fix {
return;
}

let manifest = fs::read_to_string(cargo_toml_path).unwrap();
let mut manifest = toml_edit::DocumentMut::from_str(&manifest).unwrap();
let dependencies = manifest
.iter_mut()
.find_map(|(k, v)| (v.is_table_like() && k == "dependencies").then_some(Some(v)))
.flatten()
.expect("dependencies table is missing or empty")
.as_table_mut()
.expect("unexpected missing table");

for k in unused_dep_names {
dependencies.remove(k).unwrap_or_else(|| panic!("Dependency {k} not found"));
}

let serialized = manifest.to_string();
fs::write(cargo_toml_path, serialized).expect("Cargo.toml write error");
}
}

0 comments on commit e80654d

Please sign in to comment.