caixa_core/version.rs
1use std::fmt;
2
3use serde::{Deserialize, Serialize};
4use thiserror::Error;
5
6/// A caixa's pinned version — a thin typed wrapper over a String that parses
7/// as [`semver::Version`] on demand.
8///
9/// Stored as a String at rest so authoring a `caixa.lisp` stays a single
10/// quoted literal. The typed form is reached through [`Self::parse`].
11#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash)]
12#[serde(transparent)]
13pub struct CaixaVersion(pub String);
14
15impl CaixaVersion {
16 /// Parse and validate the wrapped string as semver.
17 pub fn parse(&self) -> Result<semver::Version, VersionError> {
18 semver::Version::parse(&self.0)
19 .map_err(|e| VersionError::Semver(self.0.clone(), e.to_string()))
20 }
21
22 /// Borrow the string form.
23 #[must_use]
24 pub const fn as_str(&self) -> &str {
25 self.0.as_str()
26 }
27}
28
29impl fmt::Display for CaixaVersion {
30 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31 f.write_str(&self.0)
32 }
33}
34
35impl From<String> for CaixaVersion {
36 fn from(s: String) -> Self {
37 Self(s)
38 }
39}
40
41impl From<&str> for CaixaVersion {
42 fn from(s: &str) -> Self {
43 Self(s.to_string())
44 }
45}
46
47/// Canonical Zig-style git-tag prefix every `feira publish` run writes
48/// and every downstream consumer of a published caixa reads. A caixa
49/// published at `:versao "0.1.0"` lands as a git tag `v0.1.0` on the
50/// source repo's `origin` remote — the [`crate::CaixaVersion`] value
51/// gates the version body, this constant gates the prefix the body
52/// composes under.
53///
54/// Two production-code consumers carry this prefix on the same git
55/// remote axis:
56///
57/// 1. [`caixa-feira`]'s `feira publish` verb (caixa-feira/src/cmd/publish.rs)
58/// — the writer. Its `--prefix` clap flag defaults to this string
59/// and the verb computes the tag as `format!("{prefix}{versao}")`
60/// before `git tag -a <tag>` + `git push origin <tag>`.
61/// 2. [`caixa-flux`]'s [`caixa-flux::cluster_bundle`] renderer
62/// (caixa-flux/src/lib.rs) — the reader. Its
63/// `ClusterBundleOpts::for_caixa` constructor defaults
64/// `git_ref: GitRefSpec::Tag(...)` to `<prefix><versao>` so the
65/// rendered `gitrepository.yaml` carries `ref: { tag: v<versao> }`
66/// pointing `FluxCD`'s `GitRepository` reconciler at the exact tag
67/// the publisher just wrote.
68///
69/// Until this lift landed both consumers carried the bare `"v"` byte
70/// inline — `caixa-feira/src/cmd/publish.rs:22`'s clap
71/// `default_value = "v"` and `caixa-flux/src/lib.rs:335`'s
72/// `format!("v{}", caixa.versao)` literal. A future Zig-style-tag
73/// convention rebrand (the substrate moving to plain `<versao>` tags
74/// once the GitHub releases UI normalizes around the bare form, to
75/// `release/<versao>` once a sibling forge convention adopts the
76/// `<type>/<value>` slash-namespaced shape, or to a per-edition
77/// override the operator pins through a future `:placement
78/// :tag-prefix` slot) without a coordinated edit on both sides would
79/// silently emit a `feira publish`-side tag at one shape (e.g.
80/// `release/0.1.0`) and a `cluster_bundle`-side `ref: { tag: v0.1.0 }`
81/// pointing at the prior shape — Flux's `GitRepository` reconciler
82/// would loop forever looking for an upstream `v0.1.0` ref the publish
83/// remote no longer carries, the dependent `HelmRelease`'s `chart:
84/// sourceRef` would never resolve, every per-Servico apply would
85/// silently come up with the prior reconciled state, and the failure
86/// would surface at `kubectl describe gitrepository` time (the
87/// `Status: Stalled` / `Reason: Failed` arm) far from the rebrand
88/// commit's source.
89///
90/// Lifting the literal to one `&'static str` constant closes the drift
91/// footgun structurally — both consumers read from the same memory,
92/// so any future rebrand reaches both sites by construction and a CI
93/// build that re-introduces a sibling inline `"v"` literal trips the
94/// peer pinning tests
95/// ([`caixa-feira`]'s `publish_prefix_default_pins_lifted_caixa_core_constant`,
96/// [`caixa-flux`]'s `cluster_bundle_default_git_tag_uses_lifted_caixa_core_prefix`)
97/// at the build-time fail-before-deploy posture every prior
98/// load-bearing-string lift on this surface
99/// ([`crate::DEFAULT_NAMESPACE`] a085b26,
100/// [`crate::DEFAULT_LIBRARY_NAME`] 41438dc,
101/// [`crate::DEFAULT_SERVICO_PORT`] 1e22add) establishes.
102///
103/// Authoring-side `:versao` gates already refuse the `"v"`-prefixed
104/// publish tag shape leaking back into a version body — every typed
105/// `:versao` surface (top-level `:versao`, `:upgrade-from :from`,
106/// `:deps :versao`, `:deps-dev :versao`, `:membros :versao`,
107/// `:children :versao`) routes through `semver::Version::parse` /
108/// [`parse_requirement`], both of which reject the `v`-prefix as
109/// invalid `SemVer`. The split — bare `SemVer` at the `:versao` slot,
110/// `v<versao>` at the published git-tag axis — is the convention this
111/// constant pins.
112pub const DEFAULT_PUBLISH_TAG_PREFIX: &str = "v";
113
114/// Canonical git remote name every `feira` writer-side verb pushes to —
115/// the destination handle the operator-out-of-the-loop publish + deploy
116/// chain (`feira publish`, `feira deploy --apply`, `feira app deploy
117/// --apply`) names when it invokes `git push <remote> <ref>` against
118/// the local clone of the source / k8s GitOps repo.
119///
120/// Three production-code consumers carry this remote name on the same
121/// `git push` axis:
122///
123/// 1. [`caixa-feira`]'s `feira publish` verb (caixa-feira/src/cmd/publish.rs)
124/// — the writer-side publish path. Its `--remote` clap flag defaults
125/// to this string and the verb runs `git push <remote> <tag>` to push
126/// the freshly written `v<versao>` tag upstream.
127/// 2. [`caixa-feira`]'s `feira deploy --apply` verb
128/// (caixa-feira/src/cmd/deploy.rs) — the writer-side Servico cluster-
129/// deploy path. Its `push_origin` helper runs `git push origin HEAD`
130/// against the k8s GitOps repo's working tree after upserting the
131/// Servico's entry into the cluster's lareira-fleet-programs
132/// HelmRelease values.
133/// 3. [`caixa-feira`]'s `feira app deploy --apply` verb
134/// (caixa-feira/src/cmd/app.rs) — the writer-side Aplicacao
135/// cluster-deploy path. Its `push_origin` helper runs the same
136/// `git push origin HEAD` against the k8s GitOps repo after writing
137/// the rendered multi-doc YAML (programs.yaml entries + Cilium
138/// NetworkPolicies + Gateway/HTTPRoute) to the cluster's tree.
139///
140/// Until this lift landed all three consumers carried the bare
141/// `"origin"` byte inline — `publish.rs`'s clap `default_value = "origin"`,
142/// `deploy.rs`'s `git(repo, ["push", "origin", "HEAD"])`, and
143/// `app.rs`'s `git(repo, ["push", "origin", "HEAD"])`. A future
144/// remote-naming-convention rebrand on any one side (the substrate
145/// moving to `upstream` for forge-mirror clusters, to a per-tenant
146/// remote naming convention once the operator-flux pipeline grows the
147/// `:placement :remote` slot, or to the canonical multi-remote
148/// `release` + `mirror` split every Erlang/OTP `release_handler` /
149/// `relup` shop converges on once their git surface grows past one
150/// upstream) without a coordinated edit on the other two would have
151/// silently emitted a `git push` against a remote that doesn't exist
152/// on the operator's clone (`fatal: '<remote>' does not appear to be
153/// a git repository`) on one writer verb while the other two still
154/// pushed to the old remote — operator-observed symptom: the publish
155/// landed but the deploy didn't, or vice-versa, with the failure
156/// surfacing as a partial-state rollout far from the rebrand commit's
157/// source.
158///
159/// Lifting the literal to one `&'static str` constant closes the drift
160/// footgun structurally — all three consumers read from the same
161/// memory, so any future remote-naming rebrand reaches every writer
162/// verb by construction and a CI build that re-introduces a sibling
163/// inline `"origin"` literal trips the peer pinning tests
164/// ([`caixa-feira`]'s `publish_remote_default_pins_lifted_caixa_core_constant`
165/// on the clap-default axis, the sibling structural pins on the two
166/// `push_origin` helpers) at the build-time fail-before-deploy
167/// posture every prior load-bearing-string lift on this surface
168/// ([`crate::DEFAULT_NAMESPACE`] a085b26, [`crate::DEFAULT_LIBRARY_NAME`]
169/// 41438dc, [`crate::DEFAULT_SERVICO_PORT`] 1e22add,
170/// [`crate::DEFAULT_PUBLISH_TAG_PREFIX`] 0a6a602,
171/// [`crate::DEFAULT_FLUX_SYSTEM_NAMESPACE`] 7197d38) establishes.
172///
173/// Pairs with [`DEFAULT_PUBLISH_TAG_PREFIX`] on the same git remote
174/// axis — `feira publish` runs `git push <DEFAULT_GIT_REMOTE>
175/// <DEFAULT_PUBLISH_TAG_PREFIX><versao>` to push the typed `:versao`
176/// body composed under the canonical prefix to the canonical remote.
177/// Both halves of the publish-side convention now live in one place.
178pub const DEFAULT_GIT_REMOTE: &str = "origin";
179
180/// Canonical GitHub org name the pleme-io substrate defaults every un-
181/// pinned caixa's source repo to — the org handle the two substrate-side
182/// "no `:repositorio` / no `:fonte` declared, fall back to the canonical
183/// org" paths compose their `github:<org>/<nome>` shorthand + full
184/// `https://github.com/<org>/<nome>` URL under.
185///
186/// Two production-code consumers carry this org name on the same
187/// canonical-substrate-default-git-org axis:
188///
189/// 1. [`caixa-feira`]'s `feira lock` verb's `resolve_stub` (caixa-feira/src/cmd/lock.rs)
190/// — the resolver-side default. When a declared dep has no
191/// `:fonte` block the stub resolver composes
192/// `caixa_core::DepSource::default_github(<org>, &dep.nome)` to fill
193/// the shorthand `github:<org>/<nome>` fallback the phase 1.B
194/// `feira resolve` walker will resolve against upstream.
195/// 2. [`caixa-flux`]'s [`caixa-flux::cluster_bundle`] renderer
196/// (caixa-flux/src/lib.rs) — the renderer-side default. Its
197/// `ClusterBundleOpts::for_caixa` constructor defaults
198/// `git_url` to `format!("https://github.com/{org}/{}", caixa.nome)`
199/// when the caixa carries no `:repositorio`, so the rendered
200/// `gitrepository.yaml` points `FluxCD`'s `GitRepository`
201/// reconciler at the substrate's canonical git host for un-pinned
202/// caixas.
203///
204/// Until this lift landed both consumers carried the bare `"pleme-io"`
205/// byte inline — `caixa-feira/src/cmd/lock.rs:61`'s
206/// `default_github("pleme-io", …)` call and `caixa-flux/src/lib.rs`'s
207/// `format!("https://github.com/pleme-io/{}", …)` literal. A future
208/// substrate-side git-org migration (the pleme-io org renaming to a
209/// short form, forking to a per-tenant `<org>-<tenant>` shape once the
210/// operator-flux pipeline grows a `:placement :org` slot, or moving to
211/// a self-hosted forge under a wholly-owned org name once the
212/// substrate's forge-gen roadmap graduates past GitHub) without a
213/// coordinated edit on both sides would silently emit a `feira lock`-
214/// side `github:<old-org>/<nome>` fallback shorthand while the
215/// `cluster_bundle`-side `gitrepository.yaml` pointed at the new org's
216/// `<nome>` — the phase 1.B `feira resolve` walker would probe the
217/// prior org's git host for a repo that migrated with the org, or vice-
218/// versa: Flux's `GitRepository` reconciler would loop forever looking
219/// for an upstream repo the old org handle no longer maps to, the
220/// dependent `HelmRelease`'s `chart: sourceRef` would never resolve,
221/// every per-Servico apply would silently come up with the prior
222/// reconciled state, and the failure would surface at `kubectl describe
223/// gitrepository` time (the `Status: Stalled` / `Reason: Failed` arm)
224/// far from the org-migration commit's source.
225///
226/// Lifting the literal to one `&'static str` constant closes the drift
227/// footgun structurally — both consumers read from the same memory, so
228/// any future org migration reaches both sites by construction and a CI
229/// build that re-introduces a sibling inline `"pleme-io"` literal trips
230/// the peer pinning tests at the build-time fail-before-deploy posture
231/// every prior load-bearing-string lift on this surface
232/// ([`crate::DEFAULT_NAMESPACE`] a085b26,
233/// [`crate::DEFAULT_LIBRARY_NAME`] 41438dc,
234/// [`crate::DEFAULT_SERVICO_PORT`] 1e22add,
235/// [`DEFAULT_PUBLISH_TAG_PREFIX`] 0a6a602,
236/// [`DEFAULT_GIT_REMOTE`],
237/// [`crate::DEFAULT_FLUX_SYSTEM_NAMESPACE`] 7197d38) establishes.
238///
239/// Distinct from the [`crate::PLEME_LABEL_PREFIX`] canonical pleme-io
240/// label-namespace prefix (`"pleme.pleme.io"`, the K8s label-namespace
241/// axis every substrate-emitted cluster object's `LABEL_APLICACAO` /
242/// `LABEL_PROGRAM` / `LABEL_CONTRATO` axis shares) — these constants
243/// sit on separate schema-contract surfaces (the git-host org handle
244/// vs. the K8s label-namespace prefix) governed by independent rebrand
245/// cycles, so a git-org rename must not couple the K8s label-namespace
246/// axis to the git-host axis (or vice-versa). Splitting the two lets
247/// each schema's future rebrand land independently at its canonical
248/// const definition without silently coupling the surfaces — same
249/// "byte-distinct, semantically distinct" discipline the
250/// [`crate::PLEME_LABEL_PREFIX`] / [`crate::LABEL_APLICACAO`] /
251/// [`crate::LABEL_PROGRAM`] / [`crate::LABEL_CONTRATO`] set establishes
252/// on the peer per-K8s-label-namespace canonical-string surface.
253pub const DEFAULT_PLEME_GIT_ORG: &str = "pleme-io";
254
255/// Parse a dep's `:versao` string as a [`semver::VersionReq`].
256///
257/// Treats the literal `"*"` as "any version" (semver's wildcard).
258pub fn parse_requirement(s: &str) -> Result<semver::VersionReq, VersionError> {
259 if s == "*" {
260 return Ok(semver::VersionReq::STAR);
261 }
262 semver::VersionReq::parse(s)
263 .map_err(|e| VersionError::Requirement(s.to_string(), e.to_string()))
264}
265
266#[derive(Debug, Error)]
267pub enum VersionError {
268 #[error("invalid version '{0}': {1}")]
269 Semver(String, String),
270 #[error("invalid version requirement '{0}': {1}")]
271 Requirement(String, String),
272}
273
274#[cfg(test)]
275mod tests {
276 use super::*;
277
278 #[test]
279 fn version_round_trip() {
280 let v: CaixaVersion = "1.2.3".into();
281 assert_eq!(v.as_str(), "1.2.3");
282 assert_eq!(v.parse().unwrap().to_string(), "1.2.3");
283 }
284
285 #[test]
286 fn caixa_version_as_str_accessor_is_const_fn() {
287 // Fail-before-pass-after pin on [`CaixaVersion::as_str`]'s
288 // `const`-eval-surface posture. The accessor projects the typed
289 // newtype's inner [`String`] through the `pub const fn`
290 // [`String::as_str`] (const-stable since Rust 1.87, well within
291 // the workspace MSRV) — any future accidental downgrade to
292 // non-`const` fails `as_str_via_const_fn` at caixa-core build
293 // time with E0015 (`cannot call non-const method`), strictly
294 // stronger than a runtime `assert!`. Sibling of the peer
295 // per-M2/M3/universal-axis `String → &str` scalar-accessor
296 // family pins on the sibling `const`-eval-surface passes
297 // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
298 // top-level manifest, [`crate::aplicacao::Membro::nome`] /
299 // [`crate::aplicacao::Membro::versao_requirement`] at the M3
300 // membership axis, [`crate::aplicacao::Entrada::hostname`] /
301 // [`crate::aplicacao::Entrada::destination`] at the M3 ingress
302 // axis, [`crate::supervisor::ChildSpec::nome`] /
303 // [`crate::supervisor::ChildSpec::versao_requirement`] at the
304 // M2 supervisor-tree axis,
305 // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the M2
306 // upgrade axis, [`crate::dep::Dep::nome`] /
307 // [`crate::dep::Dep::versao_requirement`] at the dep-graph
308 // axis, and the peer per-`:contratos` [`crate::aplicacao::WitContract::source`] /
309 // [`crate::aplicacao::WitContract::destination`] /
310 // [`crate::aplicacao::WitContract::world_ref`] trio the
311 // sibling pin at 279823b already anchors).
312 const fn as_str_via_const_fn(v: &CaixaVersion) -> &str {
313 v.as_str()
314 }
315 for versao in ["0.1.0", "1.2.3-alpha.1", "0.0.0", ""] {
316 let v: CaixaVersion = versao.into();
317 assert_eq!(as_str_via_const_fn(&v), v.as_str());
318 assert_eq!(v.as_str(), versao);
319 }
320 }
321
322 #[test]
323 fn star_is_any() {
324 let r = parse_requirement("*").unwrap();
325 assert!(r.matches(&"0.1.0".parse().unwrap()));
326 assert!(r.matches(&"99.0.0".parse().unwrap()));
327 }
328
329 #[test]
330 fn caret_matches_minor_range() {
331 let r = parse_requirement("^0.1").unwrap();
332 assert!(r.matches(&"0.1.0".parse().unwrap()));
333 assert!(r.matches(&"0.1.99".parse().unwrap()));
334 assert!(!r.matches(&"0.2.0".parse().unwrap()));
335 }
336
337 #[test]
338 fn invalid_version_errors() {
339 let v: CaixaVersion = "not-a-version".into();
340 assert!(v.parse().is_err());
341 }
342
343 #[test]
344 fn default_git_remote_pins_canonical_origin_byte() {
345 // Bridge-arm pin: [`DEFAULT_GIT_REMOTE`] resolves to the
346 // canonical `"origin"` byte today, the same remote-handle every
347 // `git clone <url>` invocation populates by default and every
348 // peer `feira` writer-side verb (`feira publish`, `feira deploy
349 // --apply`, `feira app deploy --apply`) names when it invokes
350 // `git push <remote> <ref>` against the local clone. Pin the
351 // literal here (peer with the
352 // [`DEFAULT_PUBLISH_TAG_PREFIX`] / [`crate::DEFAULT_SERVICO_PORT`]
353 // / [`crate::DEFAULT_NAMESPACE`] / [`crate::DEFAULT_LIBRARY_NAME`]
354 // / [`crate::DEFAULT_FLUX_SYSTEM_NAMESPACE`] canonical-literal
355 // pins on the sibling lifted-constant surfaces) so a future
356 // remote-naming rebrand surfaces here as a coordinated edit-
357 // point: the sibling [`caixa-feira`]
358 // `publish_remote_default_pins_lifted_caixa_core_constant`
359 // pinning test already pins the equality at the clap-default
360 // axis; this pin closes the second coordinate of the
361 // triangle by anchoring the lifted constant's current byte
362 // to the canonical git-default-remote convention's documented
363 // shape.
364 assert_eq!(DEFAULT_GIT_REMOTE, "origin");
365 }
366
367 #[test]
368 fn default_pleme_git_org_pins_canonical_pleme_io_byte() {
369 // Bridge-arm pin: [`DEFAULT_PLEME_GIT_ORG`] resolves to the
370 // canonical `"pleme-io"` GitHub-org-handle today, the same org
371 // name every peer substrate-side default-git-source consumer
372 // ([`caixa-feira`]'s `feira lock` `resolve_stub` for the
373 // per-dep `:fonte`-elided `github:<org>/<nome>` fallback,
374 // [`caixa-flux`]'s `ClusterBundleOpts::for_caixa` constructor
375 // for the per-caixa `:repositorio`-elided
376 // `https://github.com/<org>/<nome>` fallback) fills into its
377 // per-consumer render/resolve compose site. Pin the literal
378 // here (peer with the [`DEFAULT_PUBLISH_TAG_PREFIX`] /
379 // [`DEFAULT_GIT_REMOTE`] canonical-literal pins on the sibling
380 // lifted-constant surfaces) so a future substrate-side git-org
381 // migration surfaces here as a coordinated edit-point: both
382 // sibling consumer sites already thread through the same
383 // `&'static str`, this pin anchors the lifted constant's
384 // current byte to the canonical substrate-git-org convention's
385 // documented shape.
386 assert_eq!(DEFAULT_PLEME_GIT_ORG, "pleme-io");
387 }
388
389 #[test]
390 fn default_publish_tag_prefix_pins_canonical_v_byte() {
391 // Bridge-arm pin: [`DEFAULT_PUBLISH_TAG_PREFIX`] resolves to the
392 // canonical Zig-style `"v"` byte today, the same prefix every
393 // peer doc-comment on the typed `:versao` surfaces (the
394 // top-level `:versao` `validate_versao` cascade at
395 // caixa-core/src/manifest.rs:646, the four sibling per-axis
396 // `:versao` requirement gates that name the publish-side
397 // `v<versao>` tag inline in their bodies) cites as the
398 // canonical convention. Pin the literal here (peer with the
399 // [`crate::DEFAULT_SERVICO_PORT`] / [`crate::DEFAULT_NAMESPACE`]
400 // / [`crate::DEFAULT_LIBRARY_NAME`] canonical-literal pins on
401 // the sibling lifted-constant surfaces) so a future rebrand of
402 // the constant surfaces here as a coordinated edit-point: both
403 // sibling pinning tests on the two consumer crates
404 // ([`caixa-feira`] `publish_prefix_default_pins_lifted_caixa_core_constant`,
405 // [`caixa-flux`] `cluster_bundle_default_git_tag_uses_lifted_caixa_core_prefix`)
406 // already pin the equality at the consumer-default axis; this
407 // pin closes the third coordinate of the triangle by anchoring
408 // the lifted constant's current byte to the canonical Zig-style
409 // convention's documented shape.
410 assert_eq!(DEFAULT_PUBLISH_TAG_PREFIX, "v");
411 }
412}