Skip to main content

cargo_unmaintained/
lib.rs

1//! Implementation details for `cargo-unmaintained`
2//!
3//! `cargo-unmaintained` is a tool for finding unmaintained packages in Rust
4//! projects.
5//!
6//! The tool's main source file is at `src/bin/cargo-unmaintained.rs`.
7
8#![deny(clippy::expect_used, clippy::panic, clippy::unwrap_used)]
9#![cfg_attr(dylint_lib = "general", allow(crate_wide_allow))]
10#![cfg_attr(dylint_lib = "supplementary", allow(nonexistent_path_in_comment))]
11
12#[cfg(not(any(feature = "crates-index", feature = "tame-index")))]
13compile_error!("At least one of the `crates-index` or `tame-index` features must be enabled");
14
15use anyhow::{Context, Result, anyhow, bail, ensure};
16use cargo_metadata::{
17    Dependency, DependencyKind, Metadata, MetadataCommand, Package, PackageName, semver::Version,
18};
19use clap::{Parser, crate_version};
20#[cfg(all(feature = "crates-index", not(feature = "tame-index")))]
21use crates_index::{Error, GitIndex};
22use elaborate::std::{path::PathContext, process::CommandContext, time::SystemTimeContext};
23#[cfg(all(feature = "crates-index", not(feature = "tame-index")))]
24use home::cargo_home;
25#[cfg(feature = "tame-index")]
26use std::mem::ManuallyDrop;
27use std::{
28    cell::RefCell,
29    collections::{HashMap, HashSet},
30    env::args,
31    ffi::OsStr,
32    io::{BufRead, IsTerminal},
33    path::{Path, PathBuf},
34    process::{Command, Stdio, exit},
35    str::FromStr,
36    sync::{
37        LazyLock,
38        atomic::{AtomicBool, Ordering},
39    },
40    time::{Duration, SystemTime},
41};
42#[cfg(all(feature = "crates-index", not(feature = "tame-index")))]
43use std::{fmt::Write, fs::File};
44#[cfg(feature = "tame-index")]
45use tame_index::{
46    IndexLocation, KrateName,
47    index::{IndexUrl, RemoteSparseIndex, sparse::SparseIndex},
48    utils::flock::LockOptions,
49};
50use tempfile::TempDir;
51use termcolor::{ColorChoice, ColorSpec, StandardStream, WriteColor};
52use toml::{Table, Value};
53
54pub mod flush;
55pub mod github;
56pub mod packaging;
57
58mod curl;
59mod on_disk_cache;
60mod opts;
61mod progress;
62mod serialize;
63mod verbose;
64
65#[cfg(all(feature = "crates-index", not(feature = "tame-index")))]
66mod flock;
67
68use github::{Github as _, GithubRepo, Impl as Github};
69
70mod repo_status;
71use repo_status::RepoStatus;
72
73mod url;
74use url::{Url, urls};
75
76const SECS_PER_DAY: u64 = 24 * 60 * 60;
77
78const USER_AGENT: &str = "cargo-unmaintained (github.com/trailofbits/cargo-unmaintained)";
79
80#[derive(Debug, Parser)]
81#[clap(bin_name = "cargo", display_name = "cargo")]
82struct Cargo {
83    #[clap(subcommand)]
84    subcmd: CargoSubCommand,
85}
86
87#[derive(Debug, Parser)]
88enum CargoSubCommand {
89    Unmaintained(Opts),
90}
91
92include!(concat!(env!("OUT_DIR"), "/after_help.rs"));
93
94#[allow(clippy::struct_excessive_bools)]
95#[derive(Debug, Parser)]
96#[remain::sorted]
97#[clap(
98    version = crate_version!(),
99    about = "Find unmaintained packages in Rust projects",
100    after_help = AFTER_HELP
101)]
102struct Opts {
103    #[clap(
104        long,
105        help = "Whether all targets should be considered, rather than just the host"
106    )]
107    all_targets: bool,
108
109    #[clap(
110        long,
111        help = "When to use color: always, auto, or never",
112        default_value = "auto",
113        value_name = "WHEN"
114    )]
115    color: ColorChoice,
116
117    #[clap(
118        long,
119        help = "Exit as soon as an unmaintained package is found",
120        conflicts_with = "no_exit_code"
121    )]
122    fail_fast: bool,
123
124    #[clap(long, help = "Output JSON (experimental)")]
125    json: bool,
126
127    #[clap(
128        long,
129        help = "Age in days that a repository's last commit must not exceed for the repository to \
130                be considered current; 0 effectively disables this check, though ages are still \
131                reported",
132        value_name = "DAYS",
133        default_value = "365"
134    )]
135    max_age: u64,
136
137    #[cfg(all(feature = "on-disk-cache", not(windows)))]
138    #[clap(long, help = "Do not cache data on disk for future runs")]
139    no_cache: bool,
140
141    #[clap(
142        long,
143        help = "Do not set exit status when unmaintained packages are found",
144        conflicts_with = "fail_fast"
145    )]
146    no_exit_code: bool,
147
148    #[clap(long, help = "Do not show warnings")]
149    no_warnings: bool,
150
151    #[clap(
152        long,
153        short,
154        help = "Check only whether package NAME is unmaintained",
155        value_name = "NAME"
156    )]
157    package: Option<String>,
158
159    #[cfg(all(feature = "on-disk-cache", not(windows)))]
160    #[clap(long, help = "Remove all cached data from disk and exit")]
161    purge: bool,
162
163    #[cfg(not(windows))]
164    #[clap(
165        long,
166        help = "Read a personal access token from standard input and save it to \
167                $HOME/.config/cargo-unmaintained/token.txt"
168    )]
169    save_token: bool,
170
171    #[cfg(windows)]
172    #[clap(
173        long,
174        help = "Read a personal access token from standard input and save it to \
175                %LOCALAPPDATA%\\cargo-unmaintained\\token.txt"
176    )]
177    save_token: bool,
178
179    #[clap(long, help = "Show paths to unmaintained packages")]
180    tree: bool,
181
182    #[clap(long, help = "Show information about what cargo-unmaintained is doing")]
183    verbose: bool,
184}
185
186struct UnmaintainedPkg<'a> {
187    pkg: &'a Package,
188    repo_age: RepoStatus<'a, u64>,
189    newer_version_is_available: bool,
190    outdated_deps: Vec<OutdatedDep<'a>>,
191}
192
193struct OutdatedDep<'a> {
194    dep: &'a Dependency,
195    version_used: &'a Version,
196    version_latest: Version,
197}
198
199#[macro_export]
200macro_rules! warn {
201    ($fmt:expr, $($arg:tt)*) => {
202        if $crate::opts::get().no_warnings {
203            log::debug!($fmt, $($arg)*);
204        } else {
205            $crate::verbose::newline!();
206            $crate::PROGRESS.with_borrow_mut(|progress| progress.as_mut().map($crate::progress::Progress::newline));
207            eprintln!(concat!("warning: ", $fmt), $($arg)*);
208        }
209    };
210}
211
212#[cfg(all(feature = "crates-index", not(feature = "tame-index")))]
213#[allow(clippy::unwrap_used)]
214fn create_index() -> GitIndex {
215    let _lock = lock_index().unwrap();
216    #[allow(clippy::panic)]
217    let mut index = match GitIndex::new_cargo_default() {
218        Ok(index) => index,
219        Err(error) => {
220            let mut msg = format!("failed to create index: {error}");
221            // smoelius: I once saw a recommendation to delete a corrupt crates.io index, but I
222            // cannot remember where. Maybe the following?
223            // https://github.com/rust-lang/cargo/issues/2403#issuecomment-186874266
224            if let Error::MissingHead { repo_path, .. } = &error {
225                write!(
226                    msg,
227                    "\n\nIf the problem persists, consider deleting this directory: {}",
228                    repo_path.display()
229                )
230                .unwrap();
231            }
232            panic!("{msg}");
233        }
234    };
235    if let Err(error) = index.update() {
236        warn!("failed to update index: {}", error);
237    }
238    index
239}
240
241#[cfg(feature = "tame-index")]
242#[allow(clippy::expect_used)]
243fn create_index() -> RemoteSparseIndex {
244    let index_url =
245        IndexUrl::crates_io(None, None, None).expect("failed to get crates.io index URL");
246    let index_location = IndexLocation::new(index_url);
247    let sparse_index = SparseIndex::new(index_location).expect("failed to create sparse index");
248    let client = reqwest::blocking::Client::builder()
249        .user_agent(USER_AGENT)
250        .build()
251        .expect("failed to build HTTP client");
252    RemoteSparseIndex::new(sparse_index, client)
253}
254
255thread_local! {
256    #[cfg(all(feature = "crates-index", not(feature = "tame-index")))]
257    static INDEX: LazyLock<GitIndex> = LazyLock::new(create_index);
258    // smoelius: Use `ManuallyDrop` to prevent the destructor from running during process exit. On
259    // Windows, `std::process::exit` triggers thread-local destructors, and the `RemoteSparseIndex`
260    // destructor can panic during shutdown.
261    #[cfg(feature = "tame-index")]
262    static INDEX: ManuallyDrop<LazyLock<RemoteSparseIndex>> = ManuallyDrop::new(LazyLock::new(create_index));
263    static PROGRESS: RefCell<Option<progress::Progress>> = const { RefCell::new(None) };
264    // smoelius: The next four statics are "in-memory" caches.
265    // smoelius: Note that repositories are (currently) stored in both an in-memory cache and an
266    // on-disk cache. The former is keyed by url; the latter is keyed by package.
267    // smoelius: A reason for having the former is the following. Multiple packages map to the same
268    // url, and multiple urls map to the same shortened url. Thus, a cache keyed by url has a
269    // greater chance of a cache hit.
270    static GENERAL_STATUS_CACHE: RefCell<HashMap<Url<'static>, RepoStatus<'static, ()>>> = RefCell::new(HashMap::new());
271    static LATEST_VERSION_CACHE: RefCell<HashMap<String, Version>> = RefCell::new(HashMap::new());
272    static TIMESTAMP_CACHE: RefCell<HashMap<Url<'static>, RepoStatus<'static, SystemTime>>> = RefCell::new(HashMap::new());
273    static REPOSITORY_CACHE: RefCell<HashMap<Url<'static>, RepoStatus<'static, PathBuf>>> = RefCell::new(HashMap::new());
274}
275
276static TOKEN_FOUND: AtomicBool = AtomicBool::new(false);
277
278pub fn run() -> Result<()> {
279    env_logger::init();
280
281    let Cargo {
282        subcmd: CargoSubCommand::Unmaintained(opts),
283    } = Cargo::parse_from(args());
284
285    opts::init(opts);
286
287    if opts::get().save_token {
288        // smoelius: Currently, if additional options are passed besides --save-token, they are
289        // ignored and no error is emitted. This is ugly.
290        return Github::save_token();
291    }
292
293    #[cfg(all(feature = "on-disk-cache", not(windows)))]
294    if opts::get().purge {
295        return on_disk_cache::purge_cache();
296    }
297
298    if Github::load_token(|_| Ok(()))? {
299        TOKEN_FOUND.store(true, Ordering::SeqCst);
300    }
301
302    match unmaintained() {
303        Ok(false) => exit(0),
304        Ok(true) => exit(1),
305        Err(error) => {
306            eprintln!("Error: {error:?}");
307            exit(2);
308        }
309    }
310}
311
312fn unmaintained() -> Result<bool> {
313    let mut unmaintained_pkgs = Vec::new();
314
315    let metadata = metadata()?;
316
317    let packages = packages(&metadata)?;
318
319    if TOKEN_FOUND.load(Ordering::SeqCst) {
320        prefetch_github_data(&packages);
321    }
322
323    eprintln!(
324        "Scanning {} packages and their dependencies{}",
325        packages.len(),
326        if opts::get().verbose {
327            ""
328        } else {
329            " (pass --verbose for more information)"
330        }
331    );
332
333    if std::io::stderr().is_terminal() && !opts::get().verbose {
334        PROGRESS
335            .with_borrow_mut(|progress| *progress = Some(progress::Progress::new(packages.len())));
336    }
337
338    for pkg in packages {
339        PROGRESS.with_borrow_mut(|progress| {
340            progress
341                .as_mut()
342                .map_or(Ok(()), |progress| progress.advance(&pkg.name))
343        })?;
344
345        if let Some(mut unmaintained_pkg) = is_unmaintained_package(&metadata, pkg)? {
346            // smoelius: Before considering a package unmaintained, verify that its latest version
347            // would be considered unmaintained as well. Note that we still report the details of
348            // the version currently used. We may want to revisit this in the future.
349            let newer_version_is_available = newer_version_is_available(pkg)?;
350            if !newer_version_is_available || latest_version_is_unmaintained(&pkg.name)? {
351                unmaintained_pkg.newer_version_is_available = newer_version_is_available;
352                unmaintained_pkgs.push(unmaintained_pkg);
353
354                if opts::get().fail_fast {
355                    break;
356                }
357            }
358        }
359    }
360
361    PROGRESS
362        .with_borrow_mut(|progress| progress.as_mut().map_or(Ok(()), progress::Progress::finish))?;
363
364    if opts::get().json {
365        unmaintained_pkgs.sort_by_key(|unmaintained| &unmaintained.pkg.id);
366
367        let json = serde_json::to_string_pretty(&unmaintained_pkgs)?;
368
369        println!("{json}");
370    } else {
371        if unmaintained_pkgs.is_empty() {
372            eprintln!("No unmaintained packages found");
373            return Ok(false);
374        }
375
376        unmaintained_pkgs.sort_by_key(|unmaintained| unmaintained.repo_age.erase_url());
377
378        display_unmaintained_pkgs(&unmaintained_pkgs)?;
379    }
380
381    Ok(!opts::get().no_exit_code)
382}
383
384fn metadata() -> Result<Metadata> {
385    let mut command = MetadataCommand::new();
386
387    // smoelius: See tests/snapbox.rs for another use of this conditional initialization trick.
388    let tempdir: TempDir;
389
390    if let Some(name) = &opts::get().package {
391        tempdir = packaging::temp_package(name)?;
392        command.current_dir(tempdir.path());
393    }
394
395    command.exec().map_err(Into::into)
396}
397
398fn packages(metadata: &Metadata) -> Result<Vec<&Package>> {
399    let ignored_packages = ignored_packages(metadata)?;
400
401    for name in &ignored_packages {
402        if !metadata.packages.iter().any(|pkg| pkg.name == *name) {
403            warn!(
404                "workspace metadata says to ignore `{}`, but workspace does not depend upon `{}`",
405                name, name
406            );
407        }
408    }
409
410    filter_packages(metadata, &ignored_packages)
411}
412
413#[derive(serde::Deserialize)]
414struct UnmaintainedMetadata {
415    ignore: Option<Vec<String>>,
416}
417
418fn ignored_packages(metadata: &Metadata) -> Result<HashSet<String>> {
419    let serde_json::Value::Object(object) = &metadata.workspace_metadata else {
420        return Ok(HashSet::default());
421    };
422    let Some(value) = object.get("unmaintained") else {
423        return Ok(HashSet::default());
424    };
425    let metadata = serde_json::value::from_value::<UnmaintainedMetadata>(value.clone())?;
426    Ok(metadata.ignore.unwrap_or_default().into_iter().collect())
427}
428
429fn filter_packages<'a>(
430    metadata: &'a Metadata,
431    ignored_packages: &HashSet<String>,
432) -> Result<Vec<&'a Package>> {
433    let mut packages = Vec::new();
434
435    // smoelius: If a project relies on multiple versions of a package, check only the latest one.
436    let metadata_latest_version_map = build_metadata_latest_version_map(metadata);
437
438    for pkg in &metadata.packages {
439        // smoelius: Don't consider whether workspace members are unmaintained.
440        if metadata.workspace_members.contains(&pkg.id) {
441            continue;
442        }
443
444        if ignored_packages.contains(pkg.name.as_str()) {
445            continue;
446        }
447
448        #[allow(clippy::panic)]
449        let version = metadata_latest_version_map
450            .get(&pkg.name)
451            .unwrap_or_else(|| {
452                panic!(
453                    "`metadata_latest_version_map` does not contain {}",
454                    pkg.name
455                )
456            });
457
458        if pkg.version != *version {
459            continue;
460        }
461
462        if let Some(name) = &opts::get().package
463            && pkg.name != *name
464        {
465            continue;
466        }
467
468        packages.push(pkg);
469    }
470
471    if let Some(name) = &opts::get().package {
472        if packages.len() >= 2 {
473            bail!("found multiple packages matching `{name}`: {packages:#?}");
474        }
475
476        if packages.is_empty() {
477            bail!("found no packages matching `{name}`");
478        }
479    }
480
481    Ok(packages)
482}
483
484fn build_metadata_latest_version_map(metadata: &Metadata) -> HashMap<PackageName, Version> {
485    let mut map: HashMap<PackageName, Version> = HashMap::new();
486
487    for pkg in &metadata.packages {
488        if let Some(version) = map.get_mut(&pkg.name) {
489            if *version < pkg.version {
490                *version = pkg.version.clone();
491            }
492        } else {
493            map.insert(pkg.name.clone(), pkg.version.clone());
494        }
495    }
496
497    map
498}
499
500fn prefetch_github_data(packages: &[&Package]) {
501    let mut repo_aliases = HashMap::new();
502    let mut seen_repos = HashSet::new();
503    let mut repos = Vec::new();
504
505    for pkg in packages {
506        let Some(github_repo) = github_repo_for_package(pkg) else {
507            continue;
508        };
509
510        let key = format!("{}/{}", github_repo.owner, github_repo.repo);
511        let aliases = repo_aliases.entry(key.clone()).or_insert_with(Vec::new);
512        for alias in urls(pkg) {
513            push_repo_alias(aliases, alias);
514        }
515        push_repo_alias(aliases, github_repo.url);
516
517        if seen_repos.insert(key) {
518            repos.push(github_repo);
519        }
520    }
521
522    if repos.is_empty() {
523        return;
524    }
525
526    eprintln!("Prefetching GitHub data for {} repositories", repos.len());
527
528    let repo_statuses = match Github::prefetch(&repos) {
529        Ok(repo_statuses) => repo_statuses,
530        Err(error) => {
531            warn!(
532                "failed to prefetch Github data; falling back to per-package queries: {}",
533                error
534            );
535            return;
536        }
537    };
538
539    for repo_status in repo_statuses {
540        let Some(url) = repo_status_url(&repo_status) else {
541            continue;
542        };
543        let Some(github_repo) = GithubRepo::from_url(url) else {
544            continue;
545        };
546        let key = format!("{}/{}", github_repo.owner, github_repo.repo);
547        if let Some(aliases) = repo_aliases.get(&key) {
548            for &alias in aliases {
549                cache_prefetched_github_data(repo_status, alias);
550            }
551        } else {
552            cache_prefetched_github_data(repo_status, url);
553        }
554    }
555}
556
557fn github_repo_for_package(pkg: &Package) -> Option<GithubRepo<'_>> {
558    let url_string = pkg.repository.as_ref()?;
559    let url = Url::from(url_string.as_str()).trim_trailing_slash();
560    GithubRepo::from_url(url)
561}
562
563fn push_repo_alias<'a>(aliases: &mut Vec<Url<'a>>, alias: Url<'a>) {
564    if !aliases.contains(&alias) {
565        aliases.push(alias);
566    }
567}
568
569fn repo_status_url<'a, T>(repo_status: &RepoStatus<'a, T>) -> Option<Url<'a>> {
570    match repo_status {
571        RepoStatus::Uncloneable(url)
572        | RepoStatus::Success(url, _)
573        | RepoStatus::Unassociated(url)
574        | RepoStatus::Nonexistent(url)
575        | RepoStatus::Archived(url) => Some(*url),
576        RepoStatus::Unnamed => None,
577    }
578}
579
580fn cache_prefetched_github_data(repo_status: RepoStatus<'_, SystemTime>, url: Url<'_>) {
581    match repo_status {
582        RepoStatus::Success(_, timestamp) => {
583            let url = url.leak();
584            GENERAL_STATUS_CACHE
585                .with_borrow_mut(|cache| cache.insert(url, RepoStatus::Success(url, ())));
586            TIMESTAMP_CACHE.with_borrow_mut(|cache| {
587                // The repository has not been cloned yet, so using the canonical GitHub URL as the
588                // timestamp cache key is optimistic. A later `clone_repository` call must still
589                // succeed before this timestamp is used.
590                let url = GithubRepo::from_url(url).map_or(url, |github_repo| github_repo.url);
591                cache.insert(url, RepoStatus::Success(url, timestamp));
592            });
593        }
594        RepoStatus::Archived(_) => {
595            let url = url.leak();
596            GENERAL_STATUS_CACHE
597                .with_borrow_mut(|cache| cache.insert(url, RepoStatus::Archived(url)));
598        }
599        RepoStatus::Nonexistent(_) => {
600            let url = url.leak();
601            GENERAL_STATUS_CACHE
602                .with_borrow_mut(|cache| cache.insert(url, RepoStatus::Nonexistent(url)));
603        }
604        RepoStatus::Uncloneable(_) | RepoStatus::Unnamed | RepoStatus::Unassociated(_) => {}
605    }
606}
607
608fn newer_version_is_available(pkg: &Package) -> Result<bool> {
609    if pkg
610        .source
611        .as_ref()
612        .is_none_or(|source| !source.is_crates_io())
613    {
614        return Ok(false);
615    }
616
617    let latest_version = latest_version(&pkg.name)?;
618
619    Ok(pkg.version != latest_version)
620}
621
622fn latest_version_is_unmaintained(name: &str) -> Result<bool> {
623    let tempdir = packaging::temp_package(name)?;
624
625    let metadata = MetadataCommand::new().current_dir(tempdir.path()).exec()?;
626
627    #[allow(clippy::panic)]
628    let pkg = metadata
629        .packages
630        .iter()
631        .find(|pkg| name == pkg.name.as_str())
632        .unwrap_or_else(|| panic!("failed to find package `{name}`"));
633
634    let unmaintained_package = is_unmaintained_package(&metadata, pkg)?;
635
636    Ok(unmaintained_package.is_some())
637}
638
639fn is_unmaintained_package<'a>(
640    metadata: &'a Metadata,
641    pkg: &'a Package,
642) -> Result<Option<UnmaintainedPkg<'a>>> {
643    if let Some(url_string) = &pkg.repository {
644        let can_use_github_api =
645            TOKEN_FOUND.load(Ordering::SeqCst) && url_string.starts_with("https://github.com/");
646
647        let url = url_string.as_str().into();
648
649        if can_use_github_api {
650            let repo_status = general_status(&pkg.name, url)?;
651            if repo_status.is_failure() {
652                return Ok(Some(UnmaintainedPkg {
653                    pkg,
654                    repo_age: repo_status.map_failure(),
655                    newer_version_is_available: false,
656                    outdated_deps: Vec::new(),
657                }));
658            }
659        }
660
661        let repo_status = clone_repository(pkg)?;
662        if repo_status.is_failure() {
663            // smoelius: Mercurial repos get a pass.
664            if matches!(repo_status, RepoStatus::Uncloneable(_)) && curl::is_mercurial_repo(url)? {
665                return Ok(None);
666            }
667            return Ok(Some(UnmaintainedPkg {
668                pkg,
669                repo_age: repo_status.map_failure(),
670                newer_version_is_available: false,
671                outdated_deps: Vec::new(),
672            }));
673        }
674    }
675
676    let outdated_deps = outdated_deps(metadata, pkg)?;
677
678    if outdated_deps.is_empty() {
679        return Ok(None);
680    }
681
682    let repo_age = latest_commit_age(pkg)?;
683
684    if repo_age
685        .as_success()
686        .is_some_and(|(_, &age)| age < opts::get().max_age * SECS_PER_DAY)
687    {
688        return Ok(None);
689    }
690
691    Ok(Some(UnmaintainedPkg {
692        pkg,
693        repo_age,
694        newer_version_is_available: false,
695        outdated_deps,
696    }))
697}
698
699fn general_status(name: &str, url: Url) -> Result<RepoStatus<'static, ()>> {
700    GENERAL_STATUS_CACHE.with_borrow_mut(|general_status_cache| {
701        if let Some(&value) = general_status_cache.get(&url) {
702            return Ok(value);
703        }
704        let to_string: &dyn Fn(&RepoStatus<'static, ()>) -> String;
705        let (use_github_api, what, how) = if TOKEN_FOUND.load(Ordering::SeqCst)
706            && url.as_str().starts_with("https://github.com/")
707        {
708            to_string = &RepoStatus::to_archival_status_string;
709            (true, "archival status", "GitHub API")
710        } else {
711            to_string = &RepoStatus::to_existence_string;
712            (false, "existence", "HTTP request")
713        };
714        verbose::wrap!(
715            || {
716                let repo_status = if use_github_api {
717                    Github::archival_status(url)
718                } else {
719                    curl::existence(url)
720                }
721                .unwrap_or_else(|error| {
722                    warn!("failed to determine `{}` {}: {}", name, what, error);
723                    RepoStatus::Success(url, ())
724                })
725                .leak_url();
726                general_status_cache.insert(url.leak(), repo_status);
727                Ok(repo_status)
728            },
729            to_string,
730            "{} of `{}` using {}",
731            what,
732            name,
733            how
734        )
735    })
736}
737
738#[allow(clippy::panic, clippy::unwrap_used)]
739static HOST: LazyLock<String> = LazyLock::new(|| {
740    let mut command = Command::new("rustc");
741    command.arg("-Vv");
742    let output = command.output_wc().unwrap();
743    assert!(output.status.success(), "command failed: {command:?}");
744    let stdout = String::from_utf8(output.stdout).unwrap();
745    stdout
746        .lines()
747        .find_map(|line| line.strip_prefix("host: "))
748        .map_or_else(|| panic!("failed to determine host"), str::to_owned)
749});
750
751#[allow(clippy::unnecessary_wraps)]
752fn outdated_deps<'a>(metadata: &'a Metadata, pkg: &'a Package) -> Result<Vec<OutdatedDep<'a>>> {
753    if !published(pkg) {
754        return Ok(Vec::new());
755    }
756    let mut deps = Vec::new();
757    for dep in &pkg.dependencies {
758        // smoelius: Skip dependencies with specified platforms that are not the host.
759        if !opts::get().all_targets
760            && let Some(platform) = &dep.target
761            && !platform.matches(&HOST, &[])
762        {
763            continue;
764        }
765        // smoelius: Don't check dependencies in private registries.
766        if dep.registry.is_some() {
767            continue;
768        }
769        // smoelius: Don't check dependencies specified by path.
770        if dep.path.is_some() {
771            continue;
772        }
773        if dep.kind == DependencyKind::Development {
774            continue;
775        }
776        let Some(dep_pkg) = resolved_package(metadata, pkg, dep) else {
777            debug_assert!(dep.optional);
778            continue;
779        };
780        let Ok(version_latest) = latest_version(&dep.name).map_err(|error| {
781            // smoelius: I don't understand why a package can fail to be in the index, but I have
782            // seen it happen.
783            warn!("failed to get latest version of `{}`: {}", dep.name, error);
784        }) else {
785            continue;
786        };
787        if dep_pkg.version <= version_latest && !dep.req.matches(&version_latest) {
788            let versions = versions(&dep_pkg.name)?;
789            // smoelius: Require at least one incompatible version of the dependency that is more
790            // than `max_age` days old.
791            if versions
792                .iter()
793                .try_fold(false, |init, version| -> Result<_> {
794                    if init {
795                        return Ok(true);
796                    }
797                    let duration =
798                        SystemTime::now().duration_since_wc(version.created_at.into())?;
799                    let version_num = Version::parse(&version.num)?;
800                    Ok(duration.as_secs() >= opts::get().max_age * SECS_PER_DAY
801                        && dep_pkg.version <= version_num
802                        && !dep.req.matches(&version_num))
803                })?
804            {
805                deps.push(OutdatedDep {
806                    dep,
807                    version_used: &dep_pkg.version,
808                    version_latest,
809                });
810            }
811        }
812    }
813    // smoelius: A dependency could appear more than once, e.g., because it is used with different
814    // features as a normal and as a development dependency.
815    deps.dedup_by(|lhs, rhs| lhs.dep.name == rhs.dep.name && lhs.dep.req == rhs.dep.req);
816    Ok(deps)
817}
818
819fn published(pkg: &Package) -> bool {
820    pkg.publish.as_deref() != Some(&[])
821}
822
823fn resolved_package<'a>(
824    metadata: &'a Metadata,
825    pkg: &Package,
826    dep: &Dependency,
827) -> Option<&'a Package> {
828    let resolve = metadata.resolve.as_ref()?;
829    let node = resolve.nodes.iter().find(|node| pkg.id == node.id)?;
830    node.deps
831        .iter()
832        .filter(|node_dep| {
833            node_dep
834                .dep_kinds
835                .iter()
836                .any(|dep_kind| dep.kind == dep_kind.kind && dep.target == dep_kind.target)
837        })
838        .find_map(|node_dep| {
839            metadata.packages.iter().find(|dep_pkg| {
840                node_dep.pkg == dep_pkg.id
841                    && dep.name.as_str() == dep_pkg.name.as_str()
842                    && dep.req.matches(&dep_pkg.version)
843            })
844        })
845}
846
847fn latest_version(name: &str) -> Result<Version> {
848    LATEST_VERSION_CACHE.with_borrow_mut(|latest_version_cache| {
849        if let Some(version) = latest_version_cache.get(name) {
850            return Ok(version.clone());
851        }
852        verbose::wrap!(
853            || {
854                #[cfg(all(feature = "crates-index", not(feature = "tame-index")))]
855                let latest_version = {
856                    let krate = INDEX.with(|index| {
857                        let _ = LazyLock::force(index);
858                        let _lock = lock_index()?;
859                        index
860                            .crate_(name)
861                            .ok_or_else(|| anyhow!("failed to find `{name}` in index"))
862                    })?;
863                    let latest_version_index = krate
864                        .highest_normal_version()
865                        .ok_or_else(|| anyhow!("`{name}` has no normal version"))?;
866                    Version::from_str(latest_version_index.version())?
867                };
868                #[cfg(feature = "tame-index")]
869                let latest_version = {
870                    let krate_name = KrateName::crates_io(name)
871                        .map_err(|e| anyhow!("invalid crate name `{name}`: {e}"))?;
872                    let lock_options = LockOptions::cargo_package_lock(None)
873                        .map_err(|e| anyhow!("failed to create cargo package lock: {e}"))?;
874                    let lock = lock_options
875                        .lock(|_| None)
876                        .map_err(|e| anyhow!("failed to acquire cargo package lock: {e}"))?;
877                    let krate = INDEX.with(|index| {
878                        let _ = LazyLock::force(index);
879                        let krate = index
880                            .krate(krate_name, true, &lock)
881                            .map_err(|e| anyhow!("failed to fetch `{name}` from index: {e}"))?;
882                        krate.ok_or_else(|| anyhow!("failed to find `{name}` in index"))
883                    })?;
884                    let latest_version_index = krate
885                        .highest_normal_version()
886                        .ok_or_else(|| anyhow!("`{name}` has no normal version"))?;
887                    Version::from_str(&latest_version_index.version)?
888                };
889                latest_version_cache.insert(name.to_owned(), latest_version.clone());
890                Ok(latest_version)
891            },
892            ToString::to_string,
893            "latest version of `{}` using crates.io index",
894            name
895        )
896    })
897}
898
899fn versions(name: &str) -> Result<Vec<crates_io_api::Version>> {
900    on_disk_cache::with_cache(|cache| -> Result<_> {
901        verbose::wrap!(
902            || { cache.fetch_versions(name) },
903            |versions: &[crates_io_api::Version]| format!("{} versions", versions.len()),
904            "versions of `{}` using crates.io API",
905            name
906        )
907    })
908}
909
910fn latest_commit_age(pkg: &Package) -> Result<RepoStatus<'_, u64>> {
911    let repo_status = timestamp(pkg)?;
912
913    repo_status
914        .map(|timestamp| {
915            let duration = SystemTime::now().duration_since_wc(timestamp)?;
916
917            Ok(duration.as_secs())
918        })
919        .transpose()
920}
921
922fn timestamp(pkg: &Package) -> Result<RepoStatus<'_, SystemTime>> {
923    TIMESTAMP_CACHE.with_borrow_mut(|timestamp_cache| {
924        // smoelius: Check both the regular and the shortened url.
925        for url in urls(pkg) {
926            if let Some(&repo_status) = timestamp_cache.get(&url) {
927                // smoelius: If a previous attempt to timestamp the repository failed (e.g., because
928                // of spurious network errors), then don't bother checking the repository cache.
929                let Some((url_timestamped, &timestamp)) = repo_status.as_success() else {
930                    return Ok(repo_status);
931                };
932                assert_eq!(url, url_timestamped);
933                // smoelius: `pkg`'s repository could contain other packages that were already
934                // timestamped. Thus, `pkg`'s repository could already be in the timestamp cache.
935                // But in that case, we still need to verify that `pkg` appears in its repository.
936                let repo_status = clone_repository(pkg)?;
937                let Some((url_cloned, _)) = repo_status.as_success() else {
938                    return Ok(repo_status.map_failure());
939                };
940                assert_eq!(url, url_cloned);
941                return Ok(RepoStatus::Success(url, timestamp));
942            }
943        }
944        let repo_status = timestamp_uncached(pkg)?;
945        if let Some((url, _)) = repo_status.as_success() {
946            timestamp_cache.insert(url.leak(), repo_status.leak_url());
947        } else {
948            // smoelius: In the event of failure, set all urls associated with the
949            // repository.
950            for url in urls(pkg) {
951                timestamp_cache.insert(url.leak(), repo_status.leak_url());
952            }
953        }
954        Ok(repo_status)
955    })
956}
957
958fn timestamp_uncached(pkg: &Package) -> Result<RepoStatus<'_, SystemTime>> {
959    if pkg.repository.is_none() {
960        return Ok(RepoStatus::Unnamed);
961    }
962
963    timestamp_from_clone(pkg)
964}
965
966fn timestamp_from_clone(pkg: &Package) -> Result<RepoStatus<'_, SystemTime>> {
967    let repo_status = clone_repository(pkg)?;
968
969    let Some((url, repo_dir)) = repo_status.as_success() else {
970        return Ok(repo_status.map_failure());
971    };
972
973    let mut command = Command::new("git");
974    command
975        .args(["log", "-1", "--pretty=format:%ct"])
976        .current_dir(repo_dir);
977    let output = command.output_wc()?;
978    ensure!(output.status.success(), "command failed: {command:?}");
979
980    let stdout = std::str::from_utf8(&output.stdout)?;
981    let secs = u64::from_str(stdout.trim_end())?;
982    let timestamp = SystemTime::UNIX_EPOCH + Duration::from_secs(secs);
983
984    Ok(RepoStatus::Success(url, timestamp))
985}
986
987#[cfg_attr(dylint_lib = "general", allow(non_local_effect_before_unhandled_error))]
988#[cfg_attr(dylint_lib = "supplementary", allow(commented_out_code))]
989fn clone_repository(pkg: &Package) -> Result<RepoStatus<'_, PathBuf>> {
990    let repo_status = REPOSITORY_CACHE.with_borrow_mut(|repository_cache| -> Result<_> {
991        on_disk_cache::with_cache(|cache| -> Result<_> {
992            // smoelius: Check all urls associated with the package.
993            for url in urls(pkg) {
994                if let Some(repo_status) = repository_cache.get(&url) {
995                    return Ok(repo_status.clone());
996                }
997            }
998            // smoelius: To make verbose printing easier, "membership" is printed regardless of the
999            // check's purpose, and the `Purpose` type was removed.
1000            /* let what = match purpose {
1001                Purpose::Membership => "membership",
1002                Purpose::Timestamp => "timestamp",
1003            }; */
1004            verbose::wrap!(
1005                || {
1006                    let url_and_dir = cache.clone_repository(pkg);
1007                    match url_and_dir {
1008                        Ok((url_string, repo_dir)) => {
1009                            // smoelius: Note the use of `leak` in the next line. But the url is
1010                            // acting as a key in a global map, so it is not so bad.
1011                            let url = Url::from(url_string.as_str()).leak();
1012                            repository_cache
1013                                .insert(url, RepoStatus::Success(url, repo_dir.clone()).leak_url());
1014                            Ok(RepoStatus::Success(url, repo_dir))
1015                        }
1016                        Err(error) => {
1017                            let repo_status = if let Some(url_string) = &pkg.repository {
1018                                let url = url_string.as_str().into();
1019                                // smoelius: If cloning failed because the repository does not
1020                                // exist, adjust the repo status.
1021                                let existence = general_status(&pkg.name, url)?;
1022                                let repo_status = if existence.is_failure() {
1023                                    existence.map_failure()
1024                                } else {
1025                                    RepoStatus::Uncloneable(url)
1026                                };
1027                                warn!("failed to clone `{}`: {}", url_string, error);
1028                                repo_status
1029                            } else {
1030                                RepoStatus::Unnamed
1031                            };
1032                            // smoelius: In the event of failure, set all urls associated with
1033                            // the repository.
1034                            for url in urls(pkg) {
1035                                repository_cache.insert(url.leak(), repo_status.clone().leak_url());
1036                            }
1037                            Ok(repo_status)
1038                        }
1039                    }
1040                },
1041                RepoStatus::to_membership_string,
1042                "membership of `{}` using shallow clone",
1043                pkg.name
1044            )
1045        })
1046    })?;
1047
1048    let Some((url, repo_dir)) = repo_status.as_success() else {
1049        return Ok(repo_status);
1050    };
1051
1052    // smoelius: Even if `purpose` is `Purpose::Timestamp`, verify that `pkg` is a member of the
1053    // repository.
1054    if membership_in_clone(pkg, repo_dir)? {
1055        Ok(repo_status)
1056    } else {
1057        Ok(RepoStatus::Unassociated(url))
1058    }
1059}
1060
1061const LINE_PREFIX: &str = "D  ";
1062
1063fn membership_in_clone(pkg: &Package, repo_dir: &Path) -> Result<bool> {
1064    let mut command = Command::new("git");
1065    command.args(["status", "--porcelain"]);
1066    command.current_dir(repo_dir);
1067    command.stdout(Stdio::piped());
1068    let mut child = command.spawn_wc()?;
1069    #[allow(clippy::unwrap_used)]
1070    let stdout = child.stdout.take().unwrap();
1071    let reader = std::io::BufReader::new(stdout);
1072    for result in reader.lines() {
1073        let line = result.with_context(|| format!("failed to read `{}`", repo_dir.display()))?;
1074        #[allow(clippy::panic)]
1075        let path = line.strip_prefix(LINE_PREFIX).map_or_else(
1076            || panic!("cache is corrupt at `{}`", repo_dir.display()),
1077            Path::new,
1078        );
1079        let filename = path.file_name_wc();
1080        if filename.is_err() || filename.is_ok_and(|s| s != OsStr::new("Cargo.toml")) {
1081            continue;
1082        }
1083        let contents = show(repo_dir, path)?;
1084        let Ok(table) = contents.parse::<Table>()
1085        /* smoelius: This "failed to parse" warning is a little too noisy.
1086        .map_err(|error| {
1087            warn!(
1088                "failed to parse {:?}: {}",
1089                path,
1090                error.to_string().trim_end()
1091            );
1092        }) */
1093        else {
1094            continue;
1095        };
1096        if table
1097            .get("package")
1098            .and_then(Value::as_table)
1099            .and_then(|table| table.get("name"))
1100            .and_then(Value::as_str)
1101            == Some(&pkg.name)
1102        {
1103            return Ok(true);
1104        }
1105    }
1106
1107    Ok(false)
1108}
1109
1110fn show(repo_dir: &Path, path: &Path) -> Result<String> {
1111    let mut command = Command::new("git");
1112    command.args(["show", &format!("HEAD:{}", path.display())]);
1113    command.current_dir(repo_dir);
1114    command.stdout(Stdio::piped());
1115    let output = command.output_wc()?;
1116    if !output.status.success() {
1117        let error = String::from_utf8(output.stderr)?;
1118        bail!(
1119            "failed to read `{}` in `{}`: {}",
1120            path.display(),
1121            repo_dir.display(),
1122            error
1123        );
1124    }
1125    String::from_utf8(output.stdout).map_err(Into::into)
1126}
1127
1128fn display_unmaintained_pkgs(unmaintained_pkgs: &[UnmaintainedPkg]) -> Result<()> {
1129    let mut pkgs_needing_warning = Vec::new();
1130    let mut at_least_one_newer_version_is_available = false;
1131    for unmaintained_pkg in unmaintained_pkgs {
1132        at_least_one_newer_version_is_available |= unmaintained_pkg.newer_version_is_available;
1133        if display_unmaintained_pkg(unmaintained_pkg)? {
1134            pkgs_needing_warning.push(unmaintained_pkg.pkg);
1135        }
1136    }
1137    if at_least_one_newer_version_is_available {
1138        println!(
1139            "\n* a newer (though still seemingly unmaintained) version of the package is available"
1140        );
1141    }
1142    if !pkgs_needing_warning.is_empty() {
1143        warn!(
1144            "the following packages' paths could not be printed:{}",
1145            pkgs_needing_warning
1146                .into_iter()
1147                .map(|pkg| format!("\n    {}@{}", pkg.name, pkg.version))
1148                .collect::<String>()
1149        );
1150    }
1151    Ok(())
1152}
1153
1154#[cfg_attr(dylint_lib = "try_io_result", allow(try_io_result))]
1155fn display_unmaintained_pkg(unmaintained_pkg: &UnmaintainedPkg) -> Result<bool> {
1156    use std::io::Write;
1157    let mut stdout = StandardStream::stdout(opts::get().color);
1158    let UnmaintainedPkg {
1159        pkg,
1160        repo_age,
1161        newer_version_is_available,
1162        outdated_deps,
1163    } = unmaintained_pkg;
1164    stdout.set_color(ColorSpec::new().set_fg(repo_age.color()))?;
1165    write!(stdout, "{}", pkg.name)?;
1166    stdout.set_color(ColorSpec::new().set_fg(None))?;
1167    write!(stdout, " (")?;
1168    repo_age.write(&mut stdout)?;
1169    write!(stdout, ")")?;
1170    if *newer_version_is_available {
1171        write!(stdout, "*")?;
1172    }
1173    writeln!(stdout)?;
1174    for OutdatedDep {
1175        dep,
1176        version_used,
1177        version_latest,
1178    } in outdated_deps
1179    {
1180        println!(
1181            "    {} (requirement: {}, version used: {}, latest: {})",
1182            dep.name, dep.req, version_used, version_latest
1183        );
1184    }
1185    if opts::get().tree {
1186        let need_warning = display_path(&pkg.name, &pkg.version)?;
1187        println!();
1188        Ok(need_warning)
1189    } else {
1190        Ok(false)
1191    }
1192}
1193
1194fn display_path(name: &str, version: &Version) -> Result<bool> {
1195    let spec = format!("{name}@{version}");
1196    let mut command = Command::new("cargo");
1197    command.args(["tree", "--workspace", "--target=all", "--invert", &spec]);
1198    let output = command.output_wc()?;
1199    // smoelius: Hack. It appears that `cargo tree` does not print proc-macros used by proc-macros.
1200    // For now, check whether stdout begins as expected. If not, ignore it and ultimately emit a
1201    // warning.
1202    let stdout = String::from_utf8(output.stdout)?;
1203    if stdout.split_ascii_whitespace().take(2).collect::<Vec<_>>() == [name, &format!("v{version}")]
1204    {
1205        print!("{stdout}");
1206        Ok(false)
1207    } else {
1208        Ok(true)
1209    }
1210}
1211
1212#[cfg(all(feature = "crates-index", not(feature = "tame-index")))]
1213static INDEX_PATH: LazyLock<PathBuf> = LazyLock::new(|| {
1214    #[allow(clippy::unwrap_used)]
1215    let cargo_home = cargo_home().unwrap();
1216    cargo_home.join("registry/index")
1217});
1218
1219#[cfg(all(feature = "crates-index", not(feature = "tame-index")))]
1220fn lock_index() -> Result<File> {
1221    flock::lock_path(&INDEX_PATH)
1222        .with_context(|| format!("failed to lock `{}`", INDEX_PATH.display()))
1223}
1224
1225#[cfg(test)]
1226mod tests {
1227    use super::*;
1228    use assert_cmd::prelude::*;
1229    use clap::CommandFactory;
1230
1231    #[test]
1232    fn verify_cli() {
1233        Opts::command().debug_assert();
1234    }
1235
1236    #[cfg_attr(dylint_lib = "general", allow(non_thread_safe_call_in_test))]
1237    #[test]
1238    fn usage() {
1239        std::process::Command::new("cargo")
1240            .args([
1241                "run",
1242                "--bin=cargo-unmaintained",
1243                "--",
1244                "unmaintained",
1245                "--help",
1246            ])
1247            .assert()
1248            .success()
1249            .stdout(predicates::str::contains("Usage: cargo unmaintained"));
1250    }
1251
1252    #[cfg_attr(dylint_lib = "general", allow(non_thread_safe_call_in_test))]
1253    #[test]
1254    fn version() {
1255        std::process::Command::new("cargo")
1256            .args([
1257                "run",
1258                "--bin=cargo-unmaintained",
1259                "--",
1260                "unmaintained",
1261                "--version",
1262            ])
1263            .assert()
1264            .success()
1265            .stdout(concat!(
1266                "cargo-unmaintained ",
1267                env!("CARGO_PKG_VERSION"),
1268                "\n"
1269            ));
1270    }
1271
1272    #[test]
1273    fn repo_status_ord() {
1274        let ys = vec![
1275            RepoStatus::Uncloneable("f".into()),
1276            RepoStatus::Unnamed,
1277            RepoStatus::Success("e".into(), 0),
1278            RepoStatus::Success("d".into(), 1),
1279            RepoStatus::Unassociated("c".into()),
1280            RepoStatus::Nonexistent("b".into()),
1281            RepoStatus::Archived("a".into()),
1282        ];
1283        let mut xs = ys.clone();
1284        xs.sort_by_key(|repo_status| repo_status.erase_url());
1285        assert_eq!(xs, ys);
1286    }
1287}