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
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
use crate::core::dependency::Dependency;
use crate::core::registry::PackageRegistry;
use crate::core::resolver::features::{CliFeatures, HasDevUnits};
use crate::core::shell::Verbosity;
use crate::core::Registry as _;
use crate::core::{PackageId, PackageIdSpec, PackageIdSpecQuery};
use crate::core::{Resolve, SourceId, Workspace};
use crate::ops;
use crate::sources::source::QueryKind;
use crate::sources::IndexSummary;
use crate::util::cache_lock::CacheLockMode;
use crate::util::context::GlobalContext;
use crate::util::toml_mut::dependency::{MaybeWorkspace, Source};
use crate::util::toml_mut::manifest::LocalManifest;
use crate::util::toml_mut::upgrade::upgrade_requirement;
use crate::util::{style, OptVersionReq};
use crate::util::{CargoResult, VersionExt};
use anyhow::Context as _;
use cargo_util_schemas::core::PartialVersion;
use itertools::Itertools;
use semver::{Op, Version, VersionReq};
use std::cmp::Ordering;
use std::collections::{BTreeMap, HashMap, HashSet};
use tracing::{debug, trace};

pub type UpgradeMap = HashMap<(String, SourceId), Version>;

pub struct UpdateOptions<'a> {
    pub gctx: &'a GlobalContext,
    pub to_update: Vec<String>,
    pub precise: Option<&'a str>,
    pub recursive: bool,
    pub dry_run: bool,
    pub workspace: bool,
}

pub fn generate_lockfile(ws: &Workspace<'_>) -> CargoResult<()> {
    let mut registry = ws.package_registry()?;
    let previous_resolve = None;
    let mut resolve = ops::resolve_with_previous(
        &mut registry,
        ws,
        &CliFeatures::new_all(true),
        HasDevUnits::Yes,
        previous_resolve,
        None,
        &[],
        true,
    )?;
    ops::write_pkg_lockfile(ws, &mut resolve)?;
    print_lockfile_changes(ws, previous_resolve, &resolve, &mut registry)?;
    Ok(())
}

pub fn update_lockfile(ws: &Workspace<'_>, opts: &UpdateOptions<'_>) -> CargoResult<()> {
    if opts.recursive && opts.precise.is_some() {
        anyhow::bail!("cannot specify both recursive and precise simultaneously")
    }

    if ws.members().count() == 0 {
        anyhow::bail!("you can't generate a lockfile for an empty workspace.")
    }

    // Updates often require a lot of modifications to the registry, so ensure
    // that we're synchronized against other Cargos.
    let _lock = ws
        .gctx()
        .acquire_package_cache_lock(CacheLockMode::DownloadExclusive)?;

    let previous_resolve = match ops::load_pkg_lockfile(ws)? {
        Some(resolve) => resolve,
        None => {
            match opts.precise {
                None => return generate_lockfile(ws),

                // Precise option specified, so calculate a previous_resolve required
                // by precise package update later.
                Some(_) => {
                    let mut registry = ws.package_registry()?;
                    ops::resolve_with_previous(
                        &mut registry,
                        ws,
                        &CliFeatures::new_all(true),
                        HasDevUnits::Yes,
                        None,
                        None,
                        &[],
                        true,
                    )?
                }
            }
        }
    };
    let mut registry = ws.package_registry()?;
    let mut to_avoid = HashSet::new();

    if opts.to_update.is_empty() {
        if !opts.workspace {
            to_avoid.extend(previous_resolve.iter());
            to_avoid.extend(previous_resolve.unused_patches());
        }
    } else {
        let mut sources = Vec::new();
        for name in opts.to_update.iter() {
            let pid = previous_resolve.query(name)?;
            if opts.recursive {
                fill_with_deps(&previous_resolve, pid, &mut to_avoid, &mut HashSet::new());
            } else {
                to_avoid.insert(pid);
                sources.push(match opts.precise {
                    Some(precise) => {
                        // TODO: see comment in `resolve.rs` as well, but this
                        //       seems like a pretty hokey reason to single out
                        //       the registry as well.
                        if pid.source_id().is_registry() {
                            pid.source_id().with_precise_registry_version(
                                pid.name(),
                                pid.version().clone(),
                                precise,
                            )?
                        } else {
                            pid.source_id().with_git_precise(Some(precise.to_string()))
                        }
                    }
                    None => pid.source_id().without_precise(),
                });
            }
            if let Ok(unused_id) =
                PackageIdSpec::query_str(name, previous_resolve.unused_patches().iter().cloned())
            {
                to_avoid.insert(unused_id);
            }
        }

        // Mirror `--workspace` and never avoid workspace members.
        // Filtering them out here so the above processes them normally
        // so their dependencies can be updated as requested
        to_avoid = to_avoid
            .into_iter()
            .filter(|id| {
                for package in ws.members() {
                    let member_id = package.package_id();
                    // Skip checking the `version` because `previous_resolve` might have a stale
                    // value.
                    // When dealing with workspace members, the other fields should be a
                    // sufficiently unique match.
                    if id.name() == member_id.name() && id.source_id() == member_id.source_id() {
                        return false;
                    }
                }
                true
            })
            .collect();

        registry.add_sources(sources)?;
    }

    // Here we place an artificial limitation that all non-registry sources
    // cannot be locked at more than one revision. This means that if a Git
    // repository provides more than one package, they must all be updated in
    // step when any of them are updated.
    //
    // TODO: this seems like a hokey reason to single out the registry as being
    // different.
    let to_avoid_sources: HashSet<_> = to_avoid
        .iter()
        .map(|p| p.source_id())
        .filter(|s| !s.is_registry())
        .collect();

    let keep = |p: &PackageId| !to_avoid_sources.contains(&p.source_id()) && !to_avoid.contains(p);

    let mut resolve = ops::resolve_with_previous(
        &mut registry,
        ws,
        &CliFeatures::new_all(true),
        HasDevUnits::Yes,
        Some(&previous_resolve),
        Some(&keep),
        &[],
        true,
    )?;

    print_lockfile_updates(
        ws,
        &previous_resolve,
        &resolve,
        opts.precise.is_some(),
        &mut registry,
    )?;
    if opts.dry_run {
        opts.gctx
            .shell()
            .warn("not updating lockfile due to dry run")?;
    } else {
        ops::write_pkg_lockfile(ws, &mut resolve)?;
    }
    Ok(())
}

/// Prints lockfile change statuses.
///
/// This would acquire the package-cache lock, as it may update the index to
/// show users latest available versions.
pub fn print_lockfile_changes(
    ws: &Workspace<'_>,
    previous_resolve: Option<&Resolve>,
    resolve: &Resolve,
    registry: &mut PackageRegistry<'_>,
) -> CargoResult<()> {
    let _lock = ws
        .gctx()
        .acquire_package_cache_lock(CacheLockMode::DownloadExclusive)?;
    if let Some(previous_resolve) = previous_resolve {
        print_lockfile_sync(ws, previous_resolve, resolve, registry)
    } else {
        print_lockfile_generation(ws, resolve, registry)
    }
}
pub fn upgrade_manifests(
    ws: &mut Workspace<'_>,
    to_update: &Vec<String>,
) -> CargoResult<UpgradeMap> {
    let gctx = ws.gctx();
    let mut upgrades = HashMap::new();
    let mut upgrade_messages = HashSet::new();

    let to_update = to_update
        .iter()
        .map(|spec| {
            PackageIdSpec::parse(spec)
                .with_context(|| format!("invalid package ID specification: `{spec}`"))
        })
        .collect::<Result<Vec<_>, _>>()?;

    // Updates often require a lot of modifications to the registry, so ensure
    // that we're synchronized against other Cargos.
    let _lock = gctx.acquire_package_cache_lock(CacheLockMode::DownloadExclusive)?;

    let mut registry = ws.package_registry()?;
    registry.lock_patches();

    for member in ws.members_mut().sorted() {
        debug!("upgrading manifest for `{}`", member.name());

        *member.manifest_mut().summary_mut() = member
            .manifest()
            .summary()
            .clone()
            .try_map_dependencies(|d| {
                upgrade_dependency(
                    &gctx,
                    &to_update,
                    &mut registry,
                    &mut upgrades,
                    &mut upgrade_messages,
                    d,
                )
            })?;
    }

    Ok(upgrades)
}

fn upgrade_dependency(
    gctx: &GlobalContext,
    to_update: &Vec<PackageIdSpec>,
    registry: &mut PackageRegistry<'_>,
    upgrades: &mut UpgradeMap,
    upgrade_messages: &mut HashSet<String>,
    dependency: Dependency,
) -> CargoResult<Dependency> {
    let name = dependency.package_name();
    let renamed_to = dependency.name_in_toml();

    if name != renamed_to {
        trace!("skipping dependency renamed from `{name}` to `{renamed_to}`");
        return Ok(dependency);
    }

    if !to_update.is_empty()
        && !to_update.iter().any(|spec| {
            spec.name() == name.as_str()
                && dependency.source_id().is_registry()
                && spec
                    .url()
                    .map_or(true, |url| url == dependency.source_id().url())
                && spec
                    .version()
                    .map_or(true, |v| dependency.version_req().matches(&v))
        })
    {
        trace!("skipping dependency `{name}` not selected for upgrading");
        return Ok(dependency);
    }

    if !dependency.source_id().is_registry() {
        trace!("skipping non-registry dependency: {name}");
        return Ok(dependency);
    }

    let version_req = dependency.version_req();

    let OptVersionReq::Req(current) = version_req else {
        trace!("skipping dependency `{name}` without a simple version requirement: {version_req}");
        return Ok(dependency);
    };

    let [comparator] = &current.comparators[..] else {
        trace!(
            "skipping dependency `{name}` with multiple version comparators: {:?}",
            &current.comparators
        );
        return Ok(dependency);
    };

    if comparator.op != Op::Caret {
        trace!("skipping non-caret dependency `{name}`: {comparator}");
        return Ok(dependency);
    }

    let query =
        crate::core::dependency::Dependency::parse(name, None, dependency.source_id().clone())?;

    let possibilities = {
        loop {
            match registry.query_vec(&query, QueryKind::Exact) {
                std::task::Poll::Ready(res) => {
                    break res?;
                }
                std::task::Poll::Pending => registry.block_until_ready()?,
            }
        }
    };

    let latest = if !possibilities.is_empty() {
        possibilities
            .iter()
            .map(|s| s.as_summary())
            .map(|s| s.version())
            .filter(|v| !v.is_prerelease())
            .max()
    } else {
        None
    };

    let Some(latest) = latest else {
        trace!("skipping dependency `{name}` without any published versions");
        return Ok(dependency);
    };

    if current.matches(&latest) {
        trace!("skipping dependency `{name}` without a breaking update available");
        return Ok(dependency);
    }

    let Some((new_req_string, _)) = upgrade_requirement(&current.to_string(), latest)? else {
        trace!("skipping dependency `{name}` because the version requirement didn't change");
        return Ok(dependency);
    };

    let upgrade_message = format!("{name} {current} -> {new_req_string}");
    trace!(upgrade_message);

    if upgrade_messages.insert(upgrade_message.clone()) {
        gctx.shell()
            .status_with_color("Upgrading", &upgrade_message, &style::GOOD)?;
    }

    upgrades.insert((name.to_string(), dependency.source_id()), latest.clone());

    let req = OptVersionReq::Req(VersionReq::parse(&latest.to_string())?);
    let mut dep = dependency.clone();
    dep.set_version_req(req);
    Ok(dep)
}

/// Update manifests with upgraded versions, and write to disk. Based on
/// cargo-edit. Returns true if any file has changed.
///
/// Some of the checks here are duplicating checks already done in
/// upgrade_manifests/upgrade_dependency. Why? Let's say upgrade_dependency has
/// found that dependency foo was eligible for an upgrade. But foo can occur in
/// multiple manifest files, and even multiple times in the same manifest file,
/// and may be pinned, renamed, etc. in some of the instances. So we still need
/// to check here which dependencies to actually modify. So why not drop the
/// upgrade map and redo all checks here? Because then we'd have to query the
/// registries again to find the latest versions.
pub fn write_manifest_upgrades(
    ws: &Workspace<'_>,
    upgrades: &UpgradeMap,
    dry_run: bool,
) -> CargoResult<bool> {
    if upgrades.is_empty() {
        return Ok(false);
    }

    let mut any_file_has_changed = false;

    let manifest_paths = std::iter::once(ws.root_manifest())
        .chain(ws.members().map(|member| member.manifest_path()))
        .collect::<Vec<_>>();

    for manifest_path in manifest_paths {
        trace!("updating TOML manifest at `{manifest_path:?}` with upgraded dependencies");

        let crate_root = manifest_path
            .parent()
            .expect("manifest path is absolute")
            .to_owned();

        let mut local_manifest = LocalManifest::try_new(&manifest_path)?;
        let mut manifest_has_changed = false;

        for dep_table in local_manifest.get_dependency_tables_mut() {
            for (mut dep_key, dep_item) in dep_table.iter_mut() {
                let dep_key_str = dep_key.get();
                let dependency = crate::util::toml_mut::dependency::Dependency::from_toml(
                    &manifest_path,
                    dep_key_str,
                    dep_item,
                )?;
                let name = &dependency.name;

                if let Some(renamed_to) = dependency.rename {
                    trace!("skipping dependency renamed from `{name}` to `{renamed_to}`");
                    continue;
                }

                let Some(current) = dependency.version() else {
                    trace!("skipping dependency without a version: {name}");
                    continue;
                };

                let (MaybeWorkspace::Other(source_id), Some(Source::Registry(source))) =
                    (dependency.source_id(ws.gctx())?, dependency.source())
                else {
                    trace!("skipping non-registry dependency: {name}");
                    continue;
                };

                let Some(latest) = upgrades.get(&(name.to_owned(), source_id)) else {
                    trace!("skipping dependency without an upgrade: {name}");
                    continue;
                };

                let Some((new_req_string, new_req)) = upgrade_requirement(current, latest)? else {
                    trace!(
                        "skipping dependency `{name}` because the version requirement didn't change"
                    );
                    continue;
                };

                let [comparator] = &new_req.comparators[..] else {
                    trace!(
                        "skipping dependency `{}` with multiple version comparators: {:?}",
                        name,
                        new_req.comparators
                    );
                    continue;
                };

                if comparator.op != Op::Caret {
                    trace!("skipping non-caret dependency `{}`: {}", name, comparator);
                    continue;
                }

                let mut dep = dependency.clone();
                let mut source = source.clone();
                source.version = new_req_string;
                dep.source = Some(Source::Registry(source));

                trace!("upgrading dependency {name}");
                dep.update_toml(&crate_root, &mut dep_key, dep_item);
                manifest_has_changed = true;
                any_file_has_changed = true;
            }
        }

        if manifest_has_changed && !dry_run {
            debug!("writing upgraded manifest to {}", manifest_path.display());
            local_manifest.write()?;
        }
    }

    Ok(any_file_has_changed)
}

fn print_lockfile_generation(
    ws: &Workspace<'_>,
    resolve: &Resolve,
    registry: &mut PackageRegistry<'_>,
) -> CargoResult<()> {
    let diff = PackageDiff::new(&resolve);
    let num_pkgs: usize = diff.iter().map(|d| d.added.len()).sum();
    if num_pkgs <= 1 {
        // just ourself, nothing worth reporting
        return Ok(());
    }
    status_locking(ws, num_pkgs)?;

    for diff in diff {
        let possibilities = if let Some(query) = diff.alternatives_query() {
            loop {
                match registry.query_vec(&query, QueryKind::Exact) {
                    std::task::Poll::Ready(res) => {
                        break res?;
                    }
                    std::task::Poll::Pending => registry.block_until_ready()?,
                }
            }
        } else {
            vec![]
        };

        for package in diff.added.iter() {
            let required_rust_version = report_required_rust_version(ws, resolve, *package);
            let latest = report_latest(&possibilities, *package);
            let note = required_rust_version.or(latest);

            if let Some(note) = note {
                ws.gctx().shell().status_with_color(
                    "Adding",
                    format!("{package}{note}"),
                    &style::NOTE,
                )?;
            }
        }
    }

    Ok(())
}

fn print_lockfile_sync(
    ws: &Workspace<'_>,
    previous_resolve: &Resolve,
    resolve: &Resolve,
    registry: &mut PackageRegistry<'_>,
) -> CargoResult<()> {
    let diff = PackageDiff::diff(&previous_resolve, &resolve);
    let num_pkgs: usize = diff.iter().map(|d| d.added.len()).sum();
    if num_pkgs == 0 {
        return Ok(());
    }
    status_locking(ws, num_pkgs)?;

    for diff in diff {
        let possibilities = if let Some(query) = diff.alternatives_query() {
            loop {
                match registry.query_vec(&query, QueryKind::Exact) {
                    std::task::Poll::Ready(res) => {
                        break res?;
                    }
                    std::task::Poll::Pending => registry.block_until_ready()?,
                }
            }
        } else {
            vec![]
        };

        if let Some((removed, added)) = diff.change() {
            let latest = if !possibilities.is_empty() {
                possibilities
                    .iter()
                    .map(|s| s.as_summary())
                    .filter(|s| is_latest(s.version(), added.version()))
                    .map(|s| s.version().clone())
                    .max()
                    .map(format_latest)
            } else {
                None
            }
            .unwrap_or_default();

            let msg = if removed.source_id().is_git() {
                format!(
                    "{removed} -> #{}",
                    &added.source_id().precise_git_fragment().unwrap()[..8],
                )
            } else {
                format!("{removed} -> v{}{latest}", added.version())
            };

            // If versions differ only in build metadata, we call it an "update"
            // regardless of whether the build metadata has gone up or down.
            // This metadata is often stuff like git commit hashes, which are
            // not meaningfully ordered.
            if removed.version().cmp_precedence(added.version()) == Ordering::Greater {
                ws.gctx()
                    .shell()
                    .status_with_color("Downgrading", msg, &style::WARN)?;
            } else {
                ws.gctx()
                    .shell()
                    .status_with_color("Updating", msg, &style::GOOD)?;
            }
        } else {
            for package in diff.added.iter() {
                let required_rust_version = report_required_rust_version(ws, resolve, *package);
                let latest = report_latest(&possibilities, *package);
                let note = required_rust_version.or(latest).unwrap_or_default();

                ws.gctx().shell().status_with_color(
                    "Adding",
                    format!("{package}{note}"),
                    &style::NOTE,
                )?;
            }
        }
    }

    Ok(())
}

fn print_lockfile_updates(
    ws: &Workspace<'_>,
    previous_resolve: &Resolve,
    resolve: &Resolve,
    precise: bool,
    registry: &mut PackageRegistry<'_>,
) -> CargoResult<()> {
    let diff = PackageDiff::diff(&previous_resolve, &resolve);
    let num_pkgs: usize = diff.iter().map(|d| d.added.len()).sum();
    if !precise {
        status_locking(ws, num_pkgs)?;
    }

    let mut unchanged_behind = 0;
    for diff in diff {
        let possibilities = if let Some(query) = diff.alternatives_query() {
            loop {
                match registry.query_vec(&query, QueryKind::Exact) {
                    std::task::Poll::Ready(res) => {
                        break res?;
                    }
                    std::task::Poll::Pending => registry.block_until_ready()?,
                }
            }
        } else {
            vec![]
        };

        if let Some((removed, added)) = diff.change() {
            let required_rust_version = report_required_rust_version(ws, resolve, *added);
            let latest = report_latest(&possibilities, *added);
            let note = required_rust_version.or(latest).unwrap_or_default();

            let msg = if removed.source_id().is_git() {
                format!(
                    "{removed} -> #{}{note}",
                    &added.source_id().precise_git_fragment().unwrap()[..8],
                )
            } else {
                format!("{removed} -> v{}{note}", added.version())
            };

            // If versions differ only in build metadata, we call it an "update"
            // regardless of whether the build metadata has gone up or down.
            // This metadata is often stuff like git commit hashes, which are
            // not meaningfully ordered.
            if removed.version().cmp_precedence(added.version()) == Ordering::Greater {
                ws.gctx()
                    .shell()
                    .status_with_color("Downgrading", msg, &style::WARN)?;
            } else {
                ws.gctx()
                    .shell()
                    .status_with_color("Updating", msg, &style::GOOD)?;
            }
        } else {
            for package in diff.removed.iter() {
                ws.gctx().shell().status_with_color(
                    "Removing",
                    format!("{package}"),
                    &style::ERROR,
                )?;
            }
            for package in diff.added.iter() {
                let required_rust_version = report_required_rust_version(ws, resolve, *package);
                let latest = report_latest(&possibilities, *package);
                let note = required_rust_version.or(latest).unwrap_or_default();

                ws.gctx().shell().status_with_color(
                    "Adding",
                    format!("{package}{note}"),
                    &style::NOTE,
                )?;
            }
        }
        for package in &diff.unchanged {
            let required_rust_version = report_required_rust_version(ws, resolve, *package);
            let latest = report_latest(&possibilities, *package);
            let note = required_rust_version.as_deref().or(latest.as_deref());

            if let Some(note) = note {
                if latest.is_some() {
                    unchanged_behind += 1;
                }
                if ws.gctx().shell().verbosity() == Verbosity::Verbose {
                    ws.gctx().shell().status_with_color(
                        "Unchanged",
                        format!("{package}{note}"),
                        &anstyle::Style::new().bold(),
                    )?;
                }
            }
        }
    }

    if ws.gctx().shell().verbosity() == Verbosity::Verbose {
        ws.gctx().shell().note(
            "to see how you depend on a package, run `cargo tree --invert --package <dep>@<ver>`",
        )?;
    } else {
        if 0 < unchanged_behind {
            ws.gctx().shell().note(format!(
                "pass `--verbose` to see {unchanged_behind} unchanged dependencies behind latest"
            ))?;
        }
    }

    Ok(())
}

fn status_locking(ws: &Workspace<'_>, num_pkgs: usize) -> CargoResult<()> {
    use std::fmt::Write as _;

    let plural = if num_pkgs == 1 { "" } else { "s" };

    let mut cfg = String::new();
    // Don't have a good way to describe `direct_minimal_versions` atm
    if !ws.gctx().cli_unstable().direct_minimal_versions {
        write!(&mut cfg, " to")?;
        if ws.gctx().cli_unstable().minimal_versions {
            write!(&mut cfg, " earliest")?;
        } else {
            write!(&mut cfg, " latest")?;
        }

        if let Some(rust_version) = required_rust_version(ws) {
            write!(&mut cfg, " Rust {rust_version}")?;
        }
        write!(&mut cfg, " compatible version{plural}")?;
    }

    ws.gctx()
        .shell()
        .status("Locking", format!("{num_pkgs} package{plural}{cfg}"))?;
    Ok(())
}

fn required_rust_version(ws: &Workspace<'_>) -> Option<PartialVersion> {
    if !ws.resolve_honors_rust_version() {
        return None;
    }

    if let Some(ver) = ws.rust_version() {
        Some(ver.clone().into_partial())
    } else {
        let rustc = ws.gctx().load_global_rustc(Some(ws)).ok()?;
        let rustc_version = rustc.version.clone().into();
        Some(rustc_version)
    }
}

fn report_required_rust_version(
    ws: &Workspace<'_>,
    resolve: &Resolve,
    package: PackageId,
) -> Option<String> {
    if package.source_id().is_path() {
        return None;
    }
    let summary = resolve.summary(package);
    let package_rust_version = summary.rust_version()?;
    let workspace_rust_version = required_rust_version(ws)?;
    if package_rust_version.is_compatible_with(&workspace_rust_version) {
        return None;
    }

    let warn = style::WARN;
    Some(format!(
        " {warn}(requires Rust {package_rust_version}){warn:#}"
    ))
}

fn report_latest(possibilities: &[IndexSummary], package: PackageId) -> Option<String> {
    if !package.source_id().is_registry() {
        return None;
    }

    possibilities
        .iter()
        .map(|s| s.as_summary())
        .filter(|s| is_latest(s.version(), package.version()))
        .map(|s| s.version().clone())
        .max()
        .map(format_latest)
}

fn format_latest(version: semver::Version) -> String {
    let warn = style::WARN;
    format!(" {warn}(latest: v{version}){warn:#}")
}

fn is_latest(candidate: &semver::Version, current: &semver::Version) -> bool {
    current < candidate
                // Only match pre-release if major.minor.patch are the same
                && (candidate.pre.is_empty()
                    || (candidate.major == current.major
                        && candidate.minor == current.minor
                        && candidate.patch == current.patch))
}

fn fill_with_deps<'a>(
    resolve: &'a Resolve,
    dep: PackageId,
    set: &mut HashSet<PackageId>,
    visited: &mut HashSet<PackageId>,
) {
    if !visited.insert(dep) {
        return;
    }
    set.insert(dep);
    for (dep, _) in resolve.deps_not_replaced(dep) {
        fill_with_deps(resolve, dep, set, visited);
    }
}

/// All resolved versions of a package name within a [`SourceId`]
#[derive(Default, Clone, Debug)]
pub struct PackageDiff {
    removed: Vec<PackageId>,
    added: Vec<PackageId>,
    unchanged: Vec<PackageId>,
}

impl PackageDiff {
    pub fn new(resolve: &Resolve) -> Vec<Self> {
        let mut changes = BTreeMap::new();
        let empty = Self::default();
        for dep in resolve.iter() {
            changes
                .entry(Self::key(dep))
                .or_insert_with(|| empty.clone())
                .added
                .push(dep);
        }

        changes.into_iter().map(|(_, v)| v).collect()
    }

    pub fn diff(previous_resolve: &Resolve, resolve: &Resolve) -> Vec<Self> {
        fn vec_subset(a: &[PackageId], b: &[PackageId]) -> Vec<PackageId> {
            a.iter().filter(|a| !contains_id(b, a)).cloned().collect()
        }

        fn vec_intersection(a: &[PackageId], b: &[PackageId]) -> Vec<PackageId> {
            a.iter().filter(|a| contains_id(b, a)).cloned().collect()
        }

        // Check if a PackageId is present `b` from `a`.
        //
        // Note that this is somewhat more complicated because the equality for source IDs does not
        // take precise versions into account (e.g., git shas), but we want to take that into
        // account here.
        fn contains_id(haystack: &[PackageId], needle: &PackageId) -> bool {
            let Ok(i) = haystack.binary_search(needle) else {
                return false;
            };

            // If we've found `a` in `b`, then we iterate over all instances
            // (we know `b` is sorted) and see if they all have different
            // precise versions. If so, then `a` isn't actually in `b` so
            // we'll let it through.
            //
            // Note that we only check this for non-registry sources,
            // however, as registries contain enough version information in
            // the package ID to disambiguate.
            if needle.source_id().is_registry() {
                return true;
            }
            haystack[i..]
                .iter()
                .take_while(|b| &needle == b)
                .any(|b| needle.source_id().has_same_precise_as(b.source_id()))
        }

        // Map `(package name, package source)` to `(removed versions, added versions)`.
        let mut changes = BTreeMap::new();
        let empty = Self::default();
        for dep in previous_resolve.iter() {
            changes
                .entry(Self::key(dep))
                .or_insert_with(|| empty.clone())
                .removed
                .push(dep);
        }
        for dep in resolve.iter() {
            changes
                .entry(Self::key(dep))
                .or_insert_with(|| empty.clone())
                .added
                .push(dep);
        }

        for v in changes.values_mut() {
            let Self {
                removed: ref mut old,
                added: ref mut new,
                unchanged: ref mut other,
            } = *v;
            old.sort();
            new.sort();
            let removed = vec_subset(old, new);
            let added = vec_subset(new, old);
            let unchanged = vec_intersection(new, old);
            *old = removed;
            *new = added;
            *other = unchanged;
        }
        debug!("{:#?}", changes);

        changes.into_iter().map(|(_, v)| v).collect()
    }

    fn key(dep: PackageId) -> (&'static str, SourceId) {
        (dep.name().as_str(), dep.source_id())
    }

    /// Guess if a package upgraded/downgraded
    ///
    /// All `PackageDiff` knows is that entries were added/removed within [`Resolve`].
    /// A package could be added or removed because of dependencies from other packages
    /// which makes it hard to definitively say "X was upgrade to N".
    pub fn change(&self) -> Option<(&PackageId, &PackageId)> {
        if self.removed.len() == 1 && self.added.len() == 1 {
            Some((&self.removed[0], &self.added[0]))
        } else {
            None
        }
    }

    /// For querying [`PackageRegistry`] for alternative versions to report to the user
    pub fn alternatives_query(&self) -> Option<crate::core::dependency::Dependency> {
        let package_id = [
            self.added.iter(),
            self.unchanged.iter(),
            self.removed.iter(),
        ]
        .into_iter()
        .flatten()
        .next()
        // Limit to registry as that is the only source with meaningful alternative versions
        .filter(|s| s.source_id().is_registry())?;
        let query = crate::core::dependency::Dependency::parse(
            package_id.name(),
            None,
            package_id.source_id(),
        )
        .expect("already a valid dependency");
        Some(query)
    }
}