Skip to main content

koji_diff/
diff.rs

1// SPDX-License-Identifier: Apache-2.0 OR MIT
2
3//! Parse installed packages from root.log and compute diffs.
4
5use std::collections::BTreeMap;
6
7use serde::Serialize;
8
9/// An installed package parsed from root.log.
10#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
11pub struct InstalledPackage {
12    pub name: String,
13    /// epoch:version-release (epoch omitted when 0).
14    pub evr: String,
15    pub arch: String,
16    /// Full NEVRA string as it appeared in the log.
17    pub full: String,
18}
19
20/// Diff between two sets of installed packages.
21#[derive(Debug, Serialize)]
22pub struct PackageDiff {
23    pub added: Vec<InstalledPackage>,
24    pub removed: Vec<InstalledPackage>,
25    pub changed: Vec<PackageChange>,
26    pub unchanged_count: usize,
27}
28
29/// A package whose version changed between two builds.
30#[derive(Debug, Serialize)]
31pub struct PackageChange {
32    pub name: String,
33    pub arch: String,
34    pub old_evr: String,
35    pub new_evr: String,
36}
37
38/// Known RPM architectures for NEVRA parsing validation.
39const VALID_ARCHES: &[&str] = &[
40    "x86_64", "aarch64", "i686", "ppc64le", "s390x", "armv7hl", "noarch", "riscv64", "i386", "i586",
41];
42
43/// Parse installed packages from a root.log file.
44///
45/// Parses the DNF transaction table that both DNF4 and DNF5 produce,
46/// with columns: Package, Arch, Version, Repo, Size.  Lines are
47/// recognised by having a known RPM arch as the second
48/// whitespace-delimited token.
49///
50/// Also handles mock's `DEBUG util.py:NNN:` prefix.
51pub fn parse_installed_packages(root_log: &str) -> Vec<InstalledPackage> {
52    let mut packages = Vec::new();
53
54    for line in root_log.lines() {
55        let content = strip_mock_prefix(line);
56        let trimmed = content.trim();
57
58        // Try to parse as a DNF transaction table row.
59        // Format: " name  arch  version  repo  size"
60        if let Some(pkg) = parse_transaction_table_row(trimmed) {
61            packages.push(pkg);
62        }
63    }
64
65    // Deduplicate by (name, arch), keeping the last occurrence (which is the
66    // latest version if the same package was upgraded).
67    let mut seen: BTreeMap<(String, String), InstalledPackage> = BTreeMap::new();
68    for pkg in packages {
69        seen.insert((pkg.name.clone(), pkg.arch.clone()), pkg);
70    }
71
72    let mut result: Vec<_> = seen.into_values().collect();
73    result.sort_by(|a, b| a.full.cmp(&b.full));
74    result
75}
76
77/// Parse a DNF transaction table row.
78///
79/// Format: `name  arch  [epoch:]version-release  repo  size`
80///
81/// Example: `libgcc  x86_64  15.2.1-7.fc42  koji-build-xxxx  268 k`
82///
83/// Recognised by having a valid RPM arch as the second token.
84fn parse_transaction_table_row(line: &str) -> Option<InstalledPackage> {
85    let tokens: Vec<&str> = line.split_whitespace().collect();
86    if tokens.len() < 4 {
87        return None;
88    }
89
90    let name = tokens[0];
91    let arch = tokens[1];
92    let evr = tokens[2]; // [epoch:]version-release
93
94    if !VALID_ARCHES.contains(&arch) {
95        return None;
96    }
97
98    // The version-release must contain a '-' (e.g. "15.2.1-7.fc42").
99    if !evr.contains('-') {
100        return None;
101    }
102
103    // Reject obvious non-package lines (e.g. table headers).
104    if name == "Package" || name.starts_with('=') {
105        return None;
106    }
107
108    let full = format!("{name}-{evr}.{arch}");
109
110    Some(InstalledPackage {
111        name: name.to_string(),
112        evr: evr.to_string(),
113        arch: arch.to_string(),
114        full,
115    })
116}
117
118fn strip_mock_prefix(line: &str) -> &str {
119    // Look for the pattern: `DEBUG <source>:  <content>`
120    // The source part is like `util.py:446:` or `mockbuild.py:123:`
121    // Mock uses two spaces after the final colon.
122    if let Some(debug_start) = line.find("DEBUG ") {
123        let after_debug = &line[debug_start + 6..];
124        // Find the first ": " after the module reference.
125        if let Some(colon_pos) = after_debug.find(": ") {
126            let rest = &after_debug[colon_pos + 2..];
127            // Skip any additional whitespace (mock uses ":  ").
128            return rest.trim_start();
129        }
130    }
131    line
132}
133
134/// Parse a NEVRA string into an [`InstalledPackage`].
135///
136/// NEVRA format: `name-[epoch:]version-release.arch`
137///
138/// Examples:
139/// - `gcc-14.2.1-1.fc42.x86_64`
140/// - `glibc-2:2.40-1.fc42.x86_64`
141pub fn parse_nevra(s: &str) -> Option<InstalledPackage> {
142    let s = s.trim();
143    if s.is_empty() || !s.contains('-') || !s.contains('.') {
144        return None;
145    }
146
147    // Split off .arch (last dot).
148    let dot_pos = s.rfind('.')?;
149    let arch = &s[dot_pos + 1..];
150    if !VALID_ARCHES.contains(&arch) {
151        return None;
152    }
153
154    let name_ver_rel = &s[..dot_pos];
155
156    // Split off -release (last dash).
157    let rel_dash = name_ver_rel.rfind('-')?;
158    let release = &name_ver_rel[rel_dash + 1..];
159    let name_ver = &name_ver_rel[..rel_dash];
160
161    // Split off -[epoch:]version (second-to-last dash).
162    let ver_dash = name_ver.rfind('-')?;
163    let version = &name_ver[ver_dash + 1..];
164    let name = &name_ver[..ver_dash];
165
166    if name.is_empty() || version.is_empty() || release.is_empty() {
167        return None;
168    }
169
170    let evr = format!("{version}-{release}");
171
172    Some(InstalledPackage {
173        name: name.to_string(),
174        evr,
175        arch: arch.to_string(),
176        full: s.to_string(),
177    })
178}
179
180/// Compute the diff between two sets of installed packages.
181pub fn diff_packages(old: &[InstalledPackage], new: &[InstalledPackage]) -> PackageDiff {
182    let old_map: BTreeMap<(&str, &str), &InstalledPackage> = old
183        .iter()
184        .map(|p| ((p.name.as_str(), p.arch.as_str()), p))
185        .collect();
186    let new_map: BTreeMap<(&str, &str), &InstalledPackage> = new
187        .iter()
188        .map(|p| ((p.name.as_str(), p.arch.as_str()), p))
189        .collect();
190
191    let mut added = Vec::new();
192    let mut removed = Vec::new();
193    let mut changed = Vec::new();
194    let mut unchanged_count = 0;
195
196    for (key, old_pkg) in &old_map {
197        match new_map.get(key) {
198            None => removed.push((*old_pkg).clone()),
199            Some(new_pkg) => {
200                if old_pkg.evr != new_pkg.evr {
201                    changed.push(PackageChange {
202                        name: old_pkg.name.clone(),
203                        arch: old_pkg.arch.clone(),
204                        old_evr: old_pkg.evr.clone(),
205                        new_evr: new_pkg.evr.clone(),
206                    });
207                } else {
208                    unchanged_count += 1;
209                }
210            }
211        }
212    }
213
214    for (key, new_pkg) in &new_map {
215        if !old_map.contains_key(key) {
216            added.push((*new_pkg).clone());
217        }
218    }
219
220    PackageDiff {
221        added,
222        removed,
223        changed,
224        unchanged_count,
225    }
226}
227
228/// How significant is a version change under Rust semver rules?
229#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
230pub enum ChangeLevel {
231    /// Same upstream version, only release/dist differs.
232    Same,
233    /// Compatible: patch change, or minor change on >= 1.0.
234    Compatible,
235    /// Breaking for 0.x: minor version changed on a 0.x version.
236    MinorBreaking,
237    /// Major version differs.
238    MajorBreaking,
239}
240
241/// Classify a version change using Rust semver rules.
242///
243/// For versions >= 1.0, a different minor is compatible.
244/// For 0.x versions, a different minor is breaking.
245pub fn classify_change(old_evr: &str, new_evr: &str) -> ChangeLevel {
246    let old_ver = extract_upstream_version(old_evr);
247    let new_ver = extract_upstream_version(new_evr);
248
249    let old_parts = parse_semver_components(&old_ver);
250    let new_parts = parse_semver_components(&new_ver);
251
252    if old_parts == new_parts {
253        return ChangeLevel::Same;
254    }
255
256    let (old_major, old_minor, _) = old_parts;
257    let (new_major, new_minor, _) = new_parts;
258
259    if old_major != new_major {
260        return ChangeLevel::MajorBreaking;
261    }
262
263    if old_minor != new_minor && old_major == 0 {
264        return ChangeLevel::MinorBreaking;
265    }
266
267    ChangeLevel::Compatible
268}
269
270/// Extract the upstream version from an EVR string.
271///
272/// `1:4.7.0-10.el10` -> `4.7.0`
273/// `2.0.18-1.fc42` -> `2.0.18`
274fn extract_upstream_version(evr: &str) -> String {
275    // Strip epoch.
276    let without_epoch = match evr.find(':') {
277        Some(pos) => &evr[pos + 1..],
278        None => evr,
279    };
280    // Take everything before the first `-` (version, not release).
281    match without_epoch.find('-') {
282        Some(pos) => without_epoch[..pos].to_string(),
283        None => without_epoch.to_string(),
284    }
285}
286
287/// Parse a version string into (major, minor, patch) components.
288///
289/// Non-numeric or missing components default to 0.
290fn parse_semver_components(version: &str) -> (u64, u64, u64) {
291    let mut parts = version.split('.');
292    let major = parts.next().and_then(|s| s.parse().ok()).unwrap_or(0);
293    let minor = parts.next().and_then(|s| s.parse().ok()).unwrap_or(0);
294    let patch = parts.next().and_then(|s| s.parse().ok()).unwrap_or(0);
295    (major, minor, patch)
296}
297
298impl ChangeLevel {
299    fn ansi_color(self) -> &'static str {
300        match self {
301            ChangeLevel::Same => "\x1b[32m",                // green
302            ChangeLevel::Compatible => "\x1b[38;5;228m",    // bright yellow
303            ChangeLevel::MinorBreaking => "\x1b[38;5;208m", // orange
304            ChangeLevel::MajorBreaking => "\x1b[31m",       // red
305        }
306    }
307
308    /// Two-char-wide label for aligned output.
309    fn label(self) -> &'static str {
310        match self {
311            ChangeLevel::Same => "= ",
312            ChangeLevel::Compatible => "~ ",
313            ChangeLevel::MinorBreaking => "! ",
314            ChangeLevel::MajorBreaking => "!!",
315        }
316    }
317}
318
319/// Print the package diff in human-readable format.
320pub fn print_diff(diff: &PackageDiff, ref1_label: &str, ref2_label: &str, color: bool) {
321    if diff.added.is_empty() && diff.removed.is_empty() && diff.changed.is_empty() {
322        println!("No differences in installed packages.");
323        println!("({} packages unchanged)", diff.unchanged_count);
324        return;
325    }
326
327    let reset = if color { "\x1b[0m" } else { "" };
328
329    println!("Buildroot package changes (root.log):");
330
331    if !diff.changed.is_empty() {
332        println!("  Changed ({}):", diff.changed.len());
333        for pkg in &diff.changed {
334            let level = classify_change(&pkg.old_evr, &pkg.new_evr);
335            let c = if color { level.ansi_color() } else { "" };
336            println!(
337                "    {c}{} {}.{}: {} -> {}{reset}",
338                level.label(),
339                pkg.name,
340                pkg.arch,
341                pkg.old_evr,
342                pkg.new_evr
343            );
344        }
345    }
346
347    if !diff.added.is_empty() {
348        println!("  Added in {} ({}):", ref2_label, diff.added.len());
349        for pkg in &diff.added {
350            println!("    + {}", pkg.full);
351        }
352    }
353
354    if !diff.removed.is_empty() {
355        println!("  Removed vs {} ({}):", ref1_label, diff.removed.len());
356        for pkg in &diff.removed {
357            println!("    - {}", pkg.full);
358        }
359    }
360
361    println!("  ({} packages unchanged)", diff.unchanged_count);
362}
363
364#[cfg(test)]
365mod tests {
366    use super::*;
367
368    // --- NEVRA parsing ---
369
370    #[test]
371    fn test_parse_nevra_simple() {
372        let pkg = parse_nevra("gcc-14.2.1-1.fc42.x86_64").unwrap();
373        assert_eq!(pkg.name, "gcc");
374        assert_eq!(pkg.evr, "14.2.1-1.fc42");
375        assert_eq!(pkg.arch, "x86_64");
376    }
377
378    #[test]
379    fn test_parse_nevra_with_epoch() {
380        let pkg = parse_nevra("glibc-2:2.40-1.fc42.x86_64").unwrap();
381        assert_eq!(pkg.name, "glibc");
382        assert_eq!(pkg.evr, "2:2.40-1.fc42");
383        assert_eq!(pkg.arch, "x86_64");
384    }
385
386    #[test]
387    fn test_parse_nevra_noarch() {
388        let pkg = parse_nevra("python3-setuptools-75.0-1.fc42.noarch").unwrap();
389        assert_eq!(pkg.name, "python3-setuptools");
390        assert_eq!(pkg.arch, "noarch");
391    }
392
393    #[test]
394    fn test_parse_nevra_complex_name() {
395        let pkg = parse_nevra("xorg-x11-server-Xwayland-24.1.1-1.fc42.x86_64").unwrap();
396        assert_eq!(pkg.name, "xorg-x11-server-Xwayland");
397        assert_eq!(pkg.evr, "24.1.1-1.fc42");
398    }
399
400    #[test]
401    fn test_parse_nevra_invalid_arch() {
402        assert!(parse_nevra("foo-1.0-1.fc42.badarch").is_none());
403    }
404
405    #[test]
406    fn test_parse_nevra_no_dashes() {
407        assert!(parse_nevra("nodashes").is_none());
408    }
409
410    #[test]
411    fn test_parse_nevra_empty() {
412        assert!(parse_nevra("").is_none());
413    }
414
415    #[test]
416    fn test_parse_nevra_size_suffix_ignored() {
417        // In some DNF output, the NEVRA might be followed by a size.
418        // We only parse the first whitespace-delimited token.
419        assert!(parse_nevra("123k").is_none());
420    }
421
422    // --- Mock prefix stripping ---
423
424    #[test]
425    fn test_strip_mock_prefix() {
426        assert_eq!(
427            strip_mock_prefix("DEBUG util.py:446:  Installed:"),
428            "Installed:"
429        );
430    }
431
432    #[test]
433    fn test_strip_mock_prefix_no_prefix() {
434        assert_eq!(strip_mock_prefix("Installed:"), "Installed:");
435    }
436
437    #[test]
438    fn test_strip_mock_prefix_with_content() {
439        assert_eq!(
440            strip_mock_prefix("DEBUG util.py:446:    gcc-14.2.1-1.fc42.x86_64"),
441            "gcc-14.2.1-1.fc42.x86_64"
442        );
443    }
444
445    // --- Transaction table parsing ---
446
447    #[test]
448    fn test_parse_transaction_table_row() {
449        let pkg = parse_transaction_table_row(
450            "libgcc                       x86_64  14.3.1-4.4.el10              build  140 k",
451        )
452        .unwrap();
453        assert_eq!(pkg.name, "libgcc");
454        assert_eq!(pkg.arch, "x86_64");
455        assert_eq!(pkg.evr, "14.3.1-4.4.el10");
456        assert_eq!(pkg.full, "libgcc-14.3.1-4.4.el10.x86_64");
457    }
458
459    #[test]
460    fn test_parse_transaction_table_row_with_epoch() {
461        let pkg = parse_transaction_table_row(
462            "dbus-libs                    x86_64  1:1.14.10-5.el10             build  156 k",
463        )
464        .unwrap();
465        assert_eq!(pkg.name, "dbus-libs");
466        assert_eq!(pkg.evr, "1:1.14.10-5.el10");
467        assert_eq!(pkg.full, "dbus-libs-1:1.14.10-5.el10.x86_64");
468    }
469
470    #[test]
471    fn test_parse_transaction_table_row_noarch() {
472        let pkg = parse_transaction_table_row(
473            "setup                        noarch  2.14.5-7.el10                build  153 k",
474        )
475        .unwrap();
476        assert_eq!(pkg.name, "setup");
477        assert_eq!(pkg.arch, "noarch");
478    }
479
480    #[test]
481    fn test_parse_transaction_table_row_rejects_header() {
482        assert!(
483            parse_transaction_table_row(
484                "Package                      Arch    Version                      Repo    Size"
485            )
486            .is_none()
487        );
488    }
489
490    #[test]
491    fn test_parse_transaction_table_row_rejects_separator() {
492        assert!(
493            parse_transaction_table_row(
494                "================================================================================"
495            )
496            .is_none()
497        );
498    }
499
500    #[test]
501    fn test_parse_transaction_table_row_rejects_section_header() {
502        assert!(parse_transaction_table_row("Installing:").is_none());
503        assert!(parse_transaction_table_row("Installing dependencies:").is_none());
504        assert!(parse_transaction_table_row("Transaction Summary").is_none());
505    }
506
507    // --- root.log parsing ---
508
509    #[test]
510    fn test_parse_installed_packages_dnf4_table() {
511        let log = "\
512DEBUG util.py:463:  Installing:
513DEBUG util.py:463:   gcc                          x86_64  14.2.1-1.fc42                build   31 M
514DEBUG util.py:463:  Installing dependencies:
515DEBUG util.py:463:   glibc                        x86_64  2.40-1.fc42                  build   12 M
516DEBUG util.py:463:   glibc-common                 x86_64  2.40-1.fc42                  build  323 k
517";
518        let pkgs = parse_installed_packages(log);
519        assert_eq!(pkgs.len(), 3);
520        assert!(pkgs.iter().any(|p| p.name == "gcc"));
521        assert!(pkgs.iter().any(|p| p.name == "glibc"));
522        assert!(pkgs.iter().any(|p| p.name == "glibc-common"));
523    }
524
525    #[test]
526    fn test_parse_installed_packages_with_mock_prefix() {
527        let log = "\
528DEBUG util.py:463:   libgcc                       x86_64  14.3.1-4.4.el10              build  140 k
529DEBUG util.py:463:   bash                         x86_64  5.2.26-6.el10                build  1.8 M
530";
531        let pkgs = parse_installed_packages(log);
532        assert_eq!(pkgs.len(), 2);
533        assert!(pkgs.iter().any(|p| p.name == "libgcc"));
534        assert!(pkgs.iter().any(|p| p.name == "bash"));
535    }
536
537    #[test]
538    fn test_parse_installed_packages_deduplication() {
539        // Same package in two transaction tables → keep last version.
540        let log = "\
541 gcc                          x86_64  14.2.1-1.fc42                build   31 M
542 gcc                          x86_64  14.2.1-2.fc42                build   31 M
543";
544        let pkgs = parse_installed_packages(log);
545        assert_eq!(pkgs.len(), 1);
546        assert_eq!(pkgs[0].evr, "14.2.1-2.fc42");
547    }
548
549    #[test]
550    fn test_parse_installed_packages_empty() {
551        let log = "No packages installed.\n";
552        let pkgs = parse_installed_packages(log);
553        assert!(pkgs.is_empty());
554    }
555
556    // --- Diff computation ---
557
558    #[test]
559    fn test_diff_identical() {
560        let pkgs = vec![InstalledPackage {
561            name: "gcc".into(),
562            evr: "14.2.1-1.fc42".into(),
563            arch: "x86_64".into(),
564            full: "gcc-14.2.1-1.fc42.x86_64".into(),
565        }];
566        let diff = diff_packages(&pkgs, &pkgs);
567        assert!(diff.added.is_empty());
568        assert!(diff.removed.is_empty());
569        assert!(diff.changed.is_empty());
570        assert_eq!(diff.unchanged_count, 1);
571    }
572
573    #[test]
574    fn test_diff_added_package() {
575        let old = vec![];
576        let new = vec![InstalledPackage {
577            name: "gcc".into(),
578            evr: "14.2.1-1.fc42".into(),
579            arch: "x86_64".into(),
580            full: "gcc-14.2.1-1.fc42.x86_64".into(),
581        }];
582        let diff = diff_packages(&old, &new);
583        assert_eq!(diff.added.len(), 1);
584        assert_eq!(diff.added[0].name, "gcc");
585    }
586
587    #[test]
588    fn test_diff_removed_package() {
589        let old = vec![InstalledPackage {
590            name: "gcc".into(),
591            evr: "14.2.1-1.fc42".into(),
592            arch: "x86_64".into(),
593            full: "gcc-14.2.1-1.fc42.x86_64".into(),
594        }];
595        let new = vec![];
596        let diff = diff_packages(&old, &new);
597        assert_eq!(diff.removed.len(), 1);
598        assert_eq!(diff.removed[0].name, "gcc");
599    }
600
601    #[test]
602    fn test_diff_changed_version() {
603        let old = vec![InstalledPackage {
604            name: "gcc".into(),
605            evr: "14.2.1-1.fc42".into(),
606            arch: "x86_64".into(),
607            full: "gcc-14.2.1-1.fc42.x86_64".into(),
608        }];
609        let new = vec![InstalledPackage {
610            name: "gcc".into(),
611            evr: "14.2.1-2.fc42".into(),
612            arch: "x86_64".into(),
613            full: "gcc-14.2.1-2.fc42.x86_64".into(),
614        }];
615        let diff = diff_packages(&old, &new);
616        assert_eq!(diff.changed.len(), 1);
617        assert_eq!(diff.changed[0].old_evr, "14.2.1-1.fc42");
618        assert_eq!(diff.changed[0].new_evr, "14.2.1-2.fc42");
619    }
620
621    #[test]
622    fn test_diff_mixed_changes() {
623        let old = vec![
624            InstalledPackage {
625                name: "gcc".into(),
626                evr: "14.2.1-1.fc42".into(),
627                arch: "x86_64".into(),
628                full: "gcc-14.2.1-1.fc42.x86_64".into(),
629            },
630            InstalledPackage {
631                name: "removed-pkg".into(),
632                evr: "1.0-1.fc42".into(),
633                arch: "x86_64".into(),
634                full: "removed-pkg-1.0-1.fc42.x86_64".into(),
635            },
636            InstalledPackage {
637                name: "unchanged".into(),
638                evr: "1.0-1.fc42".into(),
639                arch: "noarch".into(),
640                full: "unchanged-1.0-1.fc42.noarch".into(),
641            },
642        ];
643        let new = vec![
644            InstalledPackage {
645                name: "gcc".into(),
646                evr: "14.2.1-2.fc42".into(),
647                arch: "x86_64".into(),
648                full: "gcc-14.2.1-2.fc42.x86_64".into(),
649            },
650            InstalledPackage {
651                name: "new-pkg".into(),
652                evr: "2.0-1.fc42".into(),
653                arch: "x86_64".into(),
654                full: "new-pkg-2.0-1.fc42.x86_64".into(),
655            },
656            InstalledPackage {
657                name: "unchanged".into(),
658                evr: "1.0-1.fc42".into(),
659                arch: "noarch".into(),
660                full: "unchanged-1.0-1.fc42.noarch".into(),
661            },
662        ];
663        let diff = diff_packages(&old, &new);
664        assert_eq!(diff.changed.len(), 1);
665        assert_eq!(diff.added.len(), 1);
666        assert_eq!(diff.removed.len(), 1);
667        assert_eq!(diff.unchanged_count, 1);
668    }
669
670    // --- Semver classification ---
671
672    #[test]
673    fn test_classify_same_version() {
674        // Only release/dist differs.
675        assert_eq!(
676            classify_change("2.0.18-1.fc42", "2.0.18-1.el10_2"),
677            ChangeLevel::Same
678        );
679    }
680
681    #[test]
682    fn test_classify_same_version_with_epoch() {
683        assert_eq!(
684            classify_change("1:1.14.10-5.fc42", "1:1.14.10-5.el10"),
685            ChangeLevel::Same
686        );
687    }
688
689    #[test]
690    fn test_classify_compatible_minor_change() {
691        // Major >= 1, minor differs -> compatible.
692        assert_eq!(
693            classify_change("4.5.2-1.fc42", "4.4.36-10.el10"),
694            ChangeLevel::Compatible
695        );
696    }
697
698    #[test]
699    fn test_classify_compatible_patch_change() {
700        // Same major.minor, patch differs.
701        assert_eq!(
702            classify_change("1.5.2-1.fc42", "1.5.9-1.el10"),
703            ChangeLevel::Compatible
704        );
705    }
706
707    #[test]
708    fn test_classify_minor_breaking_0x() {
709        // 0.x: minor change is breaking under Rust semver.
710        assert_eq!(
711            classify_change("0.5.2-1.fc42", "0.6.0-1.el10"),
712            ChangeLevel::MinorBreaking
713        );
714    }
715
716    #[test]
717    fn test_classify_compatible_0x_patch() {
718        // 0.x: patch-only change is compatible.
719        assert_eq!(
720            classify_change("0.5.2-1.fc42", "0.5.9-1.el10"),
721            ChangeLevel::Compatible
722        );
723    }
724
725    #[test]
726    fn test_classify_major_breaking() {
727        assert_eq!(
728            classify_change("1.0.0-1.fc42", "2.0.0-1.el10"),
729            ChangeLevel::MajorBreaking
730        );
731    }
732
733    #[test]
734    fn test_classify_major_breaking_0_to_1() {
735        assert_eq!(
736            classify_change("0.9.0-1.fc42", "1.0.0-1.el10"),
737            ChangeLevel::MajorBreaking
738        );
739    }
740
741    #[test]
742    fn test_extract_upstream_version() {
743        assert_eq!(extract_upstream_version("4.7.0-10.el10"), "4.7.0");
744        assert_eq!(extract_upstream_version("1:1.14.10-5.el10"), "1.14.10");
745        assert_eq!(extract_upstream_version("20260216-1.el10"), "20260216");
746    }
747
748    #[test]
749    fn test_parse_semver_components() {
750        assert_eq!(parse_semver_components("4.7.0"), (4, 7, 0));
751        assert_eq!(parse_semver_components("1.14.10"), (1, 14, 10));
752        assert_eq!(parse_semver_components("20260216"), (20260216, 0, 0));
753        assert_eq!(parse_semver_components("2.39"), (2, 39, 0));
754    }
755}