oakum 0.12.1

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
//! Ecosystem-aware published bounds (ADR-0026).
//!
//! Cargo text is parsed with [`semver::VersionReq`]. npm text is parsed with
//! `js-semver` so bare pins, partials, and `||` keep npm meaning. Discovery
//! must call the constructor that matches the manifest's ecosystem; never
//! `VersionReq::parse` on npm strings.

use alloc::string::{String, ToString};
use core::fmt;

use semver::{Version, VersionReq};

/// Bounds ADR-0010's gate compares a candidate version against.
#[derive(Clone, Debug)]
pub enum Bounds {
    /// Cargo / crates.io grammar.
    Cargo(VersionReq),
    /// npm / node-semver grammar (`js-semver`, ADR-0026).
    ///
    /// `authored` is the manifest spelling. js-semver Display expands `^`/`~`
    /// into `>= … < …`, so rewrite must not round-trip through Display.
    Npm {
        parsed: js_semver::Range,
        authored: String,
    },
}

impl PartialEq for Bounds {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Cargo(left), Self::Cargo(right)) => left == right,
            // `js_semver::Range` has no PartialEq; compare Display strings.
            // Same-parse / same Display only: `||` clause order is not
            // normalized (`^1||^2` ≠ `^2||^1`), so this Eq is not semantic
            // equivalence for rewrite or dedup.
            (
                Self::Npm {
                    parsed: left,
                    authored: _,
                },
                Self::Npm {
                    parsed: right,
                    authored: _,
                },
            ) => left.to_string() == right.to_string(),
            _ => false,
        }
    }
}

impl Eq for Bounds {}

impl fmt::Display for Bounds {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Cargo(req) => write!(f, "{req}"),
            Self::Npm { authored, .. } => f.write_str(authored),
        }
    }
}

/// Why [`Bounds::from_cargo_text`] or [`Bounds::from_npm_text`] failed.
#[derive(Debug)]
pub enum BoundsError {
    Cargo(semver::Error),
    Npm(js_semver::SemverError),
}

impl fmt::Display for BoundsError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Cargo(error) => write!(f, "cargo range: {error}"),
            Self::Npm(error) => write!(f, "npm range: {error}"),
        }
    }
}

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

fn retarget_cargo(req: &VersionReq, new: &Version) -> Option<String> {
    if req.comparators.is_empty() {
        return Some(String::from("*"));
    }
    if let [only] = req.comparators.as_slice() {
        let op = match only.op {
            semver::Op::Greater => semver::Op::GreaterEq,
            semver::Op::Less if req.matches(new) => return Some(req.to_string()),
            semver::Op::Less => semver::Op::LessEq,
            op => op,
        };
        let rewritten = VersionReq {
            comparators: alloc::vec![semver::Comparator {
                op,
                major: new.major,
                minor: Some(new.minor),
                patch: Some(new.patch),
                pre: new.pre.clone(),
            }],
        };
        return Some(rewritten.to_string());
    }
    None
}

fn retarget_npm(text: &str, new: &Version) -> Option<String> {
    let n = new.to_string();
    if text.trim().is_empty() {
        return Some(text.to_string());
    }
    if matches!(text.trim(), "*" | "x" | "X") {
        return Some(text.trim().to_string());
    }
    let bound = |rest: &str| looks_like_version(rest) || retarget_wildcard(rest, new).is_some();
    if let Some(rest) = text.strip_prefix('>').filter(|rest| !rest.starts_with('=')) {
        if bound(rest) {
            return Some(alloc::format!(">={n}"));
        }
    }
    if let Some(rest) = text.strip_prefix('<').filter(|rest| !rest.starts_with('=')) {
        if bound(rest) {
            let still_met = text
                .parse::<js_semver::Range>()
                .ok()
                .zip(n.parse::<js_semver::Version>().ok())
                .is_some_and(|(range, version)| range.satisfies(&version));
            return Some(if still_met {
                text.to_string()
            } else {
                alloc::format!("<={n}")
            });
        }
    }
    for prefix in ["^", "~=", "~>", "~", ">=", "<=", "=", ">", "<"] {
        if let Some(rest) = text.strip_prefix(prefix) {
            if looks_like_version(rest) {
                return Some(alloc::format!("{prefix}{n}"));
            }
            if let Some(wild) = retarget_wildcard(rest, new) {
                return Some(alloc::format!("{prefix}{wild}"));
            }
        }
    }
    if looks_like_version(text) {
        if text.trim().starts_with('v') {
            return Some(alloc::format!("v{n}"));
        }
        return Some(n);
    }
    retarget_wildcard(text, new)
}

fn retarget_wildcard(text: &str, new: &Version) -> Option<String> {
    let trimmed = text.trim();
    let (v_prefix, body) = match trimmed.strip_prefix('v') {
        Some(rest) => ("v", rest),
        None => ("", trimmed),
    };
    let news = [
        new.major.to_string(),
        new.minor.to_string(),
        new.patch.to_string(),
    ];
    let mut any_wild = false;
    let mut all_wild = true;
    let mut out = String::new();
    let mut i = 0;
    for part in body.split('.') {
        if i >= 3 || part.is_empty() {
            return None;
        }
        if i > 0 {
            out.push('.');
        }
        if matches!(part, "*" | "x" | "X") {
            any_wild = true;
            out.push_str(part);
        } else if part.bytes().all(|b| b.is_ascii_digit()) {
            all_wild = false;
            out.push_str(&news[i]);
        } else {
            return None;
        }
        i += 1;
    }
    if i == 0 || !any_wild {
        return None;
    }
    if all_wild {
        return Some(trimmed.to_string());
    }
    Some(alloc::format!("{v_prefix}{out}"))
}

fn looks_like_version(text: &str) -> bool {
    let text = text.trim().strip_prefix('v').unwrap_or(text.trim());
    if Version::parse(text).is_ok() {
        return true;
    }
    // npm allows `1` and `1.2`; semver::Version does not.
    let mut n = 0;
    for part in text.split('.') {
        n += 1;
        if n > 3 || part.is_empty() || !part.bytes().all(|b| b.is_ascii_digit()) {
            return false;
        }
    }
    n == 1 || n == 2
}

impl Bounds {
    /// Parse Cargo manifest range text (`^1.2.3`, `=1.5.0`, comma AND).
    ///
    /// # Errors
    ///
    /// Returns [`BoundsError::Cargo`] when `text` is not valid Cargo range grammar.
    pub fn from_cargo_text(text: &str) -> Result<Self, BoundsError> {
        VersionReq::parse(text)
            .map(Self::Cargo)
            .map_err(BoundsError::Cargo)
    }

    /// Parse npm / package.json range text (bare exact, `||`, space AND, hyphen).
    ///
    /// # Errors
    ///
    /// Returns [`BoundsError::Npm`] when `text` is not valid npm / node-semver
    /// range grammar.
    pub fn from_npm_text(text: &str) -> Result<Self, BoundsError> {
        text.parse::<js_semver::Range>()
            .map(|parsed| Self::Npm {
                parsed,
                authored: String::from(text),
            })
            .map_err(BoundsError::Npm)
    }

    /// pnpm installs a whitespace-only npm range as any version.
    #[must_use]
    pub fn is_blank(&self) -> bool {
        matches!(self, Self::Npm { authored, .. } if authored.trim().is_empty())
    }

    /// Manifest range text with the same operator, pointed at `new`.
    ///
    /// A single comparator keeps its `Op` (`^`, `~`, `=`). `None` when the
    /// authored form is not a single operator or wildcard (`||`, AND-ranges).
    #[must_use]
    pub fn retargeted(&self, new: &Version) -> Option<String> {
        match self {
            Self::Cargo(req) => retarget_cargo(req, new),
            Self::Npm { authored, .. } => retarget_npm(authored, new),
        }
    }

    #[must_use]
    pub fn matches(&self, version: &Version) -> bool {
        match self {
            Self::Cargo(req) => req.matches(version),
            Self::Npm { parsed, .. } => {
                let range = parsed;
                if let Ok(js_version) = version.to_string().parse::<js_semver::Version>() {
                    range.satisfies(&js_version)
                } else {
                    // Package versions Display-roundtrip into js-semver; a
                    // failure here is a programming fault, not an unsatisfied
                    // range. Over-cascade (false) until the planner can abort.
                    debug_assert!(
                        false,
                        "semver::Version Display failed to parse as js_semver::Version: {version}"
                    );
                    false
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use semver::Version;

    use super::Bounds;

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

    #[test]
    fn npm_bare_is_exact_not_caret() {
        let bounds = Bounds::from_npm_text("1.5.0").expect("parse");
        assert!(bounds.matches(&v("1.5.0")));
        assert!(!bounds.matches(&v("1.6.0")));
    }

    #[test]
    fn npm_partial_major_admits_any_minor() {
        let bounds = Bounds::from_npm_text("1").expect("parse");
        assert!(bounds.matches(&v("1.9.0")));
        assert!(!bounds.matches(&v("2.0.0")));
    }

    #[test]
    fn npm_partial_minor_stays_within_patch_line() {
        let bounds = Bounds::from_npm_text("1.2").expect("parse");
        assert!(bounds.matches(&v("1.2.9")));
        assert!(!bounds.matches(&v("1.3.0")));
    }

    #[test]
    fn npm_union_admits_either_side() {
        let bounds = Bounds::from_npm_text("^1.0.0 || ^2.0.0").expect("parse");
        assert!(bounds.matches(&v("1.5.0")));
        assert!(bounds.matches(&v("2.1.0")));
        assert!(!bounds.matches(&v("3.0.0")));
    }

    #[test]
    fn npm_space_and_hyphen_forms_parse() {
        let and = Bounds::from_npm_text(">=1.2.3 <2.0.0").expect("space AND");
        assert!(and.matches(&v("1.5.0")));
        assert!(!and.matches(&v("2.0.0")));

        let hyphen = Bounds::from_npm_text("1.2.3 - 1.5.0").expect("hyphen");
        assert!(hyphen.matches(&v("1.2.3")));
        assert!(hyphen.matches(&v("1.4.0")));
        assert!(hyphen.matches(&v("1.5.0")));
        assert!(!hyphen.matches(&v("1.6.0")));
    }

    #[test]
    fn cargo_bare_remains_a_caret() {
        let bounds = Bounds::from_cargo_text("1.5.0").expect("parse");
        assert!(bounds.matches(&v("1.6.0")));
        assert!(!bounds.matches(&v("2.0.0")));
    }

    #[test]
    fn invalid_text_is_rejected_per_ecosystem() {
        assert!(Bounds::from_npm_text("not a range").is_err());
        assert!(Bounds::from_cargo_text("not a range").is_err());
    }

    #[test]
    fn npm_refuses_double_equals_on_a_full_version() {
        let error = Bounds::from_npm_text("==1.0.0").expect_err("pnpm refuses `==1.0.0`");
        assert!(matches!(error, super::BoundsError::Npm(_)), "{error}");
    }

    #[test]
    fn npm_and_cargo_bounds_are_not_equal_even_when_text_matches() {
        let npm = Bounds::from_npm_text("^1.0.0").expect("npm");
        let cargo = Bounds::from_cargo_text("^1.0.0").expect("cargo");
        assert_ne!(npm, cargo);
        assert_eq!(npm, Bounds::from_npm_text("^1.0.0").expect("npm again"));
    }

    #[test]
    fn cargo_caret_keeps_the_operator() {
        let bounds = Bounds::from_cargo_text("^0.1.3").expect("parse");
        assert_eq!(bounds.retargeted(&v("0.2.0")).as_deref(), Some("^0.2.0"));
    }

    #[test]
    fn cargo_exact_keeps_the_operator() {
        let bounds = Bounds::from_cargo_text("=0.1.3").expect("parse");
        assert_eq!(bounds.retargeted(&v("0.2.0")).as_deref(), Some("=0.2.0"));
    }

    #[test]
    fn npm_caret_keeps_the_operator() {
        let bounds = Bounds::from_npm_text("^0.1.3").expect("parse");
        assert_eq!(bounds.retargeted(&v("0.2.0")).as_deref(), Some("^0.2.0"));
    }

    #[test]
    fn npm_bare_stays_exact() {
        let bounds = Bounds::from_npm_text("0.1.3").expect("parse");
        assert_eq!(bounds.retargeted(&v("0.2.0")).as_deref(), Some("0.2.0"));
    }

    #[test]
    fn npm_tilde_on_one_x_keeps_the_operator() {
        let bounds = Bounds::from_npm_text("~1.2.3").expect("parse");
        assert_eq!(bounds.retargeted(&v("1.5.0")).as_deref(), Some("~1.5.0"));
    }

    #[test]
    fn cargo_tilde_keeps_the_operator() {
        let bounds = Bounds::from_cargo_text("~1.2.3").expect("parse");
        assert_eq!(bounds.retargeted(&v("1.5.0")).as_deref(), Some("~1.5.0"));
    }

    #[test]
    fn npm_partial_tilde_keeps_the_operator() {
        let bounds = Bounds::from_npm_text("~1.2").expect("parse");
        assert_eq!(bounds.retargeted(&v("1.5.0")).as_deref(), Some("~1.5.0"));
    }

    #[test]
    fn npm_star_stays_a_star() {
        let bounds = Bounds::from_npm_text("*").expect("parse");
        assert_eq!(bounds.retargeted(&v("2.0.0")).as_deref(), Some("*"));
    }

    #[test]
    fn npm_blank_stays_blank() {
        for text in ["", " "] {
            let bounds = Bounds::from_npm_text(text).expect("parse");
            assert_eq!(bounds.retargeted(&v("2.0.0")).as_deref(), Some(text));
        }
    }

    /// pnpm cannot install these from a catalog either.
    #[test]
    fn npm_lone_tilde_and_null_are_refused() {
        for text in ["~", "null"] {
            assert!(Bounds::from_npm_text(text).is_err(), "{text}");
        }
    }

    #[test]
    fn cargo_star_stays_a_star() {
        let bounds = Bounds::from_cargo_text("*").expect("parse");
        assert_eq!(bounds.retargeted(&v("2.0.0")).as_deref(), Some("*"));
    }

    #[test]
    fn npm_wildcard_keeps_its_shape() {
        let patch = Bounds::from_npm_text("1.2.*").expect("parse");
        assert_eq!(patch.retargeted(&v("2.0.0")).as_deref(), Some("2.0.*"));
        let minor = Bounds::from_npm_text("1.x").expect("parse");
        assert_eq!(minor.retargeted(&v("2.0.0")).as_deref(), Some("2.x"));
        let all = Bounds::from_npm_text("*.*").expect("parse");
        assert_eq!(all.retargeted(&v("2.0.0")).as_deref(), Some("*.*"));
    }

    #[test]
    fn npm_tilde_eq_and_v_prefix_keep_spelling() {
        let tilde_eq = Bounds::from_npm_text("~=1.2.3").expect("parse");
        assert_eq!(tilde_eq.retargeted(&v("2.0.0")).as_deref(), Some("~=2.0.0"));
        let tilde_gt = Bounds::from_npm_text("~>1.2.3").expect("parse");
        assert_eq!(tilde_gt.retargeted(&v("2.0.0")).as_deref(), Some("~>2.0.0"));
        let v_pin = Bounds::from_npm_text("v1.2.3").expect("parse");
        assert_eq!(v_pin.retargeted(&v("2.0.0")).as_deref(), Some("v2.0.0"));
    }

    #[test]
    fn npm_union_is_not_collapsed_to_a_caret() {
        let bounds = Bounds::from_npm_text("^1.0.0 || ^2.0.0").expect("parse");
        assert_eq!(bounds.retargeted(&v("3.0.0")), None);
    }

    /// A strict bound pointed at the new version would exclude it, so the
    /// pin stops naming the package it was written for.
    #[test]
    fn a_strict_bound_still_names_the_new_version() {
        for (text, new, want) in [
            (">0.9.0", "1.1.0", ">=1.1.0"),
            (">1.x", "2.0.0", ">=2.0.0"),
            ("<2.0.0", "1.1.0", "<2.0.0"),
            ("<2.0.0", "2.0.0", "<=2.0.0"),
            ("<=1.0.0", "1.1.0", "<=1.1.0"),
            (">=1.0.0", "1.1.0", ">=1.1.0"),
        ] {
            let bounds = Bounds::from_npm_text(text).expect("parse");
            let written = bounds.retargeted(&v(new));
            assert_eq!(written.as_deref(), Some(want), "npm {text} -> {new}");
            let written = Bounds::from_npm_text(want).expect("written parses");
            assert!(written.matches(&v(new)), "npm {want} excludes {new}");
        }
        for (text, new, want) in [
            (">0.9.0", "1.1.0", ">=1.1.0"),
            ("<2.0.0", "1.1.0", "<2.0.0"),
            ("<2.0.0", "2.0.0", "<=2.0.0"),
        ] {
            let bounds = Bounds::from_cargo_text(text).expect("parse");
            let written = bounds.retargeted(&v(new));
            assert_eq!(written.as_deref(), Some(want), "cargo {text} -> {new}");
            let written = Bounds::from_cargo_text(want).expect("written parses");
            assert!(written.matches(&v(new)), "cargo {want} excludes {new}");
        }
    }

    #[test]
    fn cargo_and_range_is_not_collapsed_to_a_caret() {
        let bounds = Bounds::from_cargo_text(">=0.1.0, <0.2.0").expect("parse");
        assert_eq!(bounds.retargeted(&v("0.2.0")), None);
    }
}