|
1 | 1 | use cargo::core::dependency::DepKind;
|
| 2 | +use cargo::core::Workspace; |
2 | 3 | use cargo::ops::cargo_remove::remove;
|
3 | 4 | use cargo::ops::cargo_remove::RemoveOptions;
|
4 | 5 | use cargo::ops::resolve_ws;
|
5 | 6 | use cargo::util::command_prelude::*;
|
6 | 7 | use cargo::util::toml_mut::manifest::DepTable;
|
| 8 | +use cargo::util::toml_mut::manifest::LocalManifest; |
| 9 | +use cargo::CargoResult; |
7 | 10 |
|
8 | 11 | pub fn cli() -> clap::Command {
|
9 | 12 | clap::Command::new("remove")
|
@@ -85,6 +88,9 @@ pub fn exec(config: &mut Config, args: &ArgMatches) -> CliResult {
|
85 | 88 | remove(&options)?;
|
86 | 89 |
|
87 | 90 | if !dry_run {
|
| 91 | + // Clean up workspace dependencies |
| 92 | + gc_workspace(&workspace, &options.dependencies)?; |
| 93 | + |
88 | 94 | // Reload the workspace since we've changed dependencies
|
89 | 95 | let ws = args.workspace(config)?;
|
90 | 96 | resolve_ws(&ws)?;
|
@@ -114,3 +120,50 @@ fn parse_section(args: &ArgMatches) -> DepTable {
|
114 | 120 |
|
115 | 121 | table
|
116 | 122 | }
|
| 123 | + |
| 124 | +/// Clean up workspace dependencies which no longer have a reference to them. |
| 125 | +fn gc_workspace(workspace: &Workspace<'_>, dependencies: &[String]) -> CargoResult<()> { |
| 126 | + let mut manifest: toml_edit::Document = |
| 127 | + cargo_util::paths::read(workspace.root_manifest())?.parse()?; |
| 128 | + |
| 129 | + let members = workspace |
| 130 | + .members() |
| 131 | + .map(|p| LocalManifest::try_new(p.manifest_path())) |
| 132 | + .collect::<CargoResult<Vec<_>>>()?; |
| 133 | + |
| 134 | + for dep in dependencies { |
| 135 | + if !dep_in_workspace(dep, &members) { |
| 136 | + remove_workspace_dep(dep, &mut manifest); |
| 137 | + } |
| 138 | + } |
| 139 | + |
| 140 | + cargo_util::paths::write(workspace.root_manifest(), manifest.to_string().as_bytes())?; |
| 141 | + |
| 142 | + Ok(()) |
| 143 | +} |
| 144 | + |
| 145 | +/// Get whether or not a dependency is depended upon in a workspace. |
| 146 | +fn dep_in_workspace(dep: &str, members: &[LocalManifest]) -> bool { |
| 147 | + members.iter().any(|manifest| { |
| 148 | + manifest.get_sections().iter().any(|(_, table)| { |
| 149 | + table |
| 150 | + .as_table_like() |
| 151 | + .unwrap() |
| 152 | + .get(dep) |
| 153 | + .and_then(|t| t.get("workspace")) |
| 154 | + .and_then(|v| v.as_bool()) |
| 155 | + .unwrap_or(false) |
| 156 | + }) |
| 157 | + }) |
| 158 | +} |
| 159 | + |
| 160 | +/// Remove a dependency from a workspace manifest. |
| 161 | +fn remove_workspace_dep(dep: &str, ws_manifest: &mut toml_edit::Document) { |
| 162 | + if let Some(toml_edit::Item::Table(table)) = ws_manifest |
| 163 | + .get_mut("workspace") |
| 164 | + .and_then(|t| t.get_mut("dependencies")) |
| 165 | + { |
| 166 | + table.set_implicit(true); |
| 167 | + table.remove(dep); |
| 168 | + } |
| 169 | +} |
0 commit comments