cargo-mend 0.21.2

Opinionated visibility auditing for Rust crates and workspaces
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
//! `cargo mend` — opinionated visibility auditing for Rust crates and workspaces.
//!
//! Drives the compiler through `rustc_private` to resolve every path a crate
//! exposes, then reports items whose visibility is wider than their use
//! requires, along with the narrowing each one allows.

#![feature(rustc_private)]

extern crate rustc_driver;
extern crate rustc_hir;
extern crate rustc_interface;
extern crate rustc_middle;
extern crate rustc_span;

mod compiler;
mod config;
mod constants;
mod fixes;
mod reporting;
mod rust_syntax;
mod selection;

use std::env;
use std::io;
use std::io::IsTerminal;
use std::process::ExitCode;
use std::time::Duration;
use std::time::Instant;

use anyhow::Result;
use compiler::DRIVER_ENV;
use config::BuildInfoMode;
use config::DiagnosticsConfig;
use config::FixExecution;
use config::OperationMode;
use config::WarningPolicy;
use constants::BUILD_INFO_UNKNOWN;
use fixes::FIX_CONVERGENCE_MAX_PASSES;
use fixes::MendRunner;
use reporting::BuildOutcome;
use reporting::CARGO_TERM_COLOR_ALWAYS;
use reporting::CARGO_TERM_COLOR_ENV;
use reporting::CARGO_TERM_COLOR_NEVER;
use reporting::CLICOLOR_DISABLED_VALUE;
use reporting::CLICOLOR_ENV;
use reporting::CLICOLOR_FORCE_ENV;
use reporting::ColorMode;
use reporting::CompilerStats;
use reporting::CompilerWarningFacts;
use reporting::DIAGNOSTICS_HELP_NAME_COLUMN_WIDTH;
use reporting::EXIT_CODE_ERROR;
use reporting::EXIT_CODE_WARNING;
use reporting::ExecutionOutcome;
use reporting::MendFailure;
use reporting::OutputFormat;
use selection::DisplayFilter;
use selection::Selection;

fn main() -> ExitCode {
    if env::var_os(DRIVER_ENV).is_some() {
        return compiler::driver_main();
    }

    match run() {
        Ok(code) => code,
        Err(err) => {
            eprintln!("mend: {err}");
            MendFailure::exit_code()
        },
    }
}

fn build_diagnostics_help(diagnostics: &DiagnosticsConfig) -> String {
    let config_path = config::global_config_path()
        .map_or_else(|| "(unavailable)".to_string(), |p| p.display().to_string());

    let mut lines = vec![String::new(), "Diagnostics:".to_string()];
    for (code, enabled) in diagnostics.entries() {
        let name = code.as_str();
        let status = enabled.label();
        lines.push(format!(
            "  {name:<DIAGNOSTICS_HELP_NAME_COLUMN_WIDTH$} {status}"
        ));
    }
    lines.push(String::new());
    lines.push(format!("Config: {config_path}"));
    lines.join("\n")
}

fn build_info_text() -> String {
    let version = env!("CARGO_PKG_VERSION");
    let git_hash = option_env!("MEND_GIT_HASH").unwrap_or(BUILD_INFO_UNKNOWN);
    let build_id = option_env!("MEND_BUILD_ID").unwrap_or(BUILD_INFO_UNKNOWN);
    let build_sysroot = option_env!("MEND_BUILD_SYSROOT").unwrap_or(BUILD_INFO_UNKNOWN);
    format!(
        "cargo-mend {version}\n\
         git_hash: {git_hash}\n\
         build_id: {build_id}\n\
         build_sysroot: {build_sysroot}"
    )
}

/// Sum of all fix-eligible items across the three categories.
const fn total_fixables(outcome: &ExecutionOutcome) -> usize {
    outcome.report.summary.fixable_with_fix
        + outcome.report.summary.fixable_with_fix_pub_use
        + outcome.compiler_fixable
}

fn run() -> Result<ExitCode, MendFailure> {
    let global = config::load_global_config();
    let after_help = build_diagnostics_help(&global.diagnostics);
    let cli = config::parse(&after_help);
    if cli.build_info == BuildInfoMode::Show {
        println!("{}", build_info_text());
        return Ok(ExitCode::SUCCESS);
    }
    let selection = selection::resolve_cargo_selection(cli.cargo.explicit_manifest_path())
        .map_err(MendFailure::Unexpected)?;
    let cargo_plan = selection::build_cargo_check_plan(&selection, &cli.cargo);
    let loaded_config = config::load_config(
        selection.manifest_dir.as_path(),
        selection.workspace_root.as_path(),
        cli.manifest.config.as_deref(),
        &global,
    )
    .map_err(MendFailure::Unexpected)?;
    let operation_mode = OperationMode::from(&cli.fix);
    let color_mode = color_mode();
    let output_format = cli.output_format;
    let start = Instant::now();
    let mut runner = MendRunner::new(
        &selection,
        &cargo_plan,
        &loaded_config,
        color_mode,
        output_format,
    );
    let mut outcome = runner.run(operation_mode.clone())?;
    let mut accumulated_notice = outcome.notice.take();
    let mut accumulated_applied_pub_use = outcome.applied_pub_use;
    let mut accumulated_check_duration = outcome.check_duration;
    let mut total_compiler_fix_duration = Duration::ZERO;

    let mut passes = 1;

    loop {
        // Decide whether to chain `cargo fix`. Two trigger conditions:
        //  1. The user explicitly asked for it (`--fix-compiler` / `--fix-all`).
        //  2. `--fix-pub-use` (or its bundle inside `--fix-all`) just applied edits that produced
        //     `unused import` warnings; auto-clean them.
        let user_asked_for_compiler_fix = cli.fix.runs_compiler_fix();
        let pub_use_self_heal = matches!(
            cli.fix.execution,
            FixExecution::ApplyRequested | FixExecution::ApplyAll
        ) && outcome.applied_pub_use > 0
            && matches!(
                outcome.compiler_warning_facts,
                CompilerWarningFacts::UnusedImportWarnings
            );

        if user_asked_for_compiler_fix || pub_use_self_heal {
            total_compiler_fix_duration += compiler::run_cargo_fix(
                &selection,
                &cargo_plan,
                color_mode,
                outcome.report.facts.all_features_coverage,
            )?;
        }

        if !matches!(
            cli.fix.execution,
            FixExecution::ApplyRequested | FixExecution::ApplyAll
        ) || passes >= FIX_CONVERGENCE_MAX_PASSES
        {
            break;
        }

        // Re-scan applied mend fixes so visibility cascades converge without a
        // second invocation. Stop unless another pass strictly reduces the
        // remaining fixable set.
        let mut next = runner.run(operation_mode.clone())?;
        let next_total = total_fixables(&next);
        let prev_total = total_fixables(&outcome);
        accumulated_check_duration += next.check_duration;
        accumulated_applied_pub_use += next.applied_pub_use;
        if let Some(next_notice) = next.notice.take() {
            if let Some(notice) = accumulated_notice.as_mut() {
                notice.merge(next_notice);
            } else {
                accumulated_notice = Some(next_notice);
            }
        }
        if next_total == 0 || next_total >= prev_total {
            outcome = next;
            break;
        }
        outcome = next;
        passes += 1;
    }
    outcome.notice = accumulated_notice;
    outcome.applied_pub_use = accumulated_applied_pub_use;

    let total_duration = start.elapsed();
    let check_duration = accumulated_check_duration + total_compiler_fix_duration;

    // Apply display filter — narrows reported findings according to the
    // user's `--lib`, `--bin`, `--example`, `--test`, `--bench` flags.
    // Analysis already ran with `--all-targets`; the filter is purely a
    // display narrower.
    let display_filter = DisplayFilter::from_cli(&cli.cargo, &selection.packages);
    display_filter.apply(&mut outcome.report);

    render_outcome(
        &outcome,
        &selection,
        output_format,
        color_mode,
        total_duration,
        check_duration,
    )?;

    if outcome.report.outcome() == BuildOutcome::Failed {
        return Ok(ExitCode::from(EXIT_CODE_ERROR));
    }
    if cli.warning_policy == WarningPolicy::Fail && outcome.report.has_warnings() {
        return Ok(ExitCode::from(EXIT_CODE_WARNING));
    }
    Ok(ExitCode::SUCCESS)
}

fn render_outcome(
    outcome: &ExecutionOutcome,
    selection: &Selection,
    output_format: OutputFormat,
    color_mode: ColorMode,
    total_duration: Duration,
    check_duration: Duration,
) -> Result<(), MendFailure> {
    let compiler_stats = CompilerStats {
        warnings: outcome.compiler_warnings,
        fixable:  outcome.compiler_fixable,
    };

    match output_format {
        OutputFormat::Json => {
            print!(
                "{}",
                reporting::render_report(&outcome.report, selection)
                    .map_err(MendFailure::Unexpected)?
            );
        },
        OutputFormat::Human => {
            print!(
                "{}",
                reporting::render_human_report(&outcome.report, &compiler_stats, color_mode)
            );
        },
    }

    if output_format == OutputFormat::Human {
        let mend_duration = total_duration.saturating_sub(check_duration);
        eprintln!(
            "{}",
            reporting::render_timing(total_duration, check_duration, mend_duration, color_mode)
        );
    }

    if let Some(notice) = outcome.notice.as_ref() {
        eprintln!("{}", notice.render());
    }

    Ok(())
}

fn color_mode() -> ColorMode {
    if let Ok(choice) = env::var(CLICOLOR_FORCE_ENV)
        && choice != CLICOLOR_DISABLED_VALUE
    {
        return ColorMode::Enabled;
    }

    if let Ok(choice) = env::var(CARGO_TERM_COLOR_ENV) {
        let color_mode = match choice.to_ascii_lowercase().as_str() {
            CARGO_TERM_COLOR_NEVER => Some(ColorMode::Disabled),
            CARGO_TERM_COLOR_ALWAYS => Some(ColorMode::Enabled),
            _ => None,
        };
        if let Some(color_mode) = color_mode {
            return color_mode;
        }
    }

    if let Ok(choice) = env::var(CLICOLOR_ENV)
        && choice == CLICOLOR_DISABLED_VALUE
    {
        return ColorMode::Disabled;
    }

    if io::stdout().is_terminal() || io::stderr().is_terminal() {
        return ColorMode::Enabled;
    }

    ColorMode::Disabled
}

#[cfg(test)]
mod tests {
    use std::env;
    use std::ffi::OsString;

    use super::build_info_text;
    use super::color_mode;
    use crate::reporting::CARGO_TERM_COLOR_ALWAYS;
    use crate::reporting::CARGO_TERM_COLOR_ENV;
    use crate::reporting::CARGO_TERM_COLOR_NEVER;
    use crate::reporting::CLICOLOR_DISABLED_VALUE;
    use crate::reporting::CLICOLOR_ENV;
    use crate::reporting::CLICOLOR_FORCE_ENV;
    use crate::reporting::ColorMode;

    /// Restores an environment variable to its previous value on drop.
    ///
    /// `env::set_var` and `env::remove_var` are unsafe in edition 2024 because a
    /// concurrent read from another thread is undefined behaviour. The suite runs
    /// under `cargo nextest`, which gives every test its own process, so nothing
    /// else observes these variables while a guard is alive.
    struct EnvGuard {
        key:      &'static str,
        previous: Option<OsString>,
    }

    #[allow(
        unsafe_code,
        reason = "std::env mutation is unsafe in edition 2024; see EnvGuard"
    )]
    impl EnvGuard {
        fn set(key: &'static str, value: &'static str) -> Self {
            let previous = env::var_os(key);
            // SAFETY: one test per process, so no concurrent reader. See EnvGuard.
            unsafe { env::set_var(key, value) };
            Self { key, previous }
        }

        fn remove(key: &'static str) -> Self {
            let previous = env::var_os(key);
            // SAFETY: one test per process, so no concurrent reader. See EnvGuard.
            unsafe { env::remove_var(key) };
            Self { key, previous }
        }
    }

    #[allow(
        unsafe_code,
        reason = "std::env mutation is unsafe in edition 2024; see EnvGuard"
    )]
    impl Drop for EnvGuard {
        fn drop(&mut self) {
            if let Some(previous) = &self.previous {
                // SAFETY: one test per process, so no concurrent reader. See EnvGuard.
                unsafe { env::set_var(self.key, previous) };
            } else {
                // SAFETY: one test per process, so no concurrent reader. See EnvGuard.
                unsafe { env::remove_var(self.key) };
            }
        }
    }

    #[test]
    fn cargo_term_color_never_disables_color() {
        let _guard = EnvGuard::set(CARGO_TERM_COLOR_ENV, CARGO_TERM_COLOR_NEVER);
        assert!(matches!(color_mode(), ColorMode::Disabled));
    }

    #[test]
    fn cargo_term_color_always_enables_color() {
        let _guard = EnvGuard::set(CARGO_TERM_COLOR_ENV, CARGO_TERM_COLOR_ALWAYS);
        assert!(matches!(color_mode(), ColorMode::Enabled));
    }

    #[test]
    fn clicolor_zero_disables_color() {
        let _guard = EnvGuard::set(CLICOLOR_ENV, CLICOLOR_DISABLED_VALUE);
        let _cargo_term_color = EnvGuard::remove(CARGO_TERM_COLOR_ENV);
        assert!(matches!(color_mode(), ColorMode::Disabled));
    }

    #[test]
    fn term_does_not_enable_color_when_output_is_captured() {
        let _cargo_term_color = EnvGuard::remove(CARGO_TERM_COLOR_ENV);
        let _clicolor = EnvGuard::remove(CLICOLOR_ENV);
        let _clicolor_force = EnvGuard::remove(CLICOLOR_FORCE_ENV);
        let _term = EnvGuard::set("TERM", "xterm-256color");
        assert!(matches!(color_mode(), ColorMode::Disabled));
    }

    #[test]
    fn build_info_contains_expected_fields() {
        let build_info = build_info_text();

        assert!(build_info.starts_with(&format!("cargo-mend {}", env!("CARGO_PKG_VERSION"))));
        assert!(build_info.contains("\ngit_hash: "));
        assert!(build_info.contains("\nbuild_id: "));
        assert!(build_info.contains("\nbuild_sysroot: "));
    }
}