pkgsrc/pkgname.rs
1/*
2 * Copyright (c) 2026 Jonathan Perkin <jonathan@perkin.org.uk>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
16
17/*!
18 * Package name parsing into base, version, and revision components.
19 *
20 * In pkgsrc, every package has a `PKGNAME` that uniquely identifies a specific
21 * version of a package.
22 *
23 * ```text
24 * PKGNAME = PKGBASE-PKGVERSION
25 * PKGVERSION = VERSION[nbPKGREVISION]
26 * ```
27 *
28 * For example, `mktool-1.4.2nb3` breaks down as:
29 *
30 * - **PKGBASE**: `mktool` - the package name
31 * - **PKGVERSION**: `1.4.2nb3` - the full version string
32 * - **VERSION**: `1.4.2` - the upstream version
33 * - **PKGREVISION**: `3` - the pkgsrc-specific revision
34 *
35 * The `PKGBASE` and `PKGVERSION` are separated by the last hyphen (`-`) in the
36 * string. The `PKGREVISION` suffix (`nb` followed by a number) indicates
37 * pkgsrc-specific changes that do not correspond to an upstream release.
38 *
39 * # Examples
40 *
41 * ```
42 * use pkgsrc::PkgName;
43 *
44 * let pkg = PkgName::new("nginx-1.25.3nb2");
45 * assert_eq!(pkg.pkgbase(), "nginx");
46 * assert_eq!(pkg.pkgversion(), "1.25.3nb2");
47 * assert_eq!(pkg.pkgrevision(), Some(2));
48 *
49 * // Package with hyphenated name
50 * let pkg = PkgName::new("p5-libwww-6.77");
51 * assert_eq!(pkg.pkgbase(), "p5-libwww");
52 * assert_eq!(pkg.pkgversion(), "6.77");
53 * assert_eq!(pkg.pkgrevision(), None);
54 *
55 * // Package without revision
56 * let pkg = PkgName::new("curl-8.5.0");
57 * assert_eq!(pkg.pkgbase(), "curl");
58 * assert_eq!(pkg.pkgversion(), "8.5.0");
59 * assert_eq!(pkg.pkgrevision(), None);
60 * ```
61 *
62 * # PKGREVISION
63 *
64 * The `PKGREVISION` is incremented by pkgsrc maintainers when:
65 *
66 * - A dependency is updated and the package needs rebuilding
67 * - pkgsrc-specific patches are modified
68 * - Build or packaging changes are made
69 *
70 * For version comparison, `1.0nb1` > `1.0` > `1.0rc1`. See the [`dewey`] module
71 * for details on version comparison rules.
72 *
73 * [`dewey`]: crate::dewey
74 */
75
76use std::borrow::Borrow;
77use std::hash::{Hash, Hasher};
78use std::str::FromStr;
79
80#[cfg(feature = "serde")]
81use serde_with::{DeserializeFromStr, SerializeDisplay};
82
83/**
84 * Parse a `PKGNAME` into its constituent parts.
85 *
86 * In pkgsrc terminology a `PKGNAME` is made up of three parts:
87 *
88 * * `PKGBASE` contains the name of the package
89 * * `PKGVERSION` contains the full version string
90 * * `PKGREVISION` is an optional package revision denoted by `nb` followed by
91 * a number.
92 *
93 * The name and version are split at the last `-`, and the revision, if
94 * specified, should be located at the end of the version.
95 *
96 * This module does not enforce strict formatting. If a `PKGNAME` is not well
97 * formed then values may be empty or [`None`].
98 *
99 * # Examples
100 *
101 * ```
102 * use pkgsrc::PkgName;
103 *
104 * // A well formed package name.
105 * let pkg = PkgName::new("mktool-1.3.2nb2");
106 * assert_eq!(pkg.pkgname(), "mktool-1.3.2nb2");
107 * assert_eq!(pkg.pkgbase(), "mktool");
108 * assert_eq!(pkg.pkgversion(), "1.3.2nb2");
109 * assert_eq!(pkg.pkgrevision(), Some(2));
110 *
111 * // An invalid PKGREVISION that can likely only be created by accident.
112 * let pkg = PkgName::new("mktool-1.3.2nb");
113 * assert_eq!(pkg.pkgbase(), "mktool");
114 * assert_eq!(pkg.pkgversion(), "1.3.2nb");
115 * assert_eq!(pkg.pkgrevision(), Some(0));
116 *
117 * // A "-" in the version causes an incorrect split.
118 * let pkg = PkgName::new("mktool-1.3-2");
119 * assert_eq!(pkg.pkgbase(), "mktool-1.3");
120 * assert_eq!(pkg.pkgversion(), "2");
121 * assert_eq!(pkg.pkgrevision(), None);
122 *
123 * // Not well formed, but still accepted.
124 * let pkg = PkgName::new("mktool");
125 * assert_eq!(pkg.pkgbase(), "mktool");
126 * assert_eq!(pkg.pkgversion(), "");
127 * assert_eq!(pkg.pkgrevision(), None);
128 *
129 * // Doesn't make any sense, but whatever!
130 * let pkg = PkgName::new("1.0nb2");
131 * assert_eq!(pkg.pkgbase(), "1.0nb2");
132 * assert_eq!(pkg.pkgversion(), "");
133 * assert_eq!(pkg.pkgrevision(), None);
134 * ```
135 */
136#[derive(Clone, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
137#[cfg_attr(feature = "serde", derive(SerializeDisplay, DeserializeFromStr))]
138pub struct PkgName {
139 pkgname: String,
140 split: usize,
141 pkgrevision: Option<i64>,
142}
143
144impl PkgName {
145 /**
146 * Create a new [`PkgName`] from a [`str`] reference.
147 */
148 #[must_use]
149 pub fn new(pkgname: &str) -> Self {
150 let split = pkgname.rfind('-').unwrap_or(pkgname.len());
151 let pkgversion = if split < pkgname.len() {
152 &pkgname[split + 1..]
153 } else {
154 ""
155 };
156 let pkgrevision = match pkgversion.rsplit_once("nb") {
157 Some((_, v)) => v.parse::<i64>().ok().or(Some(0)),
158 None => None,
159 };
160 Self {
161 pkgname: pkgname.to_string(),
162 split,
163 pkgrevision,
164 }
165 }
166
167 /**
168 * Return a [`str`] reference containing the original `PKGNAME` used to
169 * create this instance.
170 */
171 #[must_use]
172 pub fn pkgname(&self) -> &str {
173 &self.pkgname
174 }
175
176 /**
177 * Return a [`str`] reference containing the `PKGBASE` portion of the
178 * package name, i.e. everything up to the final `-` and the version
179 * number.
180 */
181 #[must_use]
182 pub fn pkgbase(&self) -> &str {
183 &self.pkgname[..self.split]
184 }
185
186 /**
187 * Return a [`str`] reference containing the full `PKGVERSION` of the
188 * package name, i.e. everything after the final `-`. If no `-` was found
189 * in the [`str`] used to create this [`PkgName`] then this will be an
190 * empty string.
191 */
192 #[must_use]
193 pub fn pkgversion(&self) -> &str {
194 if self.split < self.pkgname.len() {
195 &self.pkgname[self.split + 1..]
196 } else {
197 ""
198 }
199 }
200
201 /**
202 * Return an optional `PKGREVISION`, i.e. the `nb<x>` suffix that denotes
203 * a pkgsrc revision. If any characters after the `nb` cannot be parsed
204 * as an [`i64`] then [`None`] is returned. If there are no characters at
205 * all after the `nb` then `Some(0)` is returned.
206 */
207 #[must_use]
208 pub const fn pkgrevision(&self) -> Option<i64> {
209 self.pkgrevision
210 }
211}
212
213impl From<&str> for PkgName {
214 fn from(s: &str) -> Self {
215 Self::new(s)
216 }
217}
218
219impl From<String> for PkgName {
220 fn from(s: String) -> Self {
221 Self::new(&s)
222 }
223}
224
225impl From<&String> for PkgName {
226 fn from(s: &String) -> Self {
227 Self::new(s)
228 }
229}
230
231impl std::fmt::Display for PkgName {
232 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
233 write!(f, "{}", self.pkgname)
234 }
235}
236
237impl PartialEq<str> for PkgName {
238 fn eq(&self, other: &str) -> bool {
239 self.pkgname == other
240 }
241}
242
243impl PartialEq<&str> for PkgName {
244 fn eq(&self, other: &&str) -> bool {
245 &self.pkgname == other
246 }
247}
248
249impl PartialEq<String> for PkgName {
250 fn eq(&self, other: &String) -> bool {
251 &self.pkgname == other
252 }
253}
254
255impl FromStr for PkgName {
256 type Err = std::convert::Infallible;
257
258 fn from_str(s: &str) -> Result<Self, Self::Err> {
259 Ok(Self::new(s))
260 }
261}
262
263impl AsRef<str> for PkgName {
264 fn as_ref(&self) -> &str {
265 &self.pkgname
266 }
267}
268
269impl Borrow<str> for PkgName {
270 fn borrow(&self) -> &str {
271 &self.pkgname
272 }
273}
274
275// Hash must be consistent with Borrow<str> - only hash the pkgname field
276// so that HashMap::get("foo-1.0") works when the key is PkgName::new("foo-1.0")
277impl Hash for PkgName {
278 fn hash<H: Hasher>(&self, state: &mut H) {
279 self.pkgname.hash(state);
280 }
281}
282
283impl crate::kv::FromKv for PkgName {
284 fn from_kv(value: &str, _span: crate::kv::Span) -> crate::kv::Result<Self> {
285 Ok(Self::new(value))
286 }
287}
288
289#[cfg(test)]
290mod tests {
291 use super::*;
292
293 #[test]
294 fn pkgname_full() {
295 let pkg = PkgName::new("mktool-1.3.2nb2");
296 assert_eq!(format!("{pkg}"), "mktool-1.3.2nb2");
297 assert_eq!(pkg.pkgname(), "mktool-1.3.2nb2");
298 assert_eq!(pkg.pkgbase(), "mktool");
299 assert_eq!(pkg.pkgversion(), "1.3.2nb2");
300 assert_eq!(pkg.pkgrevision(), Some(2));
301 }
302
303 #[test]
304 fn pkgname_broken_pkgrevision() {
305 let pkg = PkgName::new("mktool-1nb3alpha2nb");
306 assert_eq!(pkg.pkgbase(), "mktool");
307 assert_eq!(pkg.pkgversion(), "1nb3alpha2nb");
308 assert_eq!(pkg.pkgrevision(), Some(0));
309 }
310
311 #[test]
312 fn pkgname_no_version() {
313 let pkg = PkgName::new("mktool");
314 assert_eq!(pkg.pkgbase(), "mktool");
315 assert_eq!(pkg.pkgversion(), "");
316 assert_eq!(pkg.pkgrevision(), None);
317 }
318
319 #[test]
320 fn pkgname_from() {
321 let pkg = PkgName::from("mktool-1.3.2nb2");
322 assert_eq!(pkg.pkgname(), "mktool-1.3.2nb2");
323 let pkg = PkgName::from(String::from("mktool-1.3.2nb2"));
324 assert_eq!(pkg.pkgname(), "mktool-1.3.2nb2");
325 let s = String::from("mktool-1.3.2nb2");
326 let pkg = PkgName::from(&s);
327 assert_eq!(pkg.pkgname(), "mktool-1.3.2nb2");
328 }
329
330 #[test]
331 fn pkgname_from_str() -> Result<(), std::convert::Infallible> {
332 use std::str::FromStr;
333
334 let pkg = PkgName::from_str("mktool-1.3.2nb2")?;
335 assert_eq!(pkg.pkgname(), "mktool-1.3.2nb2");
336
337 let pkg: PkgName = "foo-2.0".parse()?;
338 assert_eq!(pkg.pkgbase(), "foo");
339 Ok(())
340 }
341
342 #[test]
343 fn pkgname_partial_eq() {
344 let pkg = PkgName::new("mktool-1.3.2nb2");
345 assert_eq!(pkg, *"mktool-1.3.2nb2");
346 assert_eq!(pkg, "mktool-1.3.2nb2");
347 assert_eq!(pkg, "mktool-1.3.2nb2".to_string());
348 assert_ne!(pkg, "notmktool-1.0");
349 }
350
351 #[test]
352 fn pkgname_as_ref() {
353 let pkg = PkgName::new("mktool-1.3.2nb2");
354 let s: &str = pkg.as_ref();
355 assert_eq!(s, "mktool-1.3.2nb2");
356
357 // Test that it works with generic functions expecting AsRef<str>
358 fn takes_asref(s: impl AsRef<str>) -> usize {
359 s.as_ref().len()
360 }
361 assert_eq!(takes_asref(&pkg), 15);
362 }
363
364 #[test]
365 fn pkgname_borrow() {
366 use std::collections::HashMap;
367
368 // Test that PkgName can be used as HashMap key with &str lookup
369 let mut map: HashMap<PkgName, i32> = HashMap::new();
370 map.insert(PkgName::new("foo-1.0"), 42);
371
372 // Can look up by &str due to Borrow<str>
373 assert_eq!(map.get("foo-1.0"), Some(&42));
374 assert_eq!(map.get("bar-2.0"), None);
375 }
376
377 #[test]
378 #[cfg(feature = "serde")]
379 fn pkgname_serde() -> Result<(), serde_json::Error> {
380 let pkg = PkgName::new("mktool-1.3.2nb2");
381 let se = serde_json::to_string(&pkg)?;
382 let de: PkgName = serde_json::from_str(&se)?;
383 assert_eq!(se, "\"mktool-1.3.2nb2\"");
384 assert_eq!(pkg, de);
385 assert_eq!(de.pkgname(), "mktool-1.3.2nb2");
386 assert_eq!(de.pkgbase(), "mktool");
387 assert_eq!(de.pkgversion(), "1.3.2nb2");
388 assert_eq!(de.pkgrevision(), Some(2));
389 Ok(())
390 }
391}