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 = metadata_command();
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 = metadata_command().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 metadata_command() -> MetadataCommand {
640    let mut command = MetadataCommand::new();
641    // smoelius: Note that `other_options` replaces previous options; it does not add to them. So if
642    // additional options are needed, they must be added here.
643    if !opts::get().all_targets {
644        command.other_options(["--filter-platform".to_owned(), HOST.clone()]);
645    }
646    command
647}
648
649#[allow(clippy::panic, clippy::unwrap_used)]
650static HOST: LazyLock<String> = LazyLock::new(|| {
651    let mut command = Command::new("rustc");
652    command.arg("-Vv");
653    let output = command.output_wc().unwrap();
654    assert!(output.status.success(), "command failed: {command:?}");
655    let stdout = String::from_utf8(output.stdout).unwrap();
656    stdout
657        .lines()
658        .find_map(|line| line.strip_prefix("host: "))
659        .map_or_else(|| panic!("failed to determine host"), str::to_owned)
660});
661
662fn is_unmaintained_package<'a>(
663    metadata: &'a Metadata,
664    pkg: &'a Package,
665) -> Result<Option<UnmaintainedPkg<'a>>> {
666    if let Some(url_string) = &pkg.repository {
667        let can_use_github_api =
668            TOKEN_FOUND.load(Ordering::SeqCst) && url_string.starts_with("https://github.com/");
669
670        let url = url_string.as_str().into();
671
672        if can_use_github_api {
673            let repo_status = general_status(&pkg.name, url)?;
674            if repo_status.is_failure() {
675                return Ok(Some(UnmaintainedPkg {
676                    pkg,
677                    repo_age: repo_status.map_failure(),
678                    newer_version_is_available: false,
679                    outdated_deps: Vec::new(),
680                }));
681            }
682        }
683
684        let repo_status = clone_repository(pkg)?;
685        if repo_status.is_failure() {
686            // smoelius: Mercurial repos get a pass.
687            if matches!(repo_status, RepoStatus::Uncloneable(_)) && curl::is_mercurial_repo(url)? {
688                return Ok(None);
689            }
690            return Ok(Some(UnmaintainedPkg {
691                pkg,
692                repo_age: repo_status.map_failure(),
693                newer_version_is_available: false,
694                outdated_deps: Vec::new(),
695            }));
696        }
697    }
698
699    let outdated_deps = outdated_deps(metadata, pkg)?;
700
701    if outdated_deps.is_empty() {
702        return Ok(None);
703    }
704
705    let repo_age = latest_commit_age(pkg)?;
706
707    if repo_age
708        .as_success()
709        .is_some_and(|(_, &age)| age < opts::get().max_age * SECS_PER_DAY)
710    {
711        return Ok(None);
712    }
713
714    Ok(Some(UnmaintainedPkg {
715        pkg,
716        repo_age,
717        newer_version_is_available: false,
718        outdated_deps,
719    }))
720}
721
722fn general_status(name: &str, url: Url) -> Result<RepoStatus<'static, ()>> {
723    GENERAL_STATUS_CACHE.with_borrow_mut(|general_status_cache| {
724        if let Some(&value) = general_status_cache.get(&url) {
725            return Ok(value);
726        }
727        let to_string: &dyn Fn(&RepoStatus<'static, ()>) -> String;
728        let (use_github_api, what, how) = if TOKEN_FOUND.load(Ordering::SeqCst)
729            && url.as_str().starts_with("https://github.com/")
730        {
731            to_string = &RepoStatus::to_archival_status_string;
732            (true, "archival status", "GitHub API")
733        } else {
734            to_string = &RepoStatus::to_existence_string;
735            (false, "existence", "HTTP request")
736        };
737        verbose::wrap!(
738            || {
739                let repo_status = if use_github_api {
740                    Github::archival_status(url)
741                } else {
742                    curl::existence(url)
743                }
744                .unwrap_or_else(|error| {
745                    warn!("failed to determine `{}` {}: {}", name, what, error);
746                    RepoStatus::Success(url, ())
747                })
748                .leak_url();
749                general_status_cache.insert(url.leak(), repo_status);
750                Ok(repo_status)
751            },
752            to_string,
753            "{} of `{}` using {}",
754            what,
755            name,
756            how
757        )
758    })
759}
760
761#[allow(clippy::unnecessary_wraps)]
762fn outdated_deps<'a>(metadata: &'a Metadata, pkg: &'a Package) -> Result<Vec<OutdatedDep<'a>>> {
763    if !published(pkg) {
764        return Ok(Vec::new());
765    }
766    let mut deps = Vec::new();
767    for dep in &pkg.dependencies {
768        // smoelius: Don't check dependencies in private registries.
769        if dep.registry.is_some() {
770            continue;
771        }
772        // smoelius: Don't check dependencies specified by path.
773        if dep.path.is_some() {
774            continue;
775        }
776        if dep.kind == DependencyKind::Development {
777            continue;
778        }
779        let Some(dep_pkg) = resolved_package(metadata, pkg, dep) else {
780            // smoelius: An unresolved dependency must either be optional and disabled or have been
781            // excluded by `--filter-platform`. Note that this assertion does not flag
782            // platform-gated dependencies that apply to the host but fail to resolve. Flagging
783            // those would require the host's `cfg`s and use of, e.g., `Platform::matches`.
784            debug_assert!(
785                dep.optional || (!opts::get().all_targets && dep.target.is_some()),
786                "failed for: {dep:?}"
787            );
788            continue;
789        };
790        let Ok(version_latest) = latest_version(&dep.name).map_err(|error| {
791            // smoelius: I don't understand why a package can fail to be in the index, but I have
792            // seen it happen.
793            warn!("failed to get latest version of `{}`: {}", dep.name, error);
794        }) else {
795            continue;
796        };
797        if dep_pkg.version <= version_latest && !dep.req.matches(&version_latest) {
798            let versions = versions(&dep_pkg.name)?;
799            // smoelius: Require at least one incompatible version of the dependency that is more
800            // than `max_age` days old.
801            if versions
802                .iter()
803                .try_fold(false, |init, version| -> Result<_> {
804                    if init {
805                        return Ok(true);
806                    }
807                    let duration =
808                        SystemTime::now().duration_since_wc(version.created_at.into())?;
809                    let version_num = Version::parse(&version.num)?;
810                    Ok(duration.as_secs() >= opts::get().max_age * SECS_PER_DAY
811                        && dep_pkg.version <= version_num
812                        && !dep.req.matches(&version_num))
813                })?
814            {
815                deps.push(OutdatedDep {
816                    dep,
817                    version_used: &dep_pkg.version,
818                    version_latest,
819                });
820            }
821        }
822    }
823    // smoelius: A dependency could appear more than once, e.g., because it is used with different
824    // features as a normal and as a development dependency.
825    deps.dedup_by(|lhs, rhs| lhs.dep.name == rhs.dep.name && lhs.dep.req == rhs.dep.req);
826    Ok(deps)
827}
828
829fn published(pkg: &Package) -> bool {
830    pkg.publish.as_deref() != Some(&[])
831}
832
833fn resolved_package<'a>(
834    metadata: &'a Metadata,
835    pkg: &Package,
836    dep: &Dependency,
837) -> Option<&'a Package> {
838    let resolve = metadata.resolve.as_ref()?;
839    let node = resolve.nodes.iter().find(|node| pkg.id == node.id)?;
840    node.deps
841        .iter()
842        .filter(|node_dep| {
843            node_dep
844                .dep_kinds
845                .iter()
846                .any(|dep_kind| dep.kind == dep_kind.kind && dep.target == dep_kind.target)
847        })
848        .find_map(|node_dep| {
849            metadata.packages.iter().find(|dep_pkg| {
850                node_dep.pkg == dep_pkg.id
851                    && dep.name.as_str() == dep_pkg.name.as_str()
852                    && dep.req.matches(&dep_pkg.version)
853            })
854        })
855}
856
857fn latest_version(name: &str) -> Result<Version> {
858    LATEST_VERSION_CACHE.with_borrow_mut(|latest_version_cache| {
859        if let Some(version) = latest_version_cache.get(name) {
860            return Ok(version.clone());
861        }
862        verbose::wrap!(
863            || {
864                #[cfg(all(feature = "crates-index", not(feature = "tame-index")))]
865                let latest_version = {
866                    let krate = INDEX.with(|index| {
867                        let _ = LazyLock::force(index);
868                        let _lock = lock_index()?;
869                        index
870                            .crate_(name)
871                            .ok_or_else(|| anyhow!("failed to find `{name}` in index"))
872                    })?;
873                    let latest_version_index = krate
874                        .highest_normal_version()
875                        .ok_or_else(|| anyhow!("`{name}` has no normal version"))?;
876                    Version::from_str(latest_version_index.version())?
877                };
878                #[cfg(feature = "tame-index")]
879                let latest_version = {
880                    let krate_name = KrateName::crates_io(name)
881                        .map_err(|e| anyhow!("invalid crate name `{name}`: {e}"))?;
882                    let lock_options = LockOptions::cargo_package_lock(None)
883                        .map_err(|e| anyhow!("failed to create cargo package lock: {e}"))?;
884                    let lock = lock_options
885                        .lock(|_| None)
886                        .map_err(|e| anyhow!("failed to acquire cargo package lock: {e}"))?;
887                    let krate = INDEX.with(|index| {
888                        let _ = LazyLock::force(index);
889                        let krate = index
890                            .krate(krate_name, true, &lock)
891                            .map_err(|e| anyhow!("failed to fetch `{name}` from index: {e}"))?;
892                        krate.ok_or_else(|| anyhow!("failed to find `{name}` in index"))
893                    })?;
894                    let latest_version_index = krate
895                        .highest_normal_version()
896                        .ok_or_else(|| anyhow!("`{name}` has no normal version"))?;
897                    Version::from_str(&latest_version_index.version)?
898                };
899                latest_version_cache.insert(name.to_owned(), latest_version.clone());
900                Ok(latest_version)
901            },
902            ToString::to_string,
903            "latest version of `{}` using crates.io index",
904            name
905        )
906    })
907}
908
909fn versions(name: &str) -> Result<Vec<crates_io_api::Version>> {
910    on_disk_cache::with_cache(|cache| -> Result<_> {
911        verbose::wrap!(
912            || { cache.fetch_versions(name) },
913            |versions: &[crates_io_api::Version]| format!("{} versions", versions.len()),
914            "versions of `{}` using crates.io API",
915            name
916        )
917    })
918}
919
920fn latest_commit_age(pkg: &Package) -> Result<RepoStatus<'_, u64>> {
921    let repo_status = timestamp(pkg)?;
922
923    repo_status
924        .map(|timestamp| {
925            let duration = SystemTime::now().duration_since_wc(timestamp)?;
926
927            Ok(duration.as_secs())
928        })
929        .transpose()
930}
931
932fn timestamp(pkg: &Package) -> Result<RepoStatus<'_, SystemTime>> {
933    TIMESTAMP_CACHE.with_borrow_mut(|timestamp_cache| {
934        // smoelius: Check both the regular and the shortened url.
935        for url in urls(pkg) {
936            if let Some(&repo_status) = timestamp_cache.get(&url) {
937                // smoelius: If a previous attempt to timestamp the repository failed (e.g., because
938                // of spurious network errors), then don't bother checking the repository cache.
939                let Some((url_timestamped, &timestamp)) = repo_status.as_success() else {
940                    return Ok(repo_status);
941                };
942                assert_eq!(url, url_timestamped);
943                // smoelius: `pkg`'s repository could contain other packages that were already
944                // timestamped. Thus, `pkg`'s repository could already be in the timestamp cache.
945                // But in that case, we still need to verify that `pkg` appears in its repository.
946                let repo_status = clone_repository(pkg)?;
947                let Some((url_cloned, _)) = repo_status.as_success() else {
948                    return Ok(repo_status.map_failure());
949                };
950                assert_eq!(url, url_cloned);
951                return Ok(RepoStatus::Success(url, timestamp));
952            }
953        }
954        let repo_status = timestamp_uncached(pkg)?;
955        if let Some((url, _)) = repo_status.as_success() {
956            timestamp_cache.insert(url.leak(), repo_status.leak_url());
957        } else {
958            // smoelius: In the event of failure, set all urls associated with the
959            // repository.
960            for url in urls(pkg) {
961                timestamp_cache.insert(url.leak(), repo_status.leak_url());
962            }
963        }
964        Ok(repo_status)
965    })
966}
967
968fn timestamp_uncached(pkg: &Package) -> Result<RepoStatus<'_, SystemTime>> {
969    if pkg.repository.is_none() {
970        return Ok(RepoStatus::Unnamed);
971    }
972
973    timestamp_from_clone(pkg)
974}
975
976fn timestamp_from_clone(pkg: &Package) -> Result<RepoStatus<'_, SystemTime>> {
977    let repo_status = clone_repository(pkg)?;
978
979    let Some((url, repo_dir)) = repo_status.as_success() else {
980        return Ok(repo_status.map_failure());
981    };
982
983    let mut command = Command::new("git");
984    command
985        .args(["log", "-1", "--pretty=format:%ct"])
986        .current_dir(repo_dir);
987    let output = command.output_wc()?;
988    ensure!(output.status.success(), "command failed: {command:?}");
989
990    let stdout = std::str::from_utf8(&output.stdout)?;
991    let secs = u64::from_str(stdout.trim_end())?;
992    let timestamp = SystemTime::UNIX_EPOCH + Duration::from_secs(secs);
993
994    Ok(RepoStatus::Success(url, timestamp))
995}
996
997#[cfg_attr(dylint_lib = "general", allow(non_local_effect_before_unhandled_error))]
998#[cfg_attr(dylint_lib = "supplementary", allow(commented_out_code))]
999fn clone_repository(pkg: &Package) -> Result<RepoStatus<'_, PathBuf>> {
1000    let repo_status = REPOSITORY_CACHE.with_borrow_mut(|repository_cache| -> Result<_> {
1001        on_disk_cache::with_cache(|cache| -> Result<_> {
1002            // smoelius: Check all urls associated with the package.
1003            for url in urls(pkg) {
1004                if let Some(repo_status) = repository_cache.get(&url) {
1005                    return Ok(repo_status.clone());
1006                }
1007            }
1008            // smoelius: To make verbose printing easier, "membership" is printed regardless of the
1009            // check's purpose, and the `Purpose` type was removed.
1010            /* let what = match purpose {
1011                Purpose::Membership => "membership",
1012                Purpose::Timestamp => "timestamp",
1013            }; */
1014            verbose::wrap!(
1015                || {
1016                    let url_and_dir = cache.clone_repository(pkg);
1017                    match url_and_dir {
1018                        Ok((url_string, repo_dir)) => {
1019                            // smoelius: Note the use of `leak` in the next line. But the url is
1020                            // acting as a key in a global map, so it is not so bad.
1021                            let url = Url::from(url_string.as_str()).leak();
1022                            repository_cache
1023                                .insert(url, RepoStatus::Success(url, repo_dir.clone()).leak_url());
1024                            Ok(RepoStatus::Success(url, repo_dir))
1025                        }
1026                        Err(error) => {
1027                            let repo_status = if let Some(url_string) = &pkg.repository {
1028                                let url = url_string.as_str().into();
1029                                // smoelius: If cloning failed because the repository does not
1030                                // exist, adjust the repo status.
1031                                let existence = general_status(&pkg.name, url)?;
1032                                let repo_status = if existence.is_failure() {
1033                                    existence.map_failure()
1034                                } else {
1035                                    RepoStatus::Uncloneable(url)
1036                                };
1037                                warn!("failed to clone `{}`: {}", url_string, error);
1038                                repo_status
1039                            } else {
1040                                RepoStatus::Unnamed
1041                            };
1042                            // smoelius: In the event of failure, set all urls associated with
1043                            // the repository.
1044                            for url in urls(pkg) {
1045                                repository_cache.insert(url.leak(), repo_status.clone().leak_url());
1046                            }
1047                            Ok(repo_status)
1048                        }
1049                    }
1050                },
1051                RepoStatus::to_membership_string,
1052                "membership of `{}` using shallow clone",
1053                pkg.name
1054            )
1055        })
1056    })?;
1057
1058    let Some((url, repo_dir)) = repo_status.as_success() else {
1059        return Ok(repo_status);
1060    };
1061
1062    // smoelius: Even if `purpose` is `Purpose::Timestamp`, verify that `pkg` is a member of the
1063    // repository.
1064    if membership_in_clone(pkg, repo_dir)? {
1065        Ok(repo_status)
1066    } else {
1067        Ok(RepoStatus::Unassociated(url))
1068    }
1069}
1070
1071const LINE_PREFIX: &str = "D  ";
1072
1073fn membership_in_clone(pkg: &Package, repo_dir: &Path) -> Result<bool> {
1074    let mut command = Command::new("git");
1075    command.args(["status", "--porcelain"]);
1076    command.current_dir(repo_dir);
1077    command.stdout(Stdio::piped());
1078    let mut child = command.spawn_wc()?;
1079    #[allow(clippy::unwrap_used)]
1080    let stdout = child.stdout.take().unwrap();
1081    let reader = std::io::BufReader::new(stdout);
1082    for result in reader.lines() {
1083        let line = result.with_context(|| format!("failed to read `{}`", repo_dir.display()))?;
1084        #[allow(clippy::panic)]
1085        let path = line.strip_prefix(LINE_PREFIX).map_or_else(
1086            || panic!("cache is corrupt at `{}`", repo_dir.display()),
1087            Path::new,
1088        );
1089        let filename = path.file_name_wc();
1090        if filename.is_err() || filename.is_ok_and(|s| s != OsStr::new("Cargo.toml")) {
1091            continue;
1092        }
1093        let contents = show(repo_dir, path)?;
1094        let Ok(table) = contents.parse::<Table>()
1095        /* smoelius: This "failed to parse" warning is a little too noisy.
1096        .map_err(|error| {
1097            warn!(
1098                "failed to parse {:?}: {}",
1099                path,
1100                error.to_string().trim_end()
1101            );
1102        }) */
1103        else {
1104            continue;
1105        };
1106        if table
1107            .get("package")
1108            .and_then(Value::as_table)
1109            .and_then(|table| table.get("name"))
1110            .and_then(Value::as_str)
1111            == Some(&pkg.name)
1112        {
1113            return Ok(true);
1114        }
1115    }
1116
1117    Ok(false)
1118}
1119
1120fn show(repo_dir: &Path, path: &Path) -> Result<String> {
1121    let mut command = Command::new("git");
1122    command.args(["show", &format!("HEAD:{}", path.display())]);
1123    command.current_dir(repo_dir);
1124    command.stdout(Stdio::piped());
1125    let output = command.output_wc()?;
1126    if !output.status.success() {
1127        let error = String::from_utf8(output.stderr)?;
1128        bail!(
1129            "failed to read `{}` in `{}`: {}",
1130            path.display(),
1131            repo_dir.display(),
1132            error
1133        );
1134    }
1135    String::from_utf8(output.stdout).map_err(Into::into)
1136}
1137
1138fn display_unmaintained_pkgs(unmaintained_pkgs: &[UnmaintainedPkg]) -> Result<()> {
1139    let mut pkgs_needing_warning = Vec::new();
1140    let mut at_least_one_newer_version_is_available = false;
1141    for unmaintained_pkg in unmaintained_pkgs {
1142        at_least_one_newer_version_is_available |= unmaintained_pkg.newer_version_is_available;
1143        if display_unmaintained_pkg(unmaintained_pkg)? {
1144            pkgs_needing_warning.push(unmaintained_pkg.pkg);
1145        }
1146    }
1147    if at_least_one_newer_version_is_available {
1148        println!(
1149            "\n* a newer (though still seemingly unmaintained) version of the package is available"
1150        );
1151    }
1152    if !pkgs_needing_warning.is_empty() {
1153        warn!(
1154            "the following packages' paths could not be printed:{}",
1155            pkgs_needing_warning
1156                .into_iter()
1157                .map(|pkg| format!("\n    {}@{}", pkg.name, pkg.version))
1158                .collect::<String>()
1159        );
1160    }
1161    Ok(())
1162}
1163
1164#[cfg_attr(dylint_lib = "try_io_result", allow(try_io_result))]
1165fn display_unmaintained_pkg(unmaintained_pkg: &UnmaintainedPkg) -> Result<bool> {
1166    use std::io::Write;
1167    let mut stdout = StandardStream::stdout(opts::get().color);
1168    let UnmaintainedPkg {
1169        pkg,
1170        repo_age,
1171        newer_version_is_available,
1172        outdated_deps,
1173    } = unmaintained_pkg;
1174    stdout.set_color(ColorSpec::new().set_fg(repo_age.color()))?;
1175    write!(stdout, "{}", pkg.name)?;
1176    stdout.set_color(ColorSpec::new().set_fg(None))?;
1177    write!(stdout, " (")?;
1178    repo_age.write(&mut stdout)?;
1179    write!(stdout, ")")?;
1180    if *newer_version_is_available {
1181        write!(stdout, "*")?;
1182    }
1183    writeln!(stdout)?;
1184    for OutdatedDep {
1185        dep,
1186        version_used,
1187        version_latest,
1188    } in outdated_deps
1189    {
1190        println!(
1191            "    {} (requirement: {}, version used: {}, latest: {})",
1192            dep.name, dep.req, version_used, version_latest
1193        );
1194    }
1195    if opts::get().tree {
1196        let need_warning = display_path(&pkg.name, &pkg.version)?;
1197        println!();
1198        Ok(need_warning)
1199    } else {
1200        Ok(false)
1201    }
1202}
1203
1204fn display_path(name: &str, version: &Version) -> Result<bool> {
1205    let spec = format!("{name}@{version}");
1206    let mut command = Command::new("cargo");
1207    command.args(["tree", "--workspace"]);
1208    if opts::get().all_targets {
1209        command.arg("--target=all");
1210    } else {
1211        command.args(["--target", HOST.as_str()]);
1212    }
1213    command.args(["--invert", &spec]);
1214    let output = command.output_wc()?;
1215    // smoelius: Hack. It appears that `cargo tree` does not print proc-macros used by proc-macros.
1216    // For now, check whether stdout begins as expected. If not, ignore it and ultimately emit a
1217    // warning.
1218    let stdout = String::from_utf8(output.stdout)?;
1219    if stdout.split_ascii_whitespace().take(2).collect::<Vec<_>>() == [name, &format!("v{version}")]
1220    {
1221        print!("{stdout}");
1222        Ok(false)
1223    } else {
1224        Ok(true)
1225    }
1226}
1227
1228#[cfg(all(feature = "crates-index", not(feature = "tame-index")))]
1229static INDEX_PATH: LazyLock<PathBuf> = LazyLock::new(|| {
1230    #[allow(clippy::unwrap_used)]
1231    let cargo_home = cargo_home().unwrap();
1232    cargo_home.join("registry/index")
1233});
1234
1235#[cfg(all(feature = "crates-index", not(feature = "tame-index")))]
1236fn lock_index() -> Result<File> {
1237    flock::lock_path(&INDEX_PATH)
1238        .with_context(|| format!("failed to lock `{}`", INDEX_PATH.display()))
1239}
1240
1241#[cfg(test)]
1242mod tests {
1243    use super::*;
1244    use assert_cmd::prelude::*;
1245    use clap::CommandFactory;
1246
1247    #[test]
1248    fn verify_cli() {
1249        Opts::command().debug_assert();
1250    }
1251
1252    #[cfg_attr(dylint_lib = "general", allow(non_thread_safe_call_in_test))]
1253    #[test]
1254    fn usage() {
1255        std::process::Command::new("cargo")
1256            .args([
1257                "run",
1258                "--bin=cargo-unmaintained",
1259                "--",
1260                "unmaintained",
1261                "--help",
1262            ])
1263            .assert()
1264            .success()
1265            .stdout(predicates::str::contains("Usage: cargo unmaintained"));
1266    }
1267
1268    #[cfg_attr(dylint_lib = "general", allow(non_thread_safe_call_in_test))]
1269    #[test]
1270    fn version() {
1271        std::process::Command::new("cargo")
1272            .args([
1273                "run",
1274                "--bin=cargo-unmaintained",
1275                "--",
1276                "unmaintained",
1277                "--version",
1278            ])
1279            .assert()
1280            .success()
1281            .stdout(concat!(
1282                "cargo-unmaintained ",
1283                env!("CARGO_PKG_VERSION"),
1284                "\n"
1285            ));
1286    }
1287
1288    #[test]
1289    fn repo_status_ord() {
1290        let ys = vec![
1291            RepoStatus::Uncloneable("f".into()),
1292            RepoStatus::Unnamed,
1293            RepoStatus::Success("e".into(), 0),
1294            RepoStatus::Success("d".into(), 1),
1295            RepoStatus::Unassociated("c".into()),
1296            RepoStatus::Nonexistent("b".into()),
1297            RepoStatus::Archived("a".into()),
1298        ];
1299        let mut xs = ys.clone();
1300        xs.sort_by_key(|repo_status| repo_status.erase_url());
1301        assert_eq!(xs, ys);
1302    }
1303}