pkgsrc 0.11.0

Rust interface to pkgsrc packages and infrastructure
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
/*
 * Copyright (c) 2026 Jonathan Perkin <jonathan@perkin.org.uk>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/*!
 * Package name parsing into base, version, and revision components.
 *
 * In pkgsrc, every package has a `PKGNAME` that uniquely identifies a specific
 * version of a package.
 *
 * ```text
 * PKGNAME = PKGBASE-PKGVERSION
 * PKGVERSION = VERSION[nbPKGREVISION]
 * ```
 *
 * For example, `mktool-1.4.2nb3` breaks down as:
 *
 * - **PKGBASE**: `mktool` - the package name
 * - **PKGVERSION**: `1.4.2nb3` - the full version string
 * - **VERSION**: `1.4.2` - the upstream version
 * - **PKGREVISION**: `3` - the pkgsrc-specific revision
 *
 * The `PKGBASE` and `PKGVERSION` are separated by the last hyphen (`-`) in the
 * string. The `PKGREVISION` suffix (`nb` followed by a number) indicates
 * pkgsrc-specific changes that do not correspond to an upstream release.
 *
 * # Examples
 *
 * ```
 * use pkgsrc::PkgName;
 *
 * let pkg = PkgName::new("nginx-1.25.3nb2");
 * assert_eq!(pkg.pkgbase(), "nginx");
 * assert_eq!(pkg.pkgversion(), "1.25.3nb2");
 * assert_eq!(pkg.pkgrevision(), Some(2));
 *
 * // Package with hyphenated name
 * let pkg = PkgName::new("p5-libwww-6.77");
 * assert_eq!(pkg.pkgbase(), "p5-libwww");
 * assert_eq!(pkg.pkgversion(), "6.77");
 * assert_eq!(pkg.pkgrevision(), None);
 *
 * // Package without revision
 * let pkg = PkgName::new("curl-8.5.0");
 * assert_eq!(pkg.pkgbase(), "curl");
 * assert_eq!(pkg.pkgversion(), "8.5.0");
 * assert_eq!(pkg.pkgrevision(), None);
 * ```
 *
 * # PKGREVISION
 *
 * The `PKGREVISION` is incremented by pkgsrc maintainers when:
 *
 * - A dependency is updated and the package needs rebuilding
 * - pkgsrc-specific patches are modified
 * - Build or packaging changes are made
 *
 * For version comparison, `1.0nb1` > `1.0` > `1.0rc1`. See the [`dewey`] module
 * for details on version comparison rules.
 *
 * [`dewey`]: crate::dewey
 */

use std::borrow::Borrow;
use std::hash::{Hash, Hasher};
use std::str::FromStr;

#[cfg(feature = "serde")]
use serde_with::{DeserializeFromStr, SerializeDisplay};

/**
 * Parse a `PKGNAME` into its constituent parts.
 *
 * In pkgsrc terminology a `PKGNAME` is made up of three parts:
 *
 * * `PKGBASE` contains the name of the package
 * * `PKGVERSION` contains the full version string
 * * `PKGREVISION` is an optional package revision denoted by `nb` followed by
 *   a number.
 *
 * The name and version are split at the last `-`, and the revision, if
 * specified, should be located at the end of the version.
 *
 * This module does not enforce strict formatting.  If a `PKGNAME` is not well
 * formed then values may be empty or [`None`].
 *
 * # Examples
 *
 * ```
 * use pkgsrc::PkgName;
 *
 * // A well formed package name.
 * let pkg = PkgName::new("mktool-1.3.2nb2");
 * assert_eq!(pkg.pkgname(), "mktool-1.3.2nb2");
 * assert_eq!(pkg.pkgbase(), "mktool");
 * assert_eq!(pkg.pkgversion(), "1.3.2nb2");
 * assert_eq!(pkg.pkgrevision(), Some(2));
 *
 * // An invalid PKGREVISION that can likely only be created by accident.
 * let pkg = PkgName::new("mktool-1.3.2nb");
 * assert_eq!(pkg.pkgbase(), "mktool");
 * assert_eq!(pkg.pkgversion(), "1.3.2nb");
 * assert_eq!(pkg.pkgrevision(), Some(0));
 *
 * // A "-" in the version causes an incorrect split.
 * let pkg = PkgName::new("mktool-1.3-2");
 * assert_eq!(pkg.pkgbase(), "mktool-1.3");
 * assert_eq!(pkg.pkgversion(), "2");
 * assert_eq!(pkg.pkgrevision(), None);
 *
 * // Not well formed, but still accepted.
 * let pkg = PkgName::new("mktool");
 * assert_eq!(pkg.pkgbase(), "mktool");
 * assert_eq!(pkg.pkgversion(), "");
 * assert_eq!(pkg.pkgrevision(), None);
 *
 * // Doesn't make any sense, but whatever!
 * let pkg = PkgName::new("1.0nb2");
 * assert_eq!(pkg.pkgbase(), "1.0nb2");
 * assert_eq!(pkg.pkgversion(), "");
 * assert_eq!(pkg.pkgrevision(), None);
 * ```
 */
#[derive(Clone, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serde", derive(SerializeDisplay, DeserializeFromStr))]
pub struct PkgName {
    pkgname: String,
    split: usize,
}

/**
 * Return the `PKGBASE` portion of a package name, i.e. everything before
 * the final `-`, or the full input if no `-` is present.
 */
#[must_use]
pub fn pkgbase(pkgname: &str) -> &str {
    pkgname.rsplit_once('-').map_or(pkgname, |(b, _)| b)
}

/**
 * Return the `PKGVERSION` portion of a package name, i.e. everything after
 * the final `-`, or the empty string if no `-` is present.
 */
#[must_use]
pub fn pkgversion(pkgname: &str) -> &str {
    pkgname.rsplit_once('-').map_or("", |(_, v)| v)
}

/**
 * Return the `PKGVERSION_NOREV` portion of a package version, i.e. the
 * version with any trailing `nb<n>` revision marker stripped.
 *
 * Splits at the final `nb` substring, matching the behaviour of
 * [`pkgrevision`].  Returns the input unchanged when no `nb` marker is
 * present.
 */
#[must_use]
pub fn pkgversion_norev(pkgversion: &str) -> &str {
    pkgversion
        .rsplit_once("nb")
        .map_or(pkgversion, |(before, _)| before)
}

/**
 * Return the `PKGREVISION` parsed from a package version, i.e. the
 * integer following the final `nb`.
 *
 * Returns [`None`] when no `nb` marker is present, [`Some(0)`] when the
 * marker is present but the digits cannot be parsed as an [`i64`] (or
 * are absent entirely).
 */
#[must_use]
pub fn pkgrevision(pkgversion: &str) -> Option<i64> {
    pkgversion
        .rsplit_once("nb")
        .map(|(_, v)| v.parse::<i64>().unwrap_or(0))
}

impl PkgName {
    /**
     * Create a new [`PkgName`] from a [`str`] reference.
     */
    #[must_use]
    pub fn new(pkgname: &str) -> Self {
        let split = pkgname.rfind('-').unwrap_or(pkgname.len());
        Self {
            pkgname: pkgname.to_string(),
            split,
        }
    }

    /**
     * Return a [`str`] reference containing the original `PKGNAME` used to
     * create this instance.
     */
    #[must_use]
    pub fn pkgname(&self) -> &str {
        &self.pkgname
    }

    /**
     * Return a [`str`] reference containing the `PKGBASE` portion of the
     * package name, i.e.  everything up to the final `-` and the version
     * number.
     */
    #[must_use]
    pub fn pkgbase(&self) -> &str {
        &self.pkgname[..self.split]
    }

    /**
     * Return a [`str`] reference containing the full `PKGVERSION` of the
     * package name, i.e. everything after the final `-`.  If no `-` was found
     * in the [`str`] used to create this [`PkgName`] then this will be an
     * empty string.
     */
    #[must_use]
    pub fn pkgversion(&self) -> &str {
        if self.split < self.pkgname.len() {
            &self.pkgname[self.split + 1..]
        } else {
            ""
        }
    }

    /**
     * Return a [`str`] reference containing the `PKGVERSION_NOREV` of the
     * package name, i.e. the version with any `nb<x>` revision marker
     * stripped.
     */
    #[must_use]
    pub fn pkgversion_norev(&self) -> &str {
        pkgversion_norev(self.pkgversion())
    }

    /**
     * Return the `PKGREVISION` of the package name.  See [`pkgrevision`]
     * for the parsing rules.
     */
    #[must_use]
    pub fn pkgrevision(&self) -> Option<i64> {
        pkgrevision(self.pkgversion())
    }
}

impl From<&str> for PkgName {
    fn from(s: &str) -> Self {
        Self::new(s)
    }
}

impl From<String> for PkgName {
    fn from(s: String) -> Self {
        Self::new(&s)
    }
}

impl From<&String> for PkgName {
    fn from(s: &String) -> Self {
        Self::new(s)
    }
}

impl std::fmt::Display for PkgName {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.pkgname)
    }
}

impl PartialEq<str> for PkgName {
    fn eq(&self, other: &str) -> bool {
        self.pkgname == other
    }
}

impl PartialEq<&str> for PkgName {
    fn eq(&self, other: &&str) -> bool {
        &self.pkgname == other
    }
}

impl PartialEq<String> for PkgName {
    fn eq(&self, other: &String) -> bool {
        &self.pkgname == other
    }
}

impl FromStr for PkgName {
    type Err = std::convert::Infallible;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self::new(s))
    }
}

impl AsRef<str> for PkgName {
    fn as_ref(&self) -> &str {
        &self.pkgname
    }
}

impl Borrow<str> for PkgName {
    fn borrow(&self) -> &str {
        &self.pkgname
    }
}

// Hash must be consistent with Borrow<str> - only hash the pkgname field
// so that HashMap::get("foo-1.0") works when the key is PkgName::new("foo-1.0")
impl Hash for PkgName {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.pkgname.hash(state);
    }
}

impl crate::kv::FromKv for PkgName {
    fn from_kv(value: &str, _span: crate::kv::Span) -> crate::kv::Result<Self> {
        Ok(Self::new(value))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn pkgname_full() {
        let pkg = PkgName::new("mktool-1.3.2nb2");
        assert_eq!(format!("{pkg}"), "mktool-1.3.2nb2");
        assert_eq!(pkg.pkgname(), "mktool-1.3.2nb2");
        assert_eq!(pkg.pkgbase(), "mktool");
        assert_eq!(pkg.pkgversion(), "1.3.2nb2");
        assert_eq!(pkg.pkgrevision(), Some(2));
    }

    #[test]
    fn pkgname_broken_pkgrevision() {
        let pkg = PkgName::new("mktool-1nb3alpha2nb");
        assert_eq!(pkg.pkgbase(), "mktool");
        assert_eq!(pkg.pkgversion(), "1nb3alpha2nb");
        assert_eq!(pkg.pkgrevision(), Some(0));
    }

    #[test]
    fn pkgname_no_version() {
        let pkg = PkgName::new("mktool");
        assert_eq!(pkg.pkgbase(), "mktool");
        assert_eq!(pkg.pkgversion(), "");
        assert_eq!(pkg.pkgrevision(), None);
    }

    #[test]
    fn pkgname_from() {
        let pkg = PkgName::from("mktool-1.3.2nb2");
        assert_eq!(pkg.pkgname(), "mktool-1.3.2nb2");
        let pkg = PkgName::from(String::from("mktool-1.3.2nb2"));
        assert_eq!(pkg.pkgname(), "mktool-1.3.2nb2");
        let s = String::from("mktool-1.3.2nb2");
        let pkg = PkgName::from(&s);
        assert_eq!(pkg.pkgname(), "mktool-1.3.2nb2");
    }

    #[test]
    fn pkgname_from_str() -> Result<(), std::convert::Infallible> {
        use std::str::FromStr;

        let pkg = PkgName::from_str("mktool-1.3.2nb2")?;
        assert_eq!(pkg.pkgname(), "mktool-1.3.2nb2");

        let pkg: PkgName = "foo-2.0".parse()?;
        assert_eq!(pkg.pkgbase(), "foo");
        Ok(())
    }

    #[test]
    fn pkgname_partial_eq() {
        let pkg = PkgName::new("mktool-1.3.2nb2");
        assert_eq!(pkg, *"mktool-1.3.2nb2");
        assert_eq!(pkg, "mktool-1.3.2nb2");
        assert_eq!(pkg, "mktool-1.3.2nb2".to_string());
        assert_ne!(pkg, "notmktool-1.0");
    }

    #[test]
    fn pkgname_as_ref() {
        let pkg = PkgName::new("mktool-1.3.2nb2");
        let s: &str = pkg.as_ref();
        assert_eq!(s, "mktool-1.3.2nb2");

        // Test that it works with generic functions expecting AsRef<str>
        fn takes_asref(s: impl AsRef<str>) -> usize {
            s.as_ref().len()
        }
        assert_eq!(takes_asref(&pkg), 15);
    }

    #[test]
    fn pkgname_borrow() {
        use std::collections::HashMap;

        // Test that PkgName can be used as HashMap key with &str lookup
        let mut map: HashMap<PkgName, i32> = HashMap::new();
        map.insert(PkgName::new("foo-1.0"), 42);

        // Can look up by &str due to Borrow<str>
        assert_eq!(map.get("foo-1.0"), Some(&42));
        assert_eq!(map.get("bar-2.0"), None);
    }

    #[test]
    #[cfg(feature = "serde")]
    fn pkgname_serde() -> Result<(), serde_json::Error> {
        let pkg = PkgName::new("mktool-1.3.2nb2");
        let se = serde_json::to_string(&pkg)?;
        let de: PkgName = serde_json::from_str(&se)?;
        assert_eq!(se, "\"mktool-1.3.2nb2\"");
        assert_eq!(pkg, de);
        assert_eq!(de.pkgname(), "mktool-1.3.2nb2");
        assert_eq!(de.pkgbase(), "mktool");
        assert_eq!(de.pkgversion(), "1.3.2nb2");
        assert_eq!(de.pkgrevision(), Some(2));
        Ok(())
    }
}