Skip to main content

cargo/diagnostics/rules/
unused_workspace_dependencies.rs

1use std::path::Path;
2
3use crate::util::data_structures::IndexSet;
4use cargo_util_schemas::manifest::InheritableDependency;
5use cargo_util_terminal::report::AnnotationKind;
6use cargo_util_terminal::report::Group;
7use cargo_util_terminal::report::Level;
8use cargo_util_terminal::report::Origin;
9use cargo_util_terminal::report::Snippet;
10use tracing::instrument;
11
12use super::SUSPICIOUS;
13use crate::CargoResult;
14use crate::GlobalContext;
15use crate::core::MaybePackage;
16use crate::core::Workspace;
17use crate::diagnostics::Lint;
18use crate::diagnostics::LintLevelProduct;
19use crate::diagnostics::ScopedDiagnosticStats;
20use crate::diagnostics::get_key_value_span;
21use crate::diagnostics::workspace_rel_path;
22
23pub static LINT: &Lint = &Lint {
24    name: "unused_workspace_dependencies",
25    desc: "unused workspace dependency",
26    primary_group: &SUSPICIOUS,
27    msrv: Some(super::CARGO_LINTS_MSRV),
28    feature_gate: None,
29    docs: Some(
30        r#"
31### What it does
32Checks for any entry in `[workspace.dependencies]` that has not been inherited
33
34### Why it is bad
35They can give the false impression that these dependencies are used
36
37### Example
38```toml
39[workspace.dependencies]
40regex = "1"
41
42[dependencies]
43```
44"#,
45    ),
46};
47
48#[instrument(skip_all)]
49pub(crate) fn lint_workspace(
50    ws: &Workspace<'_>,
51    maybe_pkg: &MaybePackage,
52    manifest_path: &Path,
53    level: LintLevelProduct,
54    pkg_stats: &mut ScopedDiagnosticStats<'_>,
55    gctx: &GlobalContext,
56) -> CargoResult<()> {
57    let LintLevelProduct {
58        level: lint_level,
59        source,
60    } = level;
61
62    let workspace_deps: IndexSet<_> = maybe_pkg
63        .original_toml()
64        .and_then(|t| t.workspace.as_ref())
65        .and_then(|w| w.dependencies.as_ref())
66        .iter()
67        .flat_map(|d| d.keys())
68        .collect();
69
70    let mut inherited_deps = IndexSet::default();
71    for member in ws.members() {
72        let Some(original_toml) = member.manifest().original_toml() else {
73            return Ok(());
74        };
75        inherited_deps.extend(
76            original_toml
77                .build_dependencies()
78                .into_iter()
79                .flatten()
80                .filter(|(_, d)| is_inherited(d))
81                .map(|(name, _)| name),
82        );
83        inherited_deps.extend(
84            original_toml
85                .dependencies
86                .iter()
87                .flatten()
88                .filter(|(_, d)| is_inherited(d))
89                .map(|(name, _)| name),
90        );
91        inherited_deps.extend(
92            original_toml
93                .dev_dependencies()
94                .into_iter()
95                .flatten()
96                .filter(|(_, d)| is_inherited(d))
97                .map(|(name, _)| name),
98        );
99        for target in original_toml.target.iter().flat_map(|t| t.values()) {
100            inherited_deps.extend(
101                target
102                    .build_dependencies()
103                    .into_iter()
104                    .flatten()
105                    .filter(|(_, d)| is_inherited(d))
106                    .map(|(name, _)| name),
107            );
108            inherited_deps.extend(
109                target
110                    .dependencies
111                    .iter()
112                    .flatten()
113                    .filter(|(_, d)| is_inherited(d))
114                    .map(|(name, _)| name),
115            );
116            inherited_deps.extend(
117                target
118                    .dev_dependencies()
119                    .into_iter()
120                    .flatten()
121                    .filter(|(_, d)| is_inherited(d))
122                    .map(|(name, _)| name),
123            );
124        }
125    }
126
127    for (i, unused) in workspace_deps.difference(&inherited_deps).enumerate() {
128        let document = maybe_pkg.document();
129        let contents = maybe_pkg.contents();
130        let level = lint_level.to_diagnostic_level();
131        let manifest_path = workspace_rel_path(ws, manifest_path);
132        let emitted_source = LINT.emitted_source(lint_level, source);
133
134        let mut primary = Group::with_title(level.primary_title(LINT.desc));
135        if let Some(document) = document
136            && let Some(contents) = contents
137        {
138            let mut snippet = Snippet::source(contents).path(&manifest_path);
139            if let Some(span) =
140                get_key_value_span(document, &["workspace", "dependencies", unused.as_str()])
141            {
142                snippet = snippet.annotation(AnnotationKind::Primary.span(span.key));
143            }
144            primary = primary.element(snippet);
145        } else {
146            primary = primary.element(Origin::path(&manifest_path));
147        }
148        if i == 0 {
149            primary = primary.element(Level::NOTE.message(emitted_source));
150        }
151        let mut report = vec![primary];
152        let help = Group::with_title(
153            Level::HELP.secondary_title("consider removing the unused workspace dependency"),
154        );
155        report.push(help);
156
157        pkg_stats.record_lint(lint_level);
158        gctx.shell().print_report(&report, lint_level.force())?;
159    }
160
161    Ok(())
162}
163
164fn is_inherited(dep: &InheritableDependency) -> bool {
165    matches!(dep, InheritableDependency::Inherit(_))
166}