cargo-crev 0.27.1

Distributed Code REView system for verifying security and quality of Cargo dependencies
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
// Here are the structs and functions which still need to be sorted
//
use crate::{
    deps::scan::{self, RequiredDetails},
    edit, opts,
    opts::{CrateSelector, ReviewCrateSelector},
    prelude::*,
    repo::Repo,
};
use anyhow::{Context, Result, format_err};
use crev_data::{SOURCE_CRATES_IO, proof, review::Package};
use crev_lib::{self, ProofStore, ReviewMode, local::Local};
use serde::Deserialize;
use std::{
    collections::HashSet,
    env,
    ffi::{OsStr, OsString},
    io,
    path::{Path, PathBuf},
    process,
};

/// Name of ENV with original location `crev goto` was called from
pub const GOTO_ORIGINAL_DIR_ENV: &str = "CARGO_CREV_GOTO_ORIGINAL_DIR";
/// Name of ENV with name of the crate that we've `goto`ed to
pub const GOTO_CRATE_NAME_ENV: &str = "CARGO_CREV_GOTO_ORIGINAL_NAME";
/// Name of ENV with version of the crate that we've `goto`ed to
pub const GOTO_CRATE_VERSION_ENV: &str = "CARGO_CREV_GOTO_ORIGINAL_VERSION";

/// Name of file we store user-personalized
pub const KNOWN_CARGO_OWNERS_FILE: &str = "known_cargo_owners.txt";

/// The file added to crates containing vcs revision
pub const VCS_INFO_JSON_FILE: &str = ".cargo_vcs_info.json";

/// Data from `.cargo_vcs_info.json`
#[derive(Debug, Clone, Deserialize)]
pub struct VcsInfoJson {
    git: VcsInfoJsonGit,
}

pub fn vcs_info_to_revision_string(vcs: Option<VcsInfoJson>) -> String {
    vcs.map(|vcs| vcs.get_git_revision()).unwrap_or_default()
}

#[derive(Debug, Clone, Deserialize)]
pub enum VcsInfoJsonGit {
    #[serde(rename = "sha1")]
    Sha1(String),
}

impl VcsInfoJson {
    fn read_from_crate_dir(pkg_dir: &Path) -> Result<Option<Self>> {
        let path = pkg_dir.join(VCS_INFO_JSON_FILE);

        if path.exists() {
            let txt = std::fs::read_to_string(&path)?;
            let info: VcsInfoJson = serde_json::from_str(&txt)?;
            Ok(Some(info))
        } else {
            Ok(None)
        }
    }
    fn get_git_revision(&self) -> String {
        let VcsInfoJsonGit::Sha1(ref s) = self.git;
        s.to_string()
    }
}

/// Ignore things that are commonly added during the review (eg. by RLS)
pub fn cargo_full_ignore_list(ignore_cargo_lock: bool) -> fnv::FnvHashSet<PathBuf> {
    let mut ignore_list = HashSet::default();
    ignore_list.insert(PathBuf::from(".cargo-ok"));
    ignore_list.insert(PathBuf::from("target"));
    if ignore_cargo_lock {
        ignore_list.insert(PathBuf::from("Cargo.lock"));
    }

    ignore_list
}

/// Ignore only the marker added by `cargo` after fully downloading and extracting crate
pub fn cargo_min_ignore_list() -> fnv::FnvHashSet<PathBuf> {
    let mut ignore_list = HashSet::default();
    ignore_list.insert(PathBuf::from(".cargo-ok"));
    ignore_list
}

#[cfg(target_family = "unix")]
// on Unix we use `exec` so that stuff like Ctrl-C works
// we don't care about destructors at this point
pub fn exec_into(mut command: process::Command) -> Result<()> {
    use std::os::unix::process::CommandExt;
    bail!(command.exec());
}

#[cfg(target_family = "windows")]
// TODO: Is this the way to do it in Windows?
pub fn exec_into(mut command: process::Command) -> Result<()> {
    let status = command.status()?;
    if !status.success() {
        bail!("Shell returned {}", status);
    }
    Ok(())
}

/// `cd` into crate source code and start shell
///
/// Set some `envs` to help other commands work
/// from inside such a "review-shell".
pub fn goto_crate_src(selector: &opts::CrateSelector) -> Result<()> {
    if env::var(GOTO_ORIGINAL_DIR_ENV).is_ok() {
        bail!("You're already in a `cargo crev goto` shell");
    };
    let repo = Repo::auto_open_cwd_default()?;
    selector.ensure_name_given()?;

    let crate_id = repo.find_pkgid_by_crate_selector(selector)?;
    let crate_ = repo.get_crate(&crate_id)?;
    let crate_dir = crate_.root();
    let crate_name = crate_.name();
    let crate_version = crate_.version();
    let local = crev_lib::Local::auto_create_or_open()?;
    local.record_review_activity(
        SOURCE_CRATES_IO,
        &crate_.name(),
        crate_version,
        &crev_lib::ReviewActivity::new(None),
    )?;

    let shell = env::var_os("SHELL").ok_or_else(|| format_err!("$SHELL not set"))?;
    let cwd = env::current_dir()?;

    eprintln!("Opening shell in: {}", crate_dir.display());
    eprintln!("Use `exit` or Ctrl-D to return to the original project.",);
    eprintln!("Use `cargo crev review` without any arguments to review this crate.");
    let mut command = process::Command::new(shell);
    command
        .current_dir(crate_dir)
        .env("PWD", crate_dir)
        .env(GOTO_ORIGINAL_DIR_ENV, cwd)
        .env(GOTO_CRATE_NAME_ENV, crate_name)
        .env(GOTO_CRATE_VERSION_ENV, crate_version.to_string());

    exec_into(command)
}

pub fn expand_crate_src(selector: &opts::CrateSelector) -> Result<()> {
    use quote::ToTokens;

    let repo = Repo::auto_open_cwd_default()?;
    selector.ensure_name_given()?;
    let crate_id = repo.find_pkgid_by_crate_selector(selector)?;
    let crate_ = repo.get_crate(&crate_id)?;
    let crate_dir = crate_.root();

    // TODO: discover all the entrypoint, iterate over them, take care of formatting and
    // comments
    println!(
        "{}",
        syn_inline_mod::parse_and_inline_modules(&crate_dir.join("src/lib.rs")).into_token_stream()
    );

    Ok(())
}

pub fn ensure_known_owners_list_exists(local: &crev_lib::Local) -> Result<()> {
    let path = local.get_proofs_dir_path()?.join(KNOWN_CARGO_OWNERS_FILE);
    if !path.exists() {
        crev_common::store_str_to_file(&path, include_str!("known_cargo_owners_defaults.txt"))?;
        local.proof_dir_git_add_path(&PathBuf::from(KNOWN_CARGO_OWNERS_FILE))?;
    }

    Ok(())
}

pub fn read_known_owners_list() -> Result<HashSet<String>> {
    let local = Local::auto_create_or_open()?;
    let content = if let Some(path) = local.get_proofs_dir_path_opt()? {
        let path = path.join(KNOWN_CARGO_OWNERS_FILE);
        std::fs::read_to_string(path)?
    } else {
        include_str!("known_cargo_owners_defaults.txt").to_string()
    };
    Ok(content
        .lines()
        .map(str::trim)
        .filter(|s| !s.starts_with('#'))
        .map(ToString::to_string)
        .collect())
}

pub fn edit_known_owners_list() -> Result<()> {
    let local = Local::auto_create_or_open()?;
    let path = local.get_proofs_dir_path()?.join(KNOWN_CARGO_OWNERS_FILE);
    ensure_known_owners_list_exists(&local)?;
    edit::edit_file(&path)?;
    Ok(())
}

pub fn clean_all_crates_with_digest_mismatch() -> Result<()> {
    let scanner = scan::Scanner::new(CrateSelector::default(), &opts::CrateVerify::default())?;
    let events = scanner.run(&RequiredDetails::none());

    for stats in events {
        if stats.details.accumulative_own.is_local_source_code {
            continue;
        }
        if stats.has_digest_mismatch() {
            clean_crate(&CrateSelector::new(
                Some(stats.info.id.name().to_string()),
                Some(stats.info.id.version().clone()),
                false,
            ))?;
        }
    }

    Ok(())
}

/// Wipe the crate source, then re-download it
pub fn clean_crate(selector: &CrateSelector) -> Result<()> {
    let repo = Repo::auto_open_cwd_default()?;
    let crate_id = repo.find_pkgid_by_crate_selector(selector)?;
    let crate_ = repo.get_crate(&crate_id)?;
    assert!(crate_.package_id().source_id().is_registry());
    let crate_root = crate_.root();

    assert!(crate_root.is_absolute());
    assert!(
        !std::env::current_dir()?.starts_with(crate_root),
        "Cannot delete {} while inside that directory.",
        crate_root.display(),
    );

    if crate_root.is_dir() {
        std::fs::remove_dir_all(crate_root)?;
    }
    let _crate_ = repo.get_crate(&crate_id)?;
    Ok(())
}

pub fn get_open_cmd(local: &Local) -> Result<String> {
    let config = local
        .load_user_config()
        .with_context(|| "Can't open user config")?;
    if let Some(cmd) = config.open_cmd {
        return Ok(cmd);
    }

    Ok(if cfg!(target_os = "windows") {
        "start"
    } else if cfg!(target_os = "macos") {
        "open"
    } else if cfg!(target_os = "linux") {
        "xdg-open"
    } else {
        eprintln!("Unsupported platform. Please submit a PR!");
        "xdg-open"
    }
    .into())
}

/// Open a crate
///
/// * `unrelated` - the crate might not actually be a dependency
pub fn crate_open(
    crate_sel: &ReviewCrateSelector,
    cmd: Option<String>,
    cmd_save: bool,
) -> Result<()> {
    let local = Local::auto_create_or_open()?;
    let repo = Repo::auto_open_cwd_default()?;
    let crate_id = repo.find_pkgid_by_crate_selector(&crate_sel.crate_)?;
    let cargo_crate = repo.get_crate(&crate_id)?;

    if let Some(Some(base_ver)) = &crate_sel.diff {
        println!(
            "View the diff online:\nhttps://diff.rs/{name}/{base_ver}/{name}/{new_ver}/Cargo.toml\n",
            name = cargo_crate.name(),
            new_ver = cargo_crate.version(),
        );
    }

    if cmd_save {
        if let Some(cmd) = &cmd {
            local.store_config_open_cmd(cmd.clone())?;
        } else {
            bail!("Can't save cmd without specifying it");
        }
    }

    let name = cargo_crate.name().to_string();
    let version = cargo_crate.version();
    let src_dir = cargo_crate.root();

    // It's not safe to open Cargo's crate dir directly, because editor integration (like cargo check)
    // could automatically start running crate's potentially malicious build script or proc macros.
    let dest_dir = local.sanitized_crate_copy(SOURCE_CRATES_IO, &name, version, src_dir)?;

    let open_cmd = match cmd {
        Some(cmd) => cmd,
        None => get_open_cmd(&local)?,
    };
    local.record_review_activity(
        SOURCE_CRATES_IO,
        &name,
        version,
        &crev_lib::ReviewActivity::new(crate_sel.diff.as_ref().and_then(|diff| diff.clone())),
    )?;
    let status = crev_lib::util::run_with_shell_cmd(open_cmd.as_ref(), Some(&dest_dir))?;

    if !status.success() {
        bail!("Shell returned {}", status);
    }

    Ok(())
}

/*
#[derive(Copy, Clone, PartialEq, Eq)]
/// Do you select a dependency of the current project
/// or just a random, unrelated crate.
pub enum UnrelatedOrDependency {
    Unrelated,
    Dependency,
}

impl UnrelatedOrDependency {
    pub fn is_unrelated(self) -> bool {
        self == UnrelatedOrDependency::Unrelated
    }

    pub fn from_unrelated_flag(u: bool) -> Self {
        if u {
            UnrelatedOrDependency::Unrelated
        } else {
            UnrelatedOrDependency::Dependency
        }
    }
}*/

#[derive(Debug, thiserror::Error)]
pub enum ActivityCheckError {
    #[error("No previous review activity to determine base version")]
    NoPreviousReview,
    #[error("Last review activity record indicates full review")]
    UnexpectedFullReview,
    #[error("Last review activity record indicates differential review")]
    UnexpectedDiffReview,
    #[error("Last review activity record is too old")]
    Expired,
    #[error("No review activity record found")]
    NoRecord,
    #[error("{}", _0)]
    Other(#[from] crev_lib::Error),
}

/// Check `diff` command line argument against previous activity
///
/// Return `Option<Version>` indicating final `ReviewMode` settings to use.
pub fn crate_review_activity_check(
    local: &Local,
    name: &str,
    version: &Version,
    diff: &Option<Option<Version>>,
    skip_activity_check: bool,
) -> Result<Option<Version>, ActivityCheckError> {
    let activity = local.read_review_activity(SOURCE_CRATES_IO, name, version)?;

    let diff = match diff {
        None => None,
        Some(None) => Some(
            activity
                .clone()
                .ok_or(ActivityCheckError::NoPreviousReview)?
                .diff_base
                .ok_or(ActivityCheckError::UnexpectedFullReview)?,
        ),
        Some(o) => o.clone(),
    };

    if skip_activity_check {
        return Ok(diff);
    }
    if let Some(activity) = activity {
        match activity.to_review_mode() {
            ReviewMode::Full => {
                if diff.is_some() {
                    return Err(ActivityCheckError::UnexpectedFullReview);
                }
            }
            ReviewMode::Differential => {
                if diff.is_none() {
                    return Err(ActivityCheckError::UnexpectedDiffReview);
                }
            }
        }

        if activity.timestamp
            + chrono::Duration::try_days(2).expect("2 days doesn't overflow TimeDelta")
            < crev_common::now()
        {
            return Err(ActivityCheckError::Expired);
        }
    } else {
        return Err(ActivityCheckError::NoRecord);
    }

    Ok(diff)
}

pub fn check_package_clean_state(
    repo: &Repo,
    crate_root: &Path,
    name: &str,
    version: &Version,
) -> Result<(crev_data::Digest, Option<VcsInfoJson>)> {
    // to protect from creating a digest from a crate in unclean state
    // we move the old directory, download a fresh one and double
    // check if the digest was the same
    // BUG: TODO: https://users.rust-lang.org/t/append-an-additional-extension/23586
    let reviewed_pkg_dir: PathBuf =
        crev_common::fs::append_to_path(crate_root.to_owned(), ".crev.reviewed");
    if reviewed_pkg_dir.is_dir() {
        std::fs::remove_dir_all(&reviewed_pkg_dir)?;
    }

    // to prevent user calling `crev review` from the source dir,
    // having the cwd pulled from under them and confusing their
    // shells, we move all the entries in a dir, instead of the whole
    // dir. this is not a perfect solution, but better than nothing.
    crev_common::fs::move_dir_content(crate_root, &reviewed_pkg_dir)?;
    let crate_second_id = repo.find_pkgid(name, Some(version), true)?;
    let crate_second = repo.get_crate(&crate_second_id)?;
    let crate_root_second = crate_second.root();
    let crate_version_second = crate_second.version();

    assert_eq!(crate_root, crate_root_second);
    assert_eq!(version, crate_version_second);

    let digest_clean =
        crev_lib::get_recursive_digest_for_dir(crate_root, &cargo_min_ignore_list())?;
    // if the `Cargo.lock` not exist in the clean package, we can ignore it being created
    // in the reviewed version; that's normal
    let ignore_cargo_lock = !crate_root.join("Cargo.lock").exists();
    let digest_reviewed = crev_lib::get_recursive_digest_for_dir(
        &reviewed_pkg_dir,
        &cargo_full_ignore_list(ignore_cargo_lock),
    )?;

    if digest_clean != digest_reviewed {
        eprintln!(
            r#"The digest of the reviewed source code is different from the digest of a freshly downloaded copy.
            This is most probably caused by your actions: creating new or modified files.
            Will continue with the digest of a fresh copy.
            Fresh copy: {}
            Reviewed code: {}."#,
            crate_root.display(),
            reviewed_pkg_dir.display(),
        );
    } else {
        std::fs::remove_dir_all(&reviewed_pkg_dir)?;
    }

    let vcs = VcsInfoJson::read_from_crate_dir(crate_root)?;

    Ok((digest_clean, vcs))
}

pub fn find_advisories(crate_: &opts::CrateSelector) -> Result<Vec<proof::review::Package>> {
    let local = crev_lib::Local::auto_open()?;
    let db = local.load_db()?;

    Ok(db
        .get_advisories(SOURCE_CRATES_IO, crate_.name.as_deref(), crate_.version()?)
        .cloned()
        .collect())
}

pub fn run_diff(args: &opts::Diff) -> Result<std::process::ExitStatus> {
    let repo = Repo::auto_open_cwd_default()?;
    let name = &args.name;

    let dst_version = &args.dst;
    let dst_crate_id = repo.find_pkgid(name, dst_version.clone().as_ref(), args.unrelated)?;
    let dst_crate = repo.get_crate(&dst_crate_id)?;

    let requirements = crev_lib::VerificationRequirements::from(args.requirements.clone());
    let trust_distance_params = &args.trust_params.clone().into();

    let local = crev_lib::Local::auto_create_or_open()?;
    let current_id = local.get_current_userid()?;
    let db = local.load_db()?;
    let trust_set = db.calculate_trust_set(&current_id, trust_distance_params);
    let src_version = args
        .src
        .clone()
        .or_else(|| {
            crev_lib::find_latest_trusted_version(
                &trust_set,
                SOURCE_CRATES_IO,
                name,
                &requirements,
                &db,
            )
        })
        .ok_or_else(|| format_err!("No previously reviewed version found"))?;
    let src_crate_id = repo.find_pkgid(name, Some(&src_version), true)?;
    let src_crate = repo.get_crate(&src_crate_id)?;

    local.record_review_activity(
        SOURCE_CRATES_IO,
        name,
        dst_crate.version(),
        &crev_lib::ReviewActivity::new(Some(src_version)),
    )?;

    use std::process::Command;

    let diff = |exe| {
        let mut command = Command::new(exe);
        command
            .arg("-r")
            .arg("-N")
            .arg(src_crate.root())
            .arg(dst_crate.root())
            .args(&args.args);
        command
    };

    let mut command = diff(OsStr::new("diff"));

    match command.status() {
        Err(ref err) if err.kind() == io::ErrorKind::NotFound && cfg!(windows) => {
            // On Windows, diff is likely available but *not* in %PATH.  Specifically, the git installer warns that
            // adding *nix tools to %PATH% will change the behavior of some built in windows commands like "find", and
            // by default doesn't do this to avoid breaking anything.

            let program_files =
                env::var("ProgramFiles").unwrap_or_else(|_| r"C:\Program Files".to_owned());
            let mut diff_exe = PathBuf::from(program_files);
            diff_exe.push(r"Git\usr\bin\diff.exe");

            let mut command = diff(diff_exe.as_os_str());
            command
                .status()
                .map_err(|err| panic!("Failed to execute {command:?}\n{err:?}"))
        }
        Err(ref err) => panic!("Failed to execute {command:?}\n{err:?}"),
        Ok(status) => Ok(status),
    }
}

pub fn show_dir(sel: &opts::CrateSelector) -> Result<()> {
    let repo = Repo::auto_open_cwd_default()?;

    sel.ensure_name_given()?;
    let crate_id = repo.find_pkgid_by_crate_selector(sel)?;
    let crate_ = repo.get_crate(&crate_id)?;
    println!("{}", crate_.root().display());

    Ok(())
}

pub fn show_crate_digest(sel: &opts::CrateSelector) -> Result<()> {
    let repo = Repo::auto_open_cwd_default()?;

    sel.ensure_name_given()?;
    let crate_id = repo.find_pkgid_by_crate_selector(sel)?;
    let crate_ = repo.get_crate(&crate_id)?;
    let digest = crev_lib::get_recursive_digest_for_dir(crate_.root(), &cargo_min_ignore_list())?;
    println!("{digest}");

    Ok(())
}

pub fn list_advisories(crate_: &opts::CrateSelector) -> Result<()> {
    for review in find_advisories(crate_)? {
        println!("---\n{review}");
    }

    Ok(())
}

pub fn list_issues(args: &opts::RepoQueryIssue) -> Result<()> {
    let trust_distance_params = args.trust_params.clone().into();

    let local = crev_lib::Local::auto_open()?;
    let current_id = local.get_current_userid()?;
    let db = local.load_db()?;
    let trust_set = db.calculate_trust_set(&current_id, &trust_distance_params);

    for review in db.get_pkg_reviews_with_issues_for(
        SOURCE_CRATES_IO,
        args.crate_.name.as_deref(),
        args.crate_.version()?,
        &trust_set,
        args.trust_level.into(),
    ) {
        println!("---\n{review}");
    }

    Ok(())
}

/// Are we executing from a shell started by `cargo crev goto`?
///
/// If yes - return the path the original directory where the
/// `goto` command was issued.
pub fn are_we_called_from_goto_shell() -> Option<OsString> {
    env::var_os(GOTO_ORIGINAL_DIR_ENV)
}

/// Handle the `goto mode` commands
///
/// After jumping to a crate with `goto`, the crate is selected
/// already, and commands like `review` must not be given any arguments
/// like that.
pub fn handle_goto_mode_command<F>(
    args: &opts::ReviewCrateSelector,
    local_for_review: Option<&Local>,
    f: F,
) -> Result<()>
where
    F: FnOnce(&ReviewCrateSelector) -> Result<()>,
{
    if let Some(org_dir) = are_we_called_from_goto_shell() {
        if args.crate_.name.is_some() {
            bail!("In `crev goto` mode no arguments can be given");
        }
        if args.diff.is_some() {
            bail!("In `crev goto` mode diff can't be set");
        }
        let name = env::var(GOTO_CRATE_NAME_ENV)
            .map_err(|_| format_err!("crate name env var not found"))?;
        let version = env::var(GOTO_CRATE_VERSION_ENV)
            .map_err(|_| format_err!("crate version env var not found"))?;

        env::set_current_dir(org_dir)?;
        f(&ReviewCrateSelector {
            crate_: CrateSelector::new(Some(name), Some(Version::parse(&version)?), true),
            diff: None,
        })?;
    } else {
        let mut sel = None;
        if args.crate_.name.is_none()
            && let Some(latest) = local_for_review.and_then(|l| l.latest_review_activity())
            && args
                .diff
                .as_ref()
                .is_none_or(|new_base| new_base == &latest.diff_base)
        {
            sel = Some(ReviewCrateSelector {
                diff: latest.diff_base.is_some().then_some(latest.diff_base),
                crate_: CrateSelector::new(
                    Some(latest.name),
                    Some(latest.version),
                    args.crate_.unrelated,
                )
                .auto_unrelated()?,
            });
        };
        let sel = sel.as_ref().unwrap_or(args);
        sel.crate_.ensure_name_given()?;
        f(sel)?;
    }
    Ok(())
}

#[cfg(feature = "geiger")]
pub fn is_file_with_ext(entry: &walkdir::DirEntry, file_ext: &str) -> bool {
    if !entry.file_type().is_file() {
        return false;
    }
    entry
        .path()
        .extension()
        .map_or(false, |ext| ext.to_string_lossy().as_ref() == file_ext)
}

#[cfg(feature = "geiger")]
pub fn iter_rs_files_in_dir(dir: &Path) -> impl Iterator<Item = Result<PathBuf>> {
    let walker = walkdir::WalkDir::new(dir).into_iter();
    walker
        .map(|entry| {
            let entry = entry?;
            if !is_file_with_ext(&entry, "rs") {
                return Ok(None);
            }
            Ok(Some(entry.path().canonicalize()?))
        })
        .filter_map(|res| res.transpose())
}

// Note: this function is very slow
#[cfg(feature = "geiger")]
pub fn get_geiger_count(path: &Path) -> Result<u64> {
    use resiter::flat_map::FlatMap;

    let mut count = 0;
    for metrics in iter_rs_files_in_dir(path)
        .flat_map_ok(|path| geiger::find::find_unsafe_in_file(&path, geiger::IncludeTests::No))
    {
        let counters = metrics?.counters;
        count += counters.functions.unsafe_
            + counters.exprs.unsafe_
            + counters.item_impls.unsafe_
            + counters.item_traits.unsafe_
            + counters.methods.unsafe_;
    }

    Ok(count)
}

#[cfg(not(feature = "geiger"))]
pub fn get_geiger_count(_: &Path) -> Result<u64> {
    Err(anyhow::Error::msg("geiger feature is not enabled"))
}

/// Result of `run_command`
///
/// This is to distinguish expected non-success results,
/// from errors: unexpected failures.
#[must_use]
pub enum CommandExitStatus {
    // `verify deps` failed
    VerificationFailed,
    // Success, exit code 0
    Success,
    CommandExitCode(i32),
}

pub fn get_crate_digest_mismatches(
    db: &crev_wot::ProofDB,
    name: &str,
    version: &Version,
    digest: &crev_data::Digest,
) -> Vec<Package> {
    db.get_package_reviews_for_package(SOURCE_CRATES_IO, Some(name), Some(version))
        .filter(|review| review.package.digest != digest.as_slice())
        .cloned()
        .collect()
}

/// Optionally print and/or store a proof.
///
/// The signed proof is produced lazily by the `sign` closure on first use: if
/// neither `--print-signed` nor storing is requested the closure is never
/// invoked. This lets callers that may unlock the crev id on demand (e.g.
/// importing a draft for round-trip validation) avoid prompting for a
/// passphrase when no signature is going to be consumed.
///
/// `unsigned` is the unsigned content. It is used to satisfy `--print-unsigned`
/// without signing, and to validate (via
/// [`ContentExt::ensure_serializes_to_valid_proof`]) that the content would
/// round-trip cleanly when no signing happens — without this, an invalid
/// body could be silently emitted on the print-unsigned path.
pub fn maybe_store<C>(
    local: &Local,
    unsigned: &C,
    sign: impl FnOnce() -> Result<crev_data::proof::Proof>,
    commit_msg: &str,
    proof_create_opt: &opts::CommonProofCreate,
) -> Result<()>
where
    C: crev_data::proof::Content + std::fmt::Display + ?Sized,
{
    use crev_data::proof::ContentExt as _;
    use once_cell::unsync::OnceCell;

    if proof_create_opt.print_unsigned {
        print!("{unsigned}");
    }

    let signed: OnceCell<crev_data::proof::Proof> = OnceCell::new();
    let mut sign = Some(sign);

    if proof_create_opt.print_signed {
        let proof = signed.get_or_try_init(|| sign.take().unwrap()())?;
        print!("{proof}");
    }

    if !proof_create_opt.no_store {
        let proof = signed.get_or_try_init(|| sign.take().unwrap()())?;
        local.insert(proof)?;

        if !proof_create_opt.no_commit {
            local
                .proof_dir_commit(commit_msg)
                .with_context(|| "Could not not automatically commit")?;
        }
    }

    if signed.get().is_none() {
        // We never signed, so signing's implicit serialize/parse round-trip
        // never happened. Validate the unsigned body explicitly so a
        // malformed one can't escape via `--print-unsigned`.
        unsigned.ensure_serializes_to_valid_proof()?;
    }

    Ok(())
}

pub fn lookup_crates(query: &str, count: usize) -> Result<()> {
    struct CrateStats {
        name: String,
        downloads: u64,
        proof_count: usize,
    }

    use crates_io_api::{CratesQuery, Sort, SyncClient};

    let local = crev_lib::Local::auto_create_or_open()?;
    let db = local.load_db()?;

    let client = SyncClient::new("cargo-crev", std::time::Duration::from_secs(1))?;
    let mut stats: Vec<_> = client
        .crates(
            CratesQuery::builder()
                .sort(Sort::Downloads)
                .page_size(100)
                .search(query.to_string())
                .build(),
        )?
        .crates
        .iter()
        .map(|crate_| CrateStats {
            name: crate_.name.clone(),
            downloads: crate_.downloads,
            proof_count: db.get_package_review_count(SOURCE_CRATES_IO, Some(&crate_.name), None),
        })
        .collect();

    stats.sort_by(|a, b| {
        a.proof_count
            .cmp(&b.proof_count)
            .then(a.downloads.cmp(&b.downloads))
            .reverse()
    });

    for stats in stats.iter().take(count) {
        println!("{:8} {}", stats.proof_count, stats.name);
    }

    Ok(())
}