oakum 0.3.2

A polyglot release tool that derives dependent version bumps from the dependency graph
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
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
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
//! Resolve git tag names to `(package, version)` without talking to git.
//!
//! Pure: the caller supplies the tags that share one commit and the workspace
//! they could belong to. Reachable-from-HEAD collection is `okm-ls1`.
//!
//! ADR-0030: parse the four known shapes (scoped and unscoped `name@version`
//! are two productions of one format), key by package, collapse hyphen/slash
//! duplicates, ignore a bare `v{semver}` when prefixed tags on that commit
//! already name the packages for that version, and refuse leftover ambiguity
//! as unverified rather than inventing `0.1.0`. Bare assignment counts only
//! packages the caller marks as tag-managed candidates.

use alloc::collections::{BTreeMap, BTreeSet};
use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;

use semver::{BuildMetadata, Version};

use crate::plan::{Package, PackageId, Workspace};

/// Tags that look like versions but could not be attributed to exactly one
/// package at exactly one version. Unverified: name them, do not pick a
/// winner, do not compute `0.1.0` (ADR-0030).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Leftover {
    tags: Vec<String>,
}

impl Leftover {
    fn from_tags(tags: BTreeSet<String>) -> Option<Self> {
        if tags.is_empty() {
            None
        } else {
            Some(Self {
                tags: tags.into_iter().collect(),
            })
        }
    }

    #[must_use]
    pub fn tags(&self) -> &[String] {
        &self.tags
    }
}

impl fmt::Display for Leftover {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "unverified: leftover tag ambiguity: {}",
            self.tags.join(", ")
        )
    }
}

impl core::error::Error for Leftover {}

/// Attribute every tag that shares one commit.
///
/// Tags that do not look like a version (`nightly`, `v1`) are ignored. Two
/// names for the same `(package, version)` collapse to one release.
///
/// `Ok` with an empty map means this commit was parsed and yielded no releases
/// (no tags, or only ignored names). That is not a shallow clone; "we did not
/// look" belongs to collection (`okm-ls1`).
///
/// # Errors
///
/// [`Leftover`] when a tag looks like a version but matches no known
/// production, when a name matches more than one workspace package, when two
/// versions claim the same package, or when a bare `v{semver}` is the only
/// evidence among two or more tag-managed candidates. Any leftover discards
/// attributed tags on the same commit: do not pick a winner.
///
/// `bare_candidate` selects which packages may own a bare tag. Product paths
/// pass [`crate::config::Config::tag_managed`]. Prefixed matching still uses
/// the full workspace.
pub fn resolve_commit_tags(
    tags: &[&str],
    workspace: &Workspace,
    bare_candidate: impl Fn(&PackageId) -> bool,
) -> Result<BTreeMap<PackageId, Version>, Leftover> {
    let mut by_package: BTreeMap<PackageId, BTreeMap<Version, BTreeSet<String>>> = BTreeMap::new();
    let mut leftover = BTreeSet::new();
    let mut bares = Vec::new();

    for tag in tags {
        match classify(tag, workspace) {
            Class::Prefixed { package, version } => {
                by_package
                    .entry(package)
                    .or_default()
                    .entry(version)
                    .or_default()
                    .insert((*tag).to_owned());
            }
            Class::Bare(version) => bares.push((*tag, version)),
            Class::LooksLikeVersion | Class::Ambiguous => {
                leftover.insert((*tag).to_owned());
            }
            Class::Ignore => {}
        }
    }

    // Covered for bare-ignore only among bare candidates: an unmanaged
    // package's prefixed tag must not make a multi-candidate bare look settled.
    let covered_versions: BTreeSet<Version> = by_package
        .iter()
        .filter(|(id, _)| bare_candidate(id))
        .map(|(_, versions)| versions)
        .filter(|versions| versions.len() == 1)
        .filter_map(|versions| versions.keys().next().cloned())
        .collect();

    match bare_owner(workspace, &bare_candidate) {
        BareOwner::One(package) => {
            for (tag, version) in bares {
                by_package
                    .entry(package.clone())
                    .or_default()
                    .entry(version)
                    .or_default()
                    .insert(tag.to_owned());
            }
        }
        BareOwner::Many => {
            for (tag, version) in bares {
                if !covered_versions.contains(&version) {
                    leftover.insert(tag.to_owned());
                }
            }
        }
        BareOwner::None => {
            // Ignore rather than leftover when the managed set is empty
            // (exclude-everything / private-only probes).
        }
    }

    let mut attributed = BTreeMap::new();
    for (package, mut versions) in by_package {
        if versions.len() == 1 {
            if let Some((version, _)) = versions.pop_first() {
                attributed.insert(package, version);
            }
        } else {
            leftover.extend(versions.into_values().flatten());
        }
    }

    match Leftover::from_tags(leftover) {
        None => Ok(attributed),
        Some(err) => Err(err),
    }
}

/// Highest attributed version per package across many commits.
///
/// Leftover on any commit is unverified for the whole look: do not keep a
/// partial max. A package with no attributed tag is omitted (`okm-coc`);
/// that is not drift.
///
/// # Errors
///
/// [`Leftover`] if any commit's tags cannot be attributed.
pub fn current_versions(
    commits: &[&[&str]],
    workspace: &Workspace,
    bare_candidate: impl Fn(&PackageId) -> bool,
) -> Result<BTreeMap<PackageId, Version>, Leftover> {
    let mut leftover = BTreeSet::new();
    let mut current = BTreeMap::new();
    for tags in commits {
        match resolve_commit_tags(tags, workspace, &bare_candidate) {
            Ok(attributed) if leftover.is_empty() => {
                for (id, version) in attributed {
                    current
                        .entry(id)
                        .and_modify(|have: &mut Version| {
                            if without_build(&version) > without_build(have) {
                                *have = version.clone();
                            }
                        })
                        .or_insert(version);
                }
            }
            Ok(_) => {}
            Err(err) => leftover.extend(err.tags().iter().cloned()),
        }
    }
    match Leftover::from_tags(leftover) {
        None => Ok(current),
        Some(err) => Err(err),
    }
}

/// A package whose manifest is above the highest reachable tag (ADR-0014).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Drift {
    id: PackageId,
    manifest: Version,
    tagged: Version,
}

impl Drift {
    fn new(id: PackageId, manifest: Version, tagged: Version) -> Option<Self> {
        (without_build(&manifest) > without_build(&tagged)).then_some(Self {
            id,
            manifest,
            tagged,
        })
    }

    #[must_use]
    pub fn id(&self) -> &PackageId {
        &self.id
    }

    #[must_use]
    pub fn manifest(&self) -> &Version {
        &self.manifest
    }

    #[must_use]
    pub fn tagged(&self) -> &Version {
        &self.tagged
    }
}

/// Packages whose working-tree version is strictly above the tagged version
/// (ADR-0014). Untagged packages are bootstrap (`okm-coc`), not drift, except
/// a manifest above `0.1.0`, which is [`untagged_ahead`]. A manifest behind
/// the tag is not drift.
///
/// `managed` selects which packages are in scope (typically publishable, or
/// `OakumConfig::tag_managed`).
#[must_use]
pub fn drift(
    workspace: &Workspace,
    tagged: &BTreeMap<PackageId, Version>,
    managed: impl Fn(&Package) -> bool,
) -> Vec<Drift> {
    workspace
        .packages()
        .filter(|package| managed(package))
        .filter_map(|package| {
            let tagged = tagged.get(package.id())?;
            Drift::new(
                package.id().clone(),
                package.version().clone(),
                tagged.clone(),
            )
        })
        .collect()
}

/// Managed packages whose manifest matches the highest reachable tag.
#[must_use]
pub fn tagged_current(
    workspace: &Workspace,
    tagged: &BTreeMap<PackageId, Version>,
    managed: impl Fn(&Package) -> bool,
) -> Vec<(PackageId, Version)> {
    workspace
        .packages()
        .filter(|package| managed(package))
        .filter_map(|package| {
            let tagged = tagged.get(package.id())?;
            (without_build(package.version()) == without_build(tagged))
                .then(|| (package.id().clone(), tagged.clone()))
        })
        .collect()
}

/// Managed packages with no tag whose manifest is above `0.1.0`
/// (ADR-0014). Placeholders `0.0.0` and `0.1.0` are bootstrap.
#[must_use]
pub fn untagged_ahead(
    workspace: &Workspace,
    tagged: &BTreeMap<PackageId, Version>,
    managed: impl Fn(&Package) -> bool,
) -> Vec<(PackageId, Version)> {
    workspace
        .packages()
        .filter(|package| managed(package))
        .filter(|package| !tagged.contains_key(package.id()))
        .filter(|package| without_build(package.version()) > Version::new(0, 1, 0))
        .map(|package| (package.id().clone(), package.version().clone()))
        .collect()
}

/// Build metadata cannot advance a release line.
fn without_build(version: &Version) -> Version {
    let mut version = version.clone();
    version.build = BuildMetadata::EMPTY;
    version
}

enum Class {
    Prefixed {
        package: PackageId,
        version: Version,
    },
    Bare(Version),
    LooksLikeVersion,
    Ambiguous,
    Ignore,
}

enum PrefixedMatch {
    Unique {
        package: PackageId,
        version: Version,
    },
    Ambiguous,
}

fn classify(tag: &str, workspace: &Workspace) -> Class {
    if let Some(found) = match_prefixed(tag, workspace) {
        return match found {
            PrefixedMatch::Unique { package, version } => Class::Prefixed { package, version },
            PrefixedMatch::Ambiguous => Class::Ambiguous,
        };
    }
    if let Some(version) = bare_version(tag) {
        return Class::Bare(version);
    }
    if looks_like_version(tag) {
        Class::LooksLikeVersion
    } else {
        Class::Ignore
    }
}

/// Longest matching package name wins (`linesmith-core` over `linesmith`).
fn match_prefixed(tag: &str, workspace: &Workspace) -> Option<PrefixedMatch> {
    let mut best: Option<(&str, Version)> = None;
    for package in workspace.packages() {
        let name = package.id().name.as_str();
        let Some(version) = prefixed_version(name, tag) else {
            continue;
        };
        if best.as_ref().is_none_or(|(n, _)| name.len() > n.len()) {
            best = Some((name, version));
        }
    }
    let (name, version) = best?;
    Some(match unique_named(workspace, name) {
        Some(package) => PrefixedMatch::Unique { package, version },
        None => PrefixedMatch::Ambiguous,
    })
}

fn prefixed_version(name: &str, tag: &str) -> Option<Version> {
    let rest = tag.strip_prefix(name)?;
    rest.strip_prefix('@')
        .or_else(|| rest.strip_prefix("/v"))
        .or_else(|| rest.strip_prefix("-v"))
        .and_then(|s| Version::parse(s).ok())
}

fn unique_named(workspace: &Workspace, name: &str) -> Option<PackageId> {
    let mut matches = workspace
        .packages()
        .filter(|package| package.id().name == name)
        .map(|package| package.id().clone());
    let first = matches.next()?;
    match matches.next() {
        Some(_) => None,
        None => Some(first),
    }
}

enum BareOwner {
    None,
    One(PackageId),
    Many,
}

fn bare_owner(workspace: &Workspace, bare_candidate: &impl Fn(&PackageId) -> bool) -> BareOwner {
    let mut packages = workspace
        .packages()
        .map(|package| package.id().clone())
        .filter(|id| bare_candidate(id));
    let Some(first) = packages.next() else {
        return BareOwner::None;
    };
    match packages.next() {
        Some(_) => BareOwner::Many,
        None => BareOwner::One(first),
    }
}

fn bare_version(tag: &str) -> Option<Version> {
    tag.strip_prefix('v').and_then(|s| Version::parse(s).ok())
}

/// Whether a tag claims to state a version at all, in any shape — including
/// shapes oakum does not attribute to a package.
///
/// `false` is what `release` treats as a tag belonging to something else
/// entirely: `v1`, `latest`, `nightly`, `release-2024-01-01`. Those are moving
/// pointers and date stamps, not releases, and a reader that refuses a history
/// over one is refusing over a tag `release` itself skips ([ADR-0030]).
///
/// [ADR-0030]: ../../../docs/decisions/0030-derive-read-tag-shapes.md
#[must_use]
pub fn looks_like_version(tag: &str) -> bool {
    if Version::parse(tag).is_ok() || bare_version(tag).is_some() {
        return true;
    }
    // Known productions first so a prerelease hyphen (`other-v1.2.3-beta.1`)
    // is not reduced to the last ident (`beta.1`) and ignored.
    if suffix_is_version(tag, "@") || suffix_is_version(tag, "/v") || suffix_is_version(tag, "-v") {
        return true;
    }
    if let Some((_, rest)) = tag.rsplit_once('/') {
        if Version::parse(rest).is_ok() {
            return true;
        }
    }
    for (i, ch) in tag.char_indices() {
        if ch == '-' {
            let rest = &tag[i + 1..];
            if Version::parse(rest).is_ok() || bare_version(rest).is_some() {
                return true;
            }
        }
    }
    false
}

fn suffix_is_version(tag: &str, marker: &str) -> bool {
    tag.rsplit_once(marker)
        .is_some_and(|(_, rest)| Version::parse(rest).is_ok() || bare_version(rest).is_some())
}

/// Version only; does not attribute a package.
///
/// ADR-0030: `name@version`, `name/v{semver}`, `name-v{semver}`, `v{semver}`.
#[must_use]
pub fn version_from_tag(tag: &str) -> Option<Version> {
    if let Ok(version) = Version::parse(tag) {
        return Some(version);
    }
    if let Some(version) = bare_version(tag) {
        return Some(version);
    }
    for marker in ["@", "/v"] {
        if let Some((_, rest)) = tag.rsplit_once(marker) {
            if let Some(version) = version_suffix(rest) {
                return Some(version);
            }
        }
    }
    // Leftmost `-v` so `pkg-v1.0.0-v1` keeps prerelease `v1` instead of parsing `1`.
    for (i, _) in tag.match_indices("-v") {
        if let Some(version) = version_suffix(&tag[i + 2..]) {
            return Some(version);
        }
    }
    tag.rsplit_once('/')
        .and_then(|(_, rest)| Version::parse(rest).ok())
}

fn version_suffix(rest: &str) -> Option<Version> {
    Version::parse(rest).ok().or_else(|| bare_version(rest))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::plan::{Ecosystem, Package, ResolvesDependenciesAt};
    use alloc::string::ToString;

    fn cargo_workspace(names: &[&str]) -> Workspace {
        workspace(Ecosystem::Cargo, names)
    }

    fn npm_workspace(names: &[&str]) -> Workspace {
        workspace(Ecosystem::Npm, names)
    }

    fn workspace(ecosystem: Ecosystem, names: &[&str]) -> Workspace {
        workspace_publishability(
            ecosystem,
            &names.iter().map(|n| (*n, true)).collect::<Vec<_>>(),
        )
    }

    fn workspace_publishability(ecosystem: Ecosystem, packages: &[(&str, bool)]) -> Workspace {
        let packages: Vec<Package> = packages
            .iter()
            .map(|(name, publishable)| {
                Package::new(
                    PackageId::new(ecosystem, *name),
                    Version::new(0, 1, 0),
                    ResolvesDependenciesAt::Install,
                    *publishable,
                    Vec::new(),
                )
            })
            .collect();
        Workspace::new(packages).expect("workspace")
    }

    /// Unit tests that do not model selection treat every member as a candidate.
    fn resolve(
        tags: &[&str],
        workspace: &Workspace,
    ) -> Result<BTreeMap<PackageId, Version>, Leftover> {
        resolve_commit_tags(tags, workspace, |_| true)
    }

    fn current(
        commits: &[&[&str]],
        workspace: &Workspace,
    ) -> Result<BTreeMap<PackageId, Version>, Leftover> {
        current_versions(commits, workspace, |_| true)
    }

    fn ver(text: &str) -> Version {
        Version::parse(text).expect("version")
    }

    fn id(ecosystem: Ecosystem, name: &str) -> PackageId {
        PackageId::new(ecosystem, name)
    }

    #[test]
    fn version_from_tag_reads_adr_0030_shapes() {
        assert_eq!(version_from_tag("v1.2.3").as_ref(), Some(&ver("1.2.3")));
        assert_eq!(
            version_from_tag("demo@0.10.0").as_ref(),
            Some(&ver("0.10.0"))
        );
        assert_eq!(
            version_from_tag("linesmith-core-v0.2.0").as_ref(),
            Some(&ver("0.2.0"))
        );
        assert_eq!(
            version_from_tag("linesmith/v0.2.0").as_ref(),
            Some(&ver("0.2.0"))
        );
        assert_eq!(version_from_tag("nightly"), None);
        assert!(version_from_tag("demo@0.10.0").unwrap() > version_from_tag("demo@0.9.0").unwrap());
        assert_eq!(
            version_from_tag("pkg-v1.0.0-v1").as_ref(),
            Some(&ver("1.0.0-v1"))
        );
    }

    #[test]
    fn scoped_changeset_is_not_a_knope_split_on_slash() {
        let ws = npm_workspace(&["@jbabin91/mui-theme", "tt-package-demo-2"]);
        let got = resolve(&["@jbabin91/mui-theme@1.4.3"], &ws).expect("ok");
        assert_eq!(
            got.get(&id(Ecosystem::Npm, "@jbabin91/mui-theme")),
            Some(&ver("1.4.3"))
        );
        assert_eq!(got.len(), 1);
    }

    #[test]
    fn unscoped_changeset_names_the_package() {
        let ws = npm_workspace(&["pr-kit", "review-cycle"]);
        let got = resolve(&["pr-kit@0.1.0"], &ws).expect("ok");
        assert_eq!(got.len(), 1);
        assert_eq!(got.get(&id(Ecosystem::Npm, "pr-kit")), Some(&ver("0.1.0")));
    }

    #[test]
    fn scoped_and_unscoped_changeset_tags_on_one_commit() {
        let ws = npm_workspace(&["@jbabin91/mui-theme", "tt-package-demo-2"]);
        let got = resolve(
            &["@jbabin91/mui-theme@1.4.3", "tt-package-demo-2@1.0.0"],
            &ws,
        )
        .expect("ok");
        assert_eq!(got.len(), 2);
        assert_eq!(
            got.get(&id(Ecosystem::Npm, "@jbabin91/mui-theme")),
            Some(&ver("1.4.3"))
        );
        assert_eq!(
            got.get(&id(Ecosystem::Npm, "tt-package-demo-2")),
            Some(&ver("1.0.0"))
        );
    }

    #[test]
    fn knope_slash_and_release_plz_hyphen_collapse() {
        let ws = cargo_workspace(&["linesmith", "linesmith-core", "linesmith-plugin"]);
        let tags = [
            "v0.2.0",
            "linesmith/v0.2.0",
            "linesmith-core/v0.2.0",
            "linesmith-core-v0.2.0",
        ];
        let got = resolve(&tags, &ws).expect("7219fa6");
        assert_eq!(got.len(), 2);
        assert_eq!(
            got.get(&id(Ecosystem::Cargo, "linesmith")),
            Some(&ver("0.2.0"))
        );
        assert_eq!(
            got.get(&id(Ecosystem::Cargo, "linesmith-core")),
            Some(&ver("0.2.0"))
        );
        assert!(!got.contains_key(&id(Ecosystem::Cargo, "linesmith-plugin")));
    }

    #[test]
    fn four_hyphen_and_slash_tags_are_three_packages() {
        let ws = cargo_workspace(&["linesmith", "linesmith-core", "linesmith-plugin"]);
        let tags = [
            "linesmith-v0.1.3",
            "linesmith-core-v0.1.3",
            "linesmith-plugin-v0.1.3",
            "linesmith-plugin/v0.1.3",
        ];
        let got = resolve(&tags, &ws).expect("3bbde7f");
        assert_eq!(got.len(), 3);
        assert_eq!(
            got.get(&id(Ecosystem::Cargo, "linesmith")),
            Some(&ver("0.1.3"))
        );
        assert_eq!(
            got.get(&id(Ecosystem::Cargo, "linesmith-core")),
            Some(&ver("0.1.3"))
        );
        assert_eq!(
            got.get(&id(Ecosystem::Cargo, "linesmith-plugin")),
            Some(&ver("0.1.3"))
        );
    }

    #[test]
    fn bare_tag_alone_in_a_multi_package_workspace_is_leftover() {
        let ws = cargo_workspace(&["linesmith", "linesmith-core", "linesmith-plugin"]);
        let err = resolve(&["v0.1.0"], &ws).expect_err("leftover");
        assert_eq!(err.tags(), &["v0.1.0".to_string()]);
        assert!(err.to_string().contains("v0.1.0"), "{err}");
        assert!(err.to_string().contains("unverified"), "{err}");
    }

    #[test]
    fn bare_tag_assigns_when_the_workspace_has_one_package() {
        let ws = npm_workspace(&["tsc-files"]);
        let got = resolve(&["v0.2.3"], &ws).expect("ok");
        assert_eq!(
            got.get(&id(Ecosystem::Npm, "tsc-files")),
            Some(&ver("0.2.3"))
        );
    }

    #[test]
    fn bare_tag_is_ignored_when_no_tag_candidate_remains() {
        let ws = workspace_publishability(
            Ecosystem::Cargo,
            &[("probe", false), ("other-probe", false)],
        );
        let got = resolve_commit_tags(&["v0.1.0"], &ws, |_| false).expect("ok");
        assert!(got.is_empty());
    }

    #[test]
    fn bare_tag_assigns_when_only_one_member_is_a_tag_candidate() {
        let ws =
            workspace_publishability(Ecosystem::Cargo, &[("oakum", true), ("plan-no-std", false)]);
        let candidates: BTreeSet<_> = ws
            .packages()
            .filter(|package| package.publishable())
            .map(|package| package.id().clone())
            .collect();
        let got = resolve_commit_tags(&["v0.1.0"], &ws, |id| candidates.contains(id)).expect("ok");
        assert_eq!(got.get(&id(Ecosystem::Cargo, "oakum")), Some(&ver("0.1.0")));
        assert!(!got.contains_key(&id(Ecosystem::Cargo, "plan-no-std")));
    }

    #[test]
    fn bare_tag_assigns_when_a_publishable_sibling_is_excluded_from_candidates() {
        let ws = cargo_workspace(&["alpha", "beta"]);
        let candidates: BTreeSet<_> = [id(Ecosystem::Cargo, "alpha")].into_iter().collect();
        let got =
            resolve_commit_tags(&["v0.1.0"], &ws, |pkg| candidates.contains(pkg)).expect("ok");
        assert_eq!(got.get(&id(Ecosystem::Cargo, "alpha")), Some(&ver("0.1.0")));
        assert!(!got.contains_key(&id(Ecosystem::Cargo, "beta")));
    }

    #[test]
    fn bare_tag_is_leftover_when_two_tag_candidates_remain() {
        let ws = workspace_publishability(
            Ecosystem::Cargo,
            &[("oakum", true), ("sibling", true), ("probe", false)],
        );
        let candidates: BTreeSet<_> = ws
            .packages()
            .filter(|package| package.publishable())
            .map(|package| package.id().clone())
            .collect();
        let err = resolve_commit_tags(&["v0.1.0"], &ws, |id| candidates.contains(id))
            .expect_err("leftover");
        assert_eq!(err.tags(), &["v0.1.0".to_string()]);
    }

    #[test]
    fn unmanaged_prefixed_tag_does_not_cover_a_multi_candidate_bare() {
        let ws = workspace_publishability(
            Ecosystem::Cargo,
            &[("oakum", true), ("sibling", true), ("probe", false)],
        );
        let candidates: BTreeSet<_> = ws
            .packages()
            .filter(|package| package.publishable())
            .map(|package| package.id().clone())
            .collect();
        let err = resolve_commit_tags(&["probe/v0.1.0", "v0.1.0"], &ws, |id| {
            candidates.contains(id)
        })
        .expect_err("leftover");
        assert!(err.tags().contains(&"v0.1.0".to_string()), "{err:?}");
    }

    #[test]
    fn empty_tags_are_ok() {
        let ws = cargo_workspace(&["linesmith"]);
        let got = resolve(&[], &ws).expect("ok");
        assert!(got.is_empty());
    }

    #[test]
    fn nightly_and_v1_are_ignored() {
        let ws = cargo_workspace(&["linesmith"]);
        let got = resolve(&["nightly", "v1"], &ws).expect("ok");
        assert!(got.is_empty());
    }

    #[test]
    fn fifth_shape_is_leftover_not_ignored() {
        let ws = cargo_workspace(&["linesmith"]);
        let err = resolve(&["linesmith/0.4.1"], &ws).expect_err("fifth");
        assert_eq!(err.tags(), &["linesmith/0.4.1".to_string()]);
    }

    #[test]
    fn unprefixed_semver_is_leftover() {
        let ws = cargo_workspace(&["linesmith"]);
        let err = resolve(&["1.0.0"], &ws).expect_err("fifth");
        assert_eq!(err.tags(), &["1.0.0".to_string()]);
    }

    #[test]
    fn unknown_package_shaped_tag_is_leftover() {
        let ws = cargo_workspace(&["linesmith"]);
        let err = resolve(&["other-v1.0.0"], &ws).expect_err("unknown");
        assert_eq!(err.tags(), &["other-v1.0.0".to_string()]);
    }

    #[test]
    fn same_name_in_two_ecosystems_is_leftover() {
        let packages = vec![
            Package::new(
                PackageId::new(Ecosystem::Cargo, "shared"),
                Version::new(0, 1, 0),
                ResolvesDependenciesAt::Install,
                true,
                Vec::new(),
            ),
            Package::new(
                PackageId::new(Ecosystem::Npm, "shared"),
                Version::new(1, 0, 0),
                ResolvesDependenciesAt::Install,
                true,
                Vec::new(),
            ),
        ];
        let ws = Workspace::new(packages).expect("workspace");
        let err = resolve(&["shared@1.2.3"], &ws).expect_err("polyglot");
        assert_eq!(err.tags(), &["shared@1.2.3".to_string()]);
    }

    #[test]
    fn two_versions_for_one_package_on_one_commit_are_leftover() {
        let ws = cargo_workspace(&["linesmith"]);
        let err = resolve(&["linesmith/v0.2.0", "linesmith/v0.3.0"], &ws).expect_err("conflict");
        assert_eq!(
            err.tags(),
            &[
                "linesmith/v0.2.0".to_string(),
                "linesmith/v0.3.0".to_string()
            ]
        );
    }

    #[test]
    fn longer_package_name_wins_hyphen_prefix() {
        let ws = cargo_workspace(&["linesmith", "linesmith-core"]);
        let got = resolve(&["linesmith-core-v0.4.1"], &ws).expect("ok");
        assert_eq!(got.len(), 1);
        assert_eq!(
            got.get(&id(Ecosystem::Cargo, "linesmith-core")),
            Some(&ver("0.4.1"))
        );
    }

    #[test]
    fn ignored_tags_do_not_hide_a_real_release() {
        let ws = cargo_workspace(&["linesmith"]);
        let got = resolve(&["nightly", "linesmith/v0.4.1"], &ws).expect("ok");
        assert_eq!(
            got.get(&id(Ecosystem::Cargo, "linesmith")),
            Some(&ver("0.4.1"))
        );
    }

    #[test]
    fn prerelease_hyphen_on_an_unknown_package_is_leftover() {
        let ws = cargo_workspace(&["linesmith"]);
        let err = resolve(&["other-v1.0.0-beta.1"], &ws).expect_err("leftover");
        assert_eq!(err.tags(), &["other-v1.0.0-beta.1".to_string()]);
    }

    #[test]
    fn uncovered_bare_next_to_a_prefixed_tag_is_leftover() {
        let ws = cargo_workspace(&["linesmith", "linesmith-core", "linesmith-plugin"]);
        let err = resolve(&["linesmith/v0.2.0", "v0.1.0"], &ws).expect_err("leftover");
        assert_eq!(err.tags(), &["v0.1.0".to_string()]);
    }

    #[test]
    fn leftover_on_a_mixed_commit_discards_the_attributed_package() {
        let ws = cargo_workspace(&["linesmith"]);
        let err = resolve(&["linesmith/v0.2.0", "other-v1.0.0"], &ws).expect_err("leftover");
        assert_eq!(err.tags(), &["other-v1.0.0".to_string()]);
    }

    #[test]
    fn ignored_tag_does_not_drop_leftover() {
        let ws = cargo_workspace(&["linesmith", "linesmith-core", "linesmith-plugin"]);
        let err = resolve(&["nightly", "v0.1.0"], &ws).expect_err("leftover");
        assert_eq!(err.tags(), &["v0.1.0".to_string()]);
    }

    #[test]
    fn hyphen_and_slash_at_different_versions_are_leftover() {
        let ws = cargo_workspace(&["linesmith"]);
        let err = resolve(&["linesmith/v0.2.0", "linesmith-v0.3.0"], &ws).expect_err("conflict");
        assert_eq!(
            err.tags(),
            &[
                "linesmith-v0.3.0".to_string(),
                "linesmith/v0.2.0".to_string()
            ]
        );
    }

    #[test]
    fn two_bare_versions_in_a_one_package_workspace_are_leftover() {
        let ws = npm_workspace(&["tsc-files"]);
        let err = resolve(&["v0.2.3", "v0.8.4"], &ws).expect_err("conflict");
        assert_eq!(err.tags(), &["v0.2.3".to_string(), "v0.8.4".to_string()]);
    }

    #[test]
    fn prefixed_and_bare_at_different_versions_are_leftover() {
        let ws = npm_workspace(&["tsc-files"]);
        let err = resolve(&["tsc-files@0.2.3", "v0.8.4"], &ws).expect_err("conflict");
        assert_eq!(
            err.tags(),
            &["tsc-files@0.2.3".to_string(), "v0.8.4".to_string()]
        );
    }

    #[test]
    fn prefixed_and_bare_at_the_same_version_collapse() {
        let ws = npm_workspace(&["tsc-files"]);
        let got = resolve(&["tsc-files@0.2.3", "v0.2.3"], &ws).expect("ok");
        assert_eq!(got.len(), 1);
        assert_eq!(
            got.get(&id(Ecosystem::Npm, "tsc-files")),
            Some(&ver("0.2.3"))
        );
    }

    #[test]
    fn unknown_at_and_slash_v_prereleases_are_leftover() {
        let ws = cargo_workspace(&["linesmith"]);
        let err =
            resolve(&["other@1.0.0-beta.1", "other/v1.0.0-beta.1"], &ws).expect_err("leftover");
        assert_eq!(
            err.tags(),
            &[
                "other/v1.0.0-beta.1".to_string(),
                "other@1.0.0-beta.1".to_string()
            ]
        );
    }

    #[test]
    fn bare_tag_in_a_polyglot_workspace_is_leftover() {
        let packages = vec![
            Package::new(
                PackageId::new(Ecosystem::Cargo, "shared"),
                Version::new(0, 1, 0),
                ResolvesDependenciesAt::Install,
                true,
                Vec::new(),
            ),
            Package::new(
                PackageId::new(Ecosystem::Npm, "shared"),
                Version::new(1, 0, 0),
                ResolvesDependenciesAt::Install,
                true,
                Vec::new(),
            ),
        ];
        let ws = Workspace::new(packages).expect("workspace");
        let err = resolve(&["v1.2.3"], &ws).expect_err("leftover");
        assert_eq!(err.tags(), &["v1.2.3".to_string()]);
    }

    #[test]
    fn hyphen_without_v_on_an_unknown_package_is_leftover() {
        let ws = cargo_workspace(&["linesmith"]);
        let err = resolve(&["other-1.0.0"], &ws).expect_err("leftover");
        assert_eq!(err.tags(), &["other-1.0.0".to_string()]);
    }

    #[test]
    fn two_uncovered_bares_in_a_multi_package_workspace_are_leftover() {
        let ws = cargo_workspace(&["linesmith", "linesmith-core", "linesmith-plugin"]);
        let err = resolve(&["v0.1.0", "v0.1.1"], &ws).expect_err("leftover");
        assert_eq!(err.tags(), &["v0.1.0".to_string(), "v0.1.1".to_string()]);
    }

    fn cargo_at(name: &str, version: &str) -> Workspace {
        let packages = vec![Package::new(
            PackageId::new(Ecosystem::Cargo, name),
            ver(version),
            ResolvesDependenciesAt::Install,
            true,
            Vec::new(),
        )];
        Workspace::new(packages).expect("workspace")
    }

    #[test]
    fn current_versions_takes_the_max_across_commits() {
        let ws = cargo_workspace(&["linesmith"]);
        let got = current(&[&["linesmith/v0.1.0"], &["linesmith/v0.2.0"]], &ws).expect("ok");
        assert_eq!(
            got.get(&id(Ecosystem::Cargo, "linesmith")),
            Some(&ver("0.2.0"))
        );
        let got = current(&[&["linesmith/v0.2.0"], &["linesmith/v0.1.0"]], &ws).expect("ok");
        assert_eq!(
            got.get(&id(Ecosystem::Cargo, "linesmith")),
            Some(&ver("0.2.0"))
        );
    }

    #[test]
    fn current_versions_keeps_packages_from_earlier_commits() {
        let ws = cargo_workspace(&["linesmith", "linesmith-core"]);
        let got = current(&[&["linesmith/v0.1.0"], &["linesmith-core/v0.2.0"]], &ws).expect("ok");
        assert_eq!(
            got.get(&id(Ecosystem::Cargo, "linesmith")),
            Some(&ver("0.1.0"))
        );
        assert_eq!(
            got.get(&id(Ecosystem::Cargo, "linesmith-core")),
            Some(&ver("0.2.0"))
        );
    }

    #[test]
    fn leftover_on_any_commit_is_unverified_for_the_look() {
        let ws = cargo_workspace(&["linesmith", "linesmith-core"]);
        let err = current(&[&["linesmith/v0.2.0"], &["v0.1.0"]], &ws).expect_err("leftover");
        assert_eq!(err.tags(), &["v0.1.0".to_string()]);
    }

    #[test]
    fn tagged_current_when_manifest_matches_the_tag() {
        let ws = cargo_at("linesmith", "0.1.0");
        let tagged = BTreeMap::from([(id(Ecosystem::Cargo, "linesmith"), ver("0.1.0"))]);
        let got = tagged_current(&ws, &tagged, Package::publishable);
        assert_eq!(got, vec![(id(Ecosystem::Cargo, "linesmith"), ver("0.1.0"))]);
    }

    #[test]
    fn tagged_current_skips_drift() {
        let ws = cargo_at("linesmith", "0.2.0");
        let tagged = BTreeMap::from([(id(Ecosystem::Cargo, "linesmith"), ver("0.1.0"))]);
        assert!(tagged_current(&ws, &tagged, Package::publishable).is_empty());
    }

    #[test]
    fn tagged_current_uses_the_tagged_version_not_build_metadata() {
        let ws = cargo_at("linesmith", "0.1.0+local");
        let tagged = BTreeMap::from([(id(Ecosystem::Cargo, "linesmith"), ver("0.1.0"))]);
        assert_eq!(
            tagged_current(&ws, &tagged, Package::publishable),
            vec![(id(Ecosystem::Cargo, "linesmith"), ver("0.1.0"))]
        );
    }

    #[test]
    fn drift_when_manifest_is_above_the_tag() {
        let ws = cargo_at("linesmith", "0.2.0");
        let tagged = BTreeMap::from([(id(Ecosystem::Cargo, "linesmith"), ver("0.1.0"))]);
        let got = drift(&ws, &tagged, Package::publishable);
        assert_eq!(got.len(), 1);
        assert_eq!(got[0].id(), &id(Ecosystem::Cargo, "linesmith"));
        assert_eq!(got[0].manifest(), &ver("0.2.0"));
        assert_eq!(got[0].tagged(), &ver("0.1.0"));
    }

    #[test]
    fn drift_reports_only_the_package_that_is_ahead() {
        let packages = vec![
            Package::new(
                PackageId::new(Ecosystem::Cargo, "ahead"),
                ver("0.2.0"),
                ResolvesDependenciesAt::Install,
                true,
                Vec::new(),
            ),
            Package::new(
                PackageId::new(Ecosystem::Cargo, "ok"),
                ver("0.1.0"),
                ResolvesDependenciesAt::Install,
                true,
                Vec::new(),
            ),
        ];
        let ws = Workspace::new(packages).expect("workspace");
        let tagged = BTreeMap::from([
            (id(Ecosystem::Cargo, "ahead"), ver("0.1.0")),
            (id(Ecosystem::Cargo, "ok"), ver("0.1.0")),
        ]);
        let got = drift(&ws, &tagged, Package::publishable);
        assert_eq!(got.len(), 1);
        assert_eq!(got[0].id(), &id(Ecosystem::Cargo, "ahead"));
        assert_eq!(got[0].manifest(), &ver("0.2.0"));
        assert_eq!(got[0].tagged(), &ver("0.1.0"));
    }

    #[test]
    fn no_drift_when_manifest_matches_or_is_behind() {
        let ws = cargo_at("linesmith", "0.1.0");
        let tagged = BTreeMap::from([(id(Ecosystem::Cargo, "linesmith"), ver("0.1.0"))]);
        assert!(drift(&ws, &tagged, Package::publishable).is_empty());
        let tagged = BTreeMap::from([(id(Ecosystem::Cargo, "linesmith"), ver("0.2.0"))]);
        assert!(drift(&ws, &tagged, Package::publishable).is_empty());
    }

    #[test]
    fn no_tag_is_not_drift() {
        let ws = cargo_at("linesmith", "0.2.0");
        assert!(drift(&ws, &BTreeMap::new(), Package::publishable).is_empty());
    }

    #[test]
    fn untagged_above_0_1_0_is_ahead() {
        let ws = cargo_at("linesmith", "0.2.0");
        let got = untagged_ahead(&ws, &BTreeMap::new(), Package::publishable);
        assert_eq!(got, vec![(id(Ecosystem::Cargo, "linesmith"), ver("0.2.0"))]);
        let ws = cargo_at("linesmith", "0.1.1");
        let got = untagged_ahead(&ws, &BTreeMap::new(), Package::publishable);
        assert_eq!(got, vec![(id(Ecosystem::Cargo, "linesmith"), ver("0.1.1"))]);
        let ws = cargo_at("linesmith", "0.1.0");
        assert!(untagged_ahead(&ws, &BTreeMap::new(), Package::publishable).is_empty());
        let ws = cargo_at("linesmith", "0.0.0");
        assert!(untagged_ahead(&ws, &BTreeMap::new(), Package::publishable).is_empty());
        let tagged = BTreeMap::from([(id(Ecosystem::Cargo, "linesmith"), ver("0.1.0"))]);
        let ws = cargo_at("linesmith", "0.2.0");
        assert!(untagged_ahead(&ws, &tagged, Package::publishable).is_empty());
        let packages = vec![
            Package::new(
                PackageId::new(Ecosystem::Cargo, "demo"),
                ver("0.1.0"),
                ResolvesDependenciesAt::Install,
                true,
                Vec::new(),
            ),
            Package::new(
                PackageId::new(Ecosystem::Cargo, "other"),
                ver("0.2.0"),
                ResolvesDependenciesAt::Install,
                true,
                Vec::new(),
            ),
        ];
        let ws = Workspace::new(packages).expect("workspace");
        let tagged = BTreeMap::from([(id(Ecosystem::Cargo, "demo"), ver("0.1.0"))]);
        assert_eq!(
            untagged_ahead(&ws, &tagged, Package::publishable),
            vec![(id(Ecosystem::Cargo, "other"), ver("0.2.0"))]
        );
    }

    #[test]
    fn unpublishable_package_is_not_drift() {
        let packages = vec![Package::new(
            PackageId::new(Ecosystem::Cargo, "priv"),
            ver("0.2.0"),
            ResolvesDependenciesAt::Install,
            false,
            Vec::new(),
        )];
        let ws = Workspace::new(packages).expect("workspace");
        let tagged = BTreeMap::from([(id(Ecosystem::Cargo, "priv"), ver("0.1.0"))]);
        assert!(drift(&ws, &tagged, Package::publishable).is_empty());
        assert!(untagged_ahead(&ws, &BTreeMap::new(), Package::publishable).is_empty());
    }

    #[test]
    fn build_metadata_does_not_count_as_ahead() {
        let ws = cargo_at("linesmith", "0.1.0+local");
        let tagged = BTreeMap::from([(id(Ecosystem::Cargo, "linesmith"), ver("0.1.0"))]);
        assert!(drift(&ws, &tagged, Package::publishable).is_empty());
    }
}