quack_rs/validate/semver.rs
1// SPDX-License-Identifier: MIT
2// Copyright 2026 Tom F. <https://github.com/tomtom215/>
3// My way of giving something small back to the open source community
4// and encouraging more Rust development!
5
6//! Semantic versioning validation for `DuckDB` community extensions.
7//!
8//! [`validate_semver`] checks strict semantic versioning,
9//! [`validate_extension_version`] checks the (much looser) `extension.version`
10//! field of a community-extension `description.yml`, and
11//! [`classify_extension_version`] maps a version onto `DuckDB`'s stability tiers.
12//!
13//! # `DuckDB` Extension Versioning Scheme
14//!
15//! `DuckDB` core extensions use a three-tier versioning scheme:
16//!
17//! | Level | Format | Example | Meaning |
18//! |-------|--------|---------|---------|
19//! | **Unstable** | Short git hash | `690bfc5` | No stability guarantees |
20//! | **Pre-release** | `v0.y.z` | `v0.1.0` | Working toward stability, semver applies |
21//! | **Stable** | `vx.y.z` (x>0) | `v1.0.0` | Full semver, backwards-compatible API |
22//!
23//! `DuckDB`'s page writes the semver tiers with a leading `v`, and the version
24//! extension-ci-tools stamps into a binary is the git tag at `HEAD`
25//! (conventionally `vX.Y.Z`) or else the short hash, so
26//! [`classify_extension_version`] accepts the `v` as optional.
27//!
28//! Use [`classify_extension_version`] to determine which tier a version falls into,
29//! or [`validate_extension_version`] to accept both semver and git-hash formats.
30//!
31//! # Reference
32//!
33//! - <https://semver.org/>
34//! - <https://duckdb.org/docs/extensions/versioning>
35
36use crate::error::ExtensionError;
37
38/// Validates that a version string is valid semantic versioning.
39///
40/// Accepts versions in the form `MAJOR.MINOR.PATCH` with optional
41/// pre-release (`-alpha.1`) and build metadata (`+build.123`) suffixes.
42///
43/// # Rules
44///
45/// - Must have exactly three numeric components separated by dots
46/// - Components must not have leading zeros (except `0` itself)
47/// - Pre-release identifiers are alphanumeric with dots/hyphens
48/// - Build metadata follows a `+` and is alphanumeric with dots/hyphens
49///
50/// # Errors
51///
52/// Returns `ExtensionError` if the version is not valid semver.
53///
54/// # Example
55///
56/// ```rust
57/// use quack_rs::validate::validate_semver;
58///
59/// assert!(validate_semver("1.0.0").is_ok());
60/// assert!(validate_semver("0.1.0").is_ok());
61/// assert!(validate_semver("1.2.3-alpha.1").is_ok());
62/// assert!(validate_semver("1.2.3+build.456").is_ok());
63/// assert!(validate_semver("1.2.3-rc.1+build.456").is_ok());
64/// assert!(validate_semver("1.2").is_err());
65/// assert!(validate_semver("v1.0.0").is_err());
66/// assert!(validate_semver("01.0.0").is_err());
67/// ```
68pub fn validate_semver(version: &str) -> Result<(), ExtensionError> {
69 if version.is_empty() {
70 return Err(ExtensionError::new("version must not be empty"));
71 }
72
73 // Split off build metadata first (after +)
74 let (version_pre, _build) = match version.split_once('+') {
75 Some((v, b)) => {
76 validate_identifiers(b, "build metadata")?;
77 (v, Some(b))
78 }
79 None => (version, None),
80 };
81
82 // Split off pre-release (after -)
83 let (core, _pre) = match version_pre.split_once('-') {
84 Some((c, p)) => {
85 validate_identifiers(p, "pre-release")?;
86 (c, Some(p))
87 }
88 None => (version_pre, None),
89 };
90
91 // Parse core version: MAJOR.MINOR.PATCH
92 let parts: Vec<&str> = core.split('.').collect();
93 if parts.len() != 3 {
94 return Err(ExtensionError::new(format!(
95 "version '{version}' must have exactly three components (MAJOR.MINOR.PATCH), got {}",
96 parts.len()
97 )));
98 }
99
100 for (i, &part) in parts.iter().enumerate() {
101 let label = ["major", "minor", "patch"][i];
102 validate_numeric_component(part, label, version)?;
103 }
104
105 Ok(())
106}
107
108/// The stability level of a `DuckDB` extension version.
109///
110/// `DuckDB` core extensions use three tiers of stability, each with different
111/// expectations for API stability, release cadence, and semver semantics.
112///
113/// # Reference
114///
115/// See the [`DuckDB` extension versioning docs](https://duckdb.org/docs/extensions/versioning)
116/// for the full specification.
117#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
118pub enum ExtensionStability {
119 /// Version is a short git hash (e.g., `690bfc5`).
120 ///
121 /// No stability guarantees. Functionality may change or be removed
122 /// completely with every release. No structured release cycle.
123 Unstable,
124 /// Version is semver `0.y.z` (e.g., `0.1.0`).
125 ///
126 /// Working toward stability. Semver semantics apply, but the API is
127 /// not yet considered stable. Breaking changes may occur in minor versions.
128 PreRelease,
129 /// Version is semver `x.y.z` where `x > 0` (e.g., `1.0.0`).
130 ///
131 /// Full semver semantics apply. The API is stable and will only change
132 /// in backwards-incompatible ways when the major version is bumped.
133 Stable,
134}
135
136impl std::fmt::Display for ExtensionStability {
137 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
138 match self {
139 Self::Unstable => f.write_str("unstable"),
140 Self::PreRelease => f.write_str("pre-release"),
141 Self::Stable => f.write_str("stable"),
142 }
143 }
144}
145
146/// Classifies an extension version into its stability level.
147///
148/// This follows the `DuckDB` core extension versioning scheme:
149/// - **Unstable**: a short git hash (7+ lowercase hex characters)
150/// - **Pre-release**: semver `0.y.z`
151/// - **Stable**: semver `x.y.z` where `x > 0`
152///
153/// The semver forms may carry one leading `v` (`v0.1.0`, `v1.0.0`): `DuckDB`'s
154/// [versioning page](https://duckdb.org/docs/current/extensions/versioning_of_extensions.html)
155/// writes the tiers that way, and extension-ci-tools
156/// (`scripts/configure_helper.py`) stamps the git tag at `HEAD` — usually
157/// `vX.Y.Z` — as the extension version. `DuckDB` itself treats the version as
158/// an opaque string (`extension_load.cpp` only stores and compares it). The
159/// returned `&str` is the input, unchanged.
160///
161/// # Errors
162///
163/// Returns `ExtensionError` if the version string is empty or does not match
164/// any recognized format.
165///
166/// # Example
167///
168/// ```rust
169/// use quack_rs::validate::semver::{classify_extension_version, ExtensionStability};
170///
171/// let (stability, _) = classify_extension_version("1.0.0").unwrap();
172/// assert_eq!(stability, ExtensionStability::Stable);
173///
174/// let (stability, _) = classify_extension_version("0.1.0").unwrap();
175/// assert_eq!(stability, ExtensionStability::PreRelease);
176///
177/// let (stability, _) = classify_extension_version("v1.2.0").unwrap();
178/// assert_eq!(stability, ExtensionStability::Stable);
179///
180/// let (stability, _) = classify_extension_version("690bfc5").unwrap();
181/// assert_eq!(stability, ExtensionStability::Unstable);
182/// ```
183pub fn classify_extension_version(
184 version: &str,
185) -> Result<(ExtensionStability, &str), ExtensionError> {
186 if version.is_empty() {
187 return Err(ExtensionError::new("extension version must not be empty"));
188 }
189
190 // Try semver first, with at most one leading `v`. A git hash is lowercase
191 // hex, so it can never start with `v` and the two forms cannot collide.
192 if version.contains('.') {
193 let semver = version.strip_prefix('v').unwrap_or(version);
194 validate_semver(semver)?;
195 let major = semver.split('.').next().unwrap_or("0");
196 let stability = if major == "0" {
197 ExtensionStability::PreRelease
198 } else {
199 ExtensionStability::Stable
200 };
201 return Ok((stability, version));
202 }
203
204 // Try git hash: 7+ lowercase hex characters
205 if version.len() >= 7
206 && version.len() <= 40
207 && version
208 .bytes()
209 .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
210 {
211 return Ok((ExtensionStability::Unstable, version));
212 }
213
214 Err(ExtensionError::new(format!(
215 "extension version '{version}' is not a valid semver version or git hash; \
216 expected MAJOR.MINOR.PATCH or a 7-40 character lowercase hex hash"
217 )))
218}
219
220/// Maximum length of an extension version string.
221///
222/// Not a `DuckDB` rule — a sanity bound, comfortably above the 40-character git
223/// hash that is the longest form anyone actually uses.
224const MAX_VERSION_LEN: usize = 64;
225
226/// Validates an extension version string for a community-extension
227/// `description.yml`.
228///
229/// **This is deliberately permissive.** `DuckDB`'s community-extension
230/// documentation specifies no version format — it says only that the descriptor
231/// carries "the version of the extension" and points at existing extensions as
232/// examples. In the `duckdb/community-extensions` repository at commit
233/// `5ae7df8`, 334 of the 346 `description.yml` files declare a version,
234/// and 42 of those are a date-based build id — 41 `YYYYMMDDNN` like
235/// `2025120401`, one `YYYYMMDD` — which is neither semver nor a git hash (one
236/// more is the four-part `0.1.5.5`). Rejecting those would tell one published
237/// extension in eight that its descriptor is invalid.
238///
239/// So this checks only what would actually break: an empty version, one longer
240/// than 64 characters, or one containing anything outside
241/// `[A-Za-z0-9._+-]` — whitespace, path separators and control characters, all
242/// of which would corrupt the metadata the version ends up in.
243///
244/// Use [`classify_extension_version`] when you want `DuckDB`'s three-tier
245/// stability scheme, which *is* documented and *is* strict.
246///
247/// # Errors
248///
249/// Returns `ExtensionError` if the version is empty, too long, or contains a
250/// character outside the allowed set.
251///
252/// # Example
253///
254/// ```rust
255/// use quack_rs::validate::validate_extension_version;
256///
257/// assert!(validate_extension_version("1.0.0").is_ok());
258/// assert!(validate_extension_version("0.1.0").is_ok());
259/// assert!(validate_extension_version("690bfc5").is_ok());
260/// // A date-based build id, as 42 published community extensions use.
261/// assert!(validate_extension_version("2025120401").is_ok());
262///
263/// assert!(validate_extension_version("").is_err());
264/// assert!(validate_extension_version("1.0.0 beta").is_err()); // whitespace
265/// assert!(validate_extension_version("../etc/passwd").is_err()); // path separator
266/// ```
267pub fn validate_extension_version(version: &str) -> Result<(), ExtensionError> {
268 if version.is_empty() {
269 return Err(ExtensionError::new("extension version must not be empty"));
270 }
271 if version.len() > MAX_VERSION_LEN {
272 return Err(ExtensionError::new(format!(
273 "extension version is {} characters; the maximum is {MAX_VERSION_LEN}",
274 version.len()
275 )));
276 }
277 if let Some(bad) = version
278 .chars()
279 .find(|c| !(c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '+' | '-')))
280 {
281 return Err(ExtensionError::new(format!(
282 "extension version '{version}' contains {bad:?}; only ASCII letters, \
283 digits, '.', '_', '+' and '-' are allowed"
284 )));
285 }
286 Ok(())
287}
288
289/// Validates a single numeric version component (no leading zeros).
290fn validate_numeric_component(
291 s: &str,
292 label: &str,
293 full_version: &str,
294) -> Result<(), ExtensionError> {
295 if s.is_empty() {
296 return Err(ExtensionError::new(format!(
297 "version '{full_version}': {label} component is empty"
298 )));
299 }
300
301 if !s.bytes().all(|b| b.is_ascii_digit()) {
302 return Err(ExtensionError::new(format!(
303 "version '{full_version}': {label} component '{s}' is not a valid number"
304 )));
305 }
306
307 // No leading zeros (except "0" itself)
308 if s.len() > 1 && s.starts_with('0') {
309 return Err(ExtensionError::new(format!(
310 "version '{full_version}': {label} component '{s}' has a leading zero"
311 )));
312 }
313
314 Ok(())
315}
316
317/// Validates dot-separated identifiers (pre-release or build metadata).
318fn validate_identifiers(s: &str, label: &str) -> Result<(), ExtensionError> {
319 if s.is_empty() {
320 return Err(ExtensionError::new(format!(
321 "{label} identifier must not be empty"
322 )));
323 }
324
325 for ident in s.split('.') {
326 if ident.is_empty() {
327 return Err(ExtensionError::new(format!(
328 "{label} contains an empty identifier"
329 )));
330 }
331 if !ident
332 .bytes()
333 .all(|b| b.is_ascii_alphanumeric() || b == b'-')
334 {
335 return Err(ExtensionError::new(format!(
336 "{label} identifier '{ident}' contains invalid characters"
337 )));
338 }
339 // SemVer 2.0.0 §9: "Numeric identifiers MUST NOT include leading
340 // zeroes." §10 sets no such rule for build metadata.
341 if label == "pre-release"
342 && ident.len() > 1
343 && ident.starts_with('0')
344 && ident.bytes().all(|b| b.is_ascii_digit())
345 {
346 return Err(ExtensionError::new(format!(
347 "pre-release identifier '{ident}' is numeric with a leading zero, which SemVer \
348 forbids"
349 )));
350 }
351 }
352
353 Ok(())
354}
355
356#[cfg(test)]
357mod tests {
358 use super::*;
359
360 #[test]
361 fn valid_simple() {
362 assert!(validate_semver("1.0.0").is_ok());
363 assert!(validate_semver("0.1.0").is_ok());
364 assert!(validate_semver("0.0.1").is_ok());
365 assert!(validate_semver("123.456.789").is_ok());
366 }
367
368 /// §9 forbids leading zeros in numeric pre-release identifiers, and the
369 /// `semver` crate refuses these three, which this validator accepted.
370 /// Against that crate over 232,615 unique random strings (seed 20260924)
371 /// it now differs only on a component above `u64::MAX`, which `SemVer`
372 /// allows. Alphanumeric identifiers, a lone `0`, and build metadata may
373 /// still start with 0.
374 #[test]
375 fn numeric_prerelease_identifiers_with_leading_zeros_are_rejected() {
376 for bad in ["1.0.0-01", "1.0.0-a.01", "8.9.209-0003"] {
377 assert!(validate_semver(bad).is_err(), "{bad}");
378 }
379 for good in [
380 "1.0.0-0",
381 "1.0.0-0a",
382 "1.0.0-a.0",
383 "1.0.0+001",
384 "1.0.0-0.3.7",
385 ] {
386 assert!(validate_semver(good).is_ok(), "{good}");
387 }
388 }
389
390 #[test]
391 fn valid_prerelease() {
392 assert!(validate_semver("1.0.0-alpha").is_ok());
393 assert!(validate_semver("1.0.0-alpha.1").is_ok());
394 assert!(validate_semver("1.0.0-0.3.7").is_ok());
395 assert!(validate_semver("1.0.0-x.7.z.92").is_ok());
396 assert!(validate_semver("1.0.0-rc-1").is_ok());
397 }
398
399 #[test]
400 fn valid_build_metadata() {
401 assert!(validate_semver("1.0.0+build").is_ok());
402 assert!(validate_semver("1.0.0+build.456").is_ok());
403 assert!(validate_semver("1.0.0+20130313144700").is_ok());
404 }
405
406 #[test]
407 fn valid_prerelease_and_build() {
408 assert!(validate_semver("1.0.0-alpha+001").is_ok());
409 assert!(validate_semver("1.0.0-rc.1+build.456").is_ok());
410 }
411
412 #[test]
413 fn empty_rejected() {
414 assert!(validate_semver("").is_err());
415 }
416
417 #[test]
418 fn two_components_rejected() {
419 let err = validate_semver("1.2").unwrap_err();
420 assert!(err.as_str().contains("three components"));
421 }
422
423 #[test]
424 fn four_components_rejected() {
425 let err = validate_semver("1.2.3.4").unwrap_err();
426 assert!(err.as_str().contains("three components"));
427 }
428
429 #[test]
430 fn leading_v_rejected() {
431 let err = validate_semver("v1.0.0").unwrap_err();
432 assert!(err.as_str().contains("not a valid number"));
433 }
434
435 #[test]
436 fn leading_zero_rejected() {
437 assert!(validate_semver("01.0.0").is_err());
438 assert!(validate_semver("1.01.0").is_err());
439 assert!(validate_semver("1.0.01").is_err());
440 }
441
442 /// semver.org items 9 and 10: pre-release and build identifiers are
443 /// non-empty runs of `[0-9A-Za-z-]` separated by dots.
444 #[test]
445 fn malformed_prerelease_or_build_identifiers_rejected() {
446 for (version, message) in [
447 ("1.0.0-", "pre-release identifier must not be empty"),
448 ("1.0.0+", "build metadata identifier must not be empty"),
449 ("1.0.0-alpha..1", "pre-release contains an empty identifier"),
450 ("1.0.0-alpha.", "pre-release contains an empty identifier"),
451 (
452 "1.0.0+build..1",
453 "build metadata contains an empty identifier",
454 ),
455 (
456 "1.0.0-al_pha",
457 "pre-release identifier 'al_pha' contains invalid",
458 ),
459 (
460 "1.0.0+b!d",
461 "build metadata identifier 'b!d' contains invalid",
462 ),
463 (
464 "1.0.0-rc.1+sha.5114f85+x",
465 "build metadata identifier '5114f85+x'",
466 ),
467 ] {
468 let err = validate_semver(version).expect_err(version);
469 assert!(err.as_str().contains(message), "{version}: {err}");
470 }
471 }
472
473 #[test]
474 fn leading_zero_on_zero_itself_accepted() {
475 assert!(validate_semver("0.0.0").is_ok());
476 }
477
478 #[test]
479 fn non_numeric_rejected() {
480 assert!(validate_semver("a.b.c").is_err());
481 assert!(validate_semver("1.0.x").is_err());
482 }
483
484 #[test]
485 fn empty_component_rejected() {
486 assert!(validate_semver("1..0").is_err());
487 assert!(validate_semver(".1.0").is_err());
488 }
489
490 #[test]
491 fn single_number_rejected() {
492 assert!(validate_semver("1").is_err());
493 }
494
495 // --- Extension version classification tests ---
496
497 #[test]
498 fn classify_stable() {
499 let (stability, _) = classify_extension_version("1.0.0").unwrap();
500 assert_eq!(stability, ExtensionStability::Stable);
501 }
502
503 #[test]
504 fn classify_stable_high_major() {
505 let (stability, _) = classify_extension_version("13.11.0").unwrap();
506 assert_eq!(stability, ExtensionStability::Stable);
507 }
508
509 #[test]
510 fn classify_pre_release() {
511 let (stability, _) = classify_extension_version("0.1.0").unwrap();
512 assert_eq!(stability, ExtensionStability::PreRelease);
513 }
514
515 #[test]
516 fn classify_pre_release_with_suffix() {
517 let (stability, _) = classify_extension_version("0.1.0-alpha.1").unwrap();
518 assert_eq!(stability, ExtensionStability::PreRelease);
519 }
520
521 #[test]
522 fn classify_unstable_git_hash() {
523 let (stability, _) = classify_extension_version("690bfc5").unwrap();
524 assert_eq!(stability, ExtensionStability::Unstable);
525 }
526
527 #[test]
528 fn classify_unstable_long_hash() {
529 let (stability, _) =
530 classify_extension_version("d9e5cc104c61e4a2b3f8a9c7d1e5f0a2b4c6d8e0").unwrap();
531 assert_eq!(stability, ExtensionStability::Unstable);
532 }
533
534 /// `DuckDB`'s versioning page writes the tiers as `v0.y.z` / `vx.y.z` and
535 /// its examples as `v0.1.0` / `v1.0.0`; extension-ci-tools and the
536 /// community build stamp the git tag, which is conventionally `vX.Y.Z`.
537 #[test]
538 fn classify_accepts_a_leading_v() {
539 for (version, expected) in [
540 ("v0.1.0", ExtensionStability::PreRelease),
541 ("v1.0.0", ExtensionStability::Stable),
542 ("v13.11.0-rc.1", ExtensionStability::Stable),
543 ] {
544 let (stability, returned) = classify_extension_version(version).unwrap();
545 assert_eq!(stability, expected, "{version}");
546 assert_eq!(returned, version, "the input is returned unchanged");
547 }
548 for version in [
549 "v", "v1", "v1.0", "vv1.0.0", "V1.0.0", "v01.0.0", "v690bfc5",
550 ] {
551 assert!(classify_extension_version(version).is_err(), "{version}");
552 }
553 }
554
555 #[test]
556 fn classify_empty_rejected() {
557 assert!(classify_extension_version("").is_err());
558 }
559
560 #[test]
561 fn classify_uppercase_hash_rejected() {
562 assert!(classify_extension_version("690BFC5").is_err());
563 }
564
565 #[test]
566 fn classify_too_short_hash_rejected() {
567 assert!(classify_extension_version("abc12").is_err());
568 }
569
570 #[test]
571 fn classify_not_hex_rejected() {
572 assert!(classify_extension_version("not-valid").is_err());
573 }
574
575 #[test]
576 fn validate_extension_version_semver() {
577 assert!(validate_extension_version("1.0.0").is_ok());
578 assert!(validate_extension_version("0.1.0").is_ok());
579 }
580
581 #[test]
582 fn validate_extension_version_hash() {
583 assert!(validate_extension_version("690bfc5").is_ok());
584 }
585
586 #[test]
587 fn validate_extension_version_invalid() {
588 assert!(validate_extension_version("").is_err());
589 assert!(
590 validate_extension_version("1.0.0 beta").is_err(),
591 "whitespace"
592 );
593 assert!(
594 validate_extension_version("../etc/passwd").is_err(),
595 "path separator"
596 );
597 assert!(
598 validate_extension_version("v1.0.0\n").is_err(),
599 "control character"
600 );
601 assert!(
602 validate_extension_version(&"a".repeat(65)).is_err(),
603 "too long"
604 );
605 }
606
607 #[test]
608 fn validate_extension_version_accepts_what_duckdb_accepts() {
609 // DuckDB's community-extension docs specify no version format. These
610 // are all in use by published extensions, and rejecting them would make
611 // the validator wrong about most of the ecosystem.
612 for version in [
613 "1.0.0",
614 "0.1.0",
615 "690bfc5",
616 "2025120401", // date-based: 42 of 334 versioned corpus descriptors
617 "20260707", // the one YYYYMMDD form in the corpus
618 "0.1.5.5", // four-part, also published
619 "0.1.0-alpha+build.1",
620 "v2.6.1",
621 &"a".repeat(64),
622 ] {
623 assert!(
624 validate_extension_version(version).is_ok(),
625 "{version} should be accepted"
626 );
627 }
628 }
629
630 #[test]
631 fn stability_display() {
632 assert_eq!(ExtensionStability::Unstable.to_string(), "unstable");
633 assert_eq!(ExtensionStability::PreRelease.to_string(), "pre-release");
634 assert_eq!(ExtensionStability::Stable.to_string(), "stable");
635 }
636}