Skip to main content

anodizer_core/config/
release.rs

1use schemars::JsonSchema;
2use serde::{Deserialize, Serialize};
3
4use super::{
5    ContentSource, ExtraFileSpec, HumanDuration, StringOrBool, TemplatedExtraFile,
6    deserialize_string_or_bool_opt,
7};
8
9// ---------------------------------------------------------------------------
10// ReleaseConfig
11// ---------------------------------------------------------------------------
12
13#[derive(Debug, Clone, Serialize, Deserialize, Default, JsonSchema)]
14#[serde(default, deny_unknown_fields)]
15pub struct ReleaseConfig {
16    /// GitHub repository to release to (owner and name).
17    pub github: Option<ScmRepoConfig>,
18    /// GitLab repository to release to (owner and name).
19    pub gitlab: Option<ScmRepoConfig>,
20    /// Gitea repository to release to (owner and name).
21    pub gitea: Option<ScmRepoConfig>,
22    /// When true, create the release as a draft (unpublished).
23    pub draft: Option<bool>,
24    #[schemars(schema_with = "prerelease_schema")]
25    /// Mark release as pre-release: true, false, or "auto" (inferred from tag).
26    pub prerelease: Option<PrereleaseConfig>,
27    #[schemars(schema_with = "make_latest_schema")]
28    /// Mark release as latest: true, false, or "auto" (latest non-prerelease).
29    pub make_latest: Option<MakeLatestConfig>,
30    /// Release title template (supports templates).
31    pub name_template: Option<String>,
32    /// Text prepended to the release body (inline string, from_file, or from_url).
33    pub header: Option<ContentSource>,
34    /// Text appended to the release body (inline string, from_file, or from_url).
35    pub footer: Option<ContentSource>,
36    /// Extra files to upload to the release beyond build artifacts.
37    ///
38    /// Paths / globs are resolved relative to the project root. `..`
39    /// segments are accepted, so an entry
40    /// like `../sibling/dist/*` will reach outside the project tree —
41    /// security-conscious users should keep the entries inside the repo or
42    /// canonicalise them before invoking the release pipeline.
43    pub extra_files: Option<Vec<ExtraFileSpec>>,
44    /// Extra files whose contents are rendered through the template engine before upload.
45    /// Unlike `extra_files` which copy as-is, template variables like `{{ Tag }}` are expanded.
46    ///
47    /// Same path-traversal caveat as `extra_files`: `..` segments reach
48    /// outside the project tree.
49    pub templated_extra_files: Option<Vec<TemplatedExtraFile>>,
50    /// Skip uploading artifacts: true, false, or "auto" (skip for snapshots).
51    /// Accepts bool or template string.
52    #[serde(deserialize_with = "deserialize_string_or_bool_opt", default)]
53    pub skip_upload: Option<StringOrBool>,
54    /// When true, replace an existing draft release instead of failing.
55    pub replace_existing_draft: Option<bool>,
56    /// When true, replace existing release artifacts with the same name.
57    pub replace_existing_artifacts: Option<bool>,
58    /// Skip the release stage. Accepts bool or template string
59    /// (e.g. `"{{ if IsSnapshot }}true{{ endif }}"` for conditional skip).
60    /// Template strings are supported here.
61    /// Accepts the legacy `disable:` spelling via serde alias for back-compat
62    /// with imported configs (the legacy `disable:` spelling).
63    #[serde(
64        default,
65        alias = "disable",
66        deserialize_with = "deserialize_string_or_bool_opt"
67    )]
68    pub skip: Option<StringOrBool>,
69    /// Release mode: "keep-existing", "append", "prepend", or "replace".
70    pub mode: Option<String>,
71    /// Artifact IDs filter for uploads. Release-wide artifacts (checksums,
72    /// source archive, extra files, metadata) always upload regardless of
73    /// the filter, and derived artifacts (signatures, certificates, SBOMs)
74    /// inherit the verdict of the artifact they derive from — a signature
75    /// uploads iff the artifact it signs uploads.
76    pub ids: Option<Vec<String>>,
77    /// Glob patterns matched against each release asset's file name; anodizer
78    /// drops any asset whose name matches at least one glob before attaching it
79    /// to THIS GitHub release only (a mirror configured elsewhere is
80    /// unaffected). Use it to keep heavy sidecars (checksums, signatures,
81    /// SBOMs) off the GitHub release while archives still attach. Composes with
82    /// `ids:` (both filters apply). `None`/empty keeps everything.
83    ///
84    /// ```yaml
85    /// release:
86    ///   github: { owner: my-org, name: my-repo }
87    ///   exclude: ["*.sha256", "*.sig", "*.cdx.json"]
88    /// ```
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub exclude: Option<Vec<String>>,
91    /// Target branch or SHA for the release tag.
92    pub target_commitish: Option<String>,
93    /// GitHub Discussion category name for the release.
94    pub discussion_category_name: Option<String>,
95    /// Upload metadata.json and artifacts.json as release assets.
96    pub include_meta: Option<bool>,
97    /// Reuse an existing draft release instead of creating a new one.
98    pub use_existing_draft: Option<bool>,
99    /// Override the release tag (template string). When set, this tag is used
100    /// as the `tag_name` in the GitHub release API instead of the crate's
101    /// `tag_template`. Useful in monorepo setups to strip a tag prefix
102    /// (e.g. `"{{ Tag }}"` to publish `v1.0.0` instead of `myapp/v1.0.0`).
103    /// A cross-platform publishing feature provided for free by anodizer.
104    pub tag: Option<String>,
105    /// Maximum number of asset-upload requests in flight simultaneously.
106    /// Applies to asset uploads on every release forge (GitHub, GitLab,
107    /// Gitea).
108    ///
109    /// GitHub's secondary rate-limit is triggered by burst traffic. Keeping
110    /// this value low avoids tripping the limit even for releases with many
111    /// artifacts. Default: 4. Override at runtime with
112    /// `ANODIZER_GITHUB_UPLOAD_CONCURRENCY`.
113    pub upload_concurrency: Option<u32>,
114    /// Minimum interval between successive asset-upload *starts* (a humantime
115    /// string, e.g. `"200ms"`, `"1s"`, `"0s"`). Applies to asset uploads on
116    /// every release forge (GitHub, GitLab, Gitea).
117    ///
118    /// This is a *proactive* pace that smooths the initial burst of upload
119    /// requests, layered on top of [`Self::upload_concurrency`] (the
120    /// concurrency cap) and the reactive secondary-rate-limit backoff. With
121    /// the concurrency cap alone, the first N uploads fire in the same instant
122    /// — exactly the burst pattern that trips GitHub's secondary rate limit.
123    /// Spacing each upload's *start* by this interval (with ±20% jitter so
124    /// concurrent releases don't synchronise) makes the burst far less likely
125    /// to trip the limit in the first place.
126    ///
127    /// Default: `"200ms"` — at the default concurrency of 4 this caps the
128    /// initial start rate at ~5/s, which is below the burst threshold yet adds
129    /// negligible wall-clock to a normal release (upload time is dominated by
130    /// transfer, not start-spacing). Set to `"0s"` to disable pacing entirely
131    /// (rely on the concurrency cap + reactive backoff). Override at runtime
132    /// with `ANODIZER_GITHUB_UPLOAD_PACE_MS` (integer milliseconds; `0`
133    /// disables).
134    pub upload_pace: Option<HumanDuration>,
135    /// Override whether this publisher failing should fail the overall release.
136    ///
137    /// Default: `true` — a failure here aborts the release.
138    /// Set to `false` to log failures but continue.
139    #[serde(default, skip_serializing_if = "Option::is_none")]
140    pub required: Option<bool>,
141    /// Explicit publish target — the SCM provider whose `release.<provider>`
142    /// block the publisher uses. When set, overrides the implicit
143    /// token-type fallback chain in
144    /// [`crate::scm::resolve_token_type`].
145    ///
146    /// Use this for **cross-platform publishing**
147    /// pattern: source repo on one provider (e.g. GitLab) but releases
148    /// land on another (e.g. GitHub). Without it, the publish target
149    /// is inferred from which `*_TOKEN` env-var is set — fine for
150    /// single-provider setups but ambiguous when both tokens are
151    /// available.
152    ///
153    /// ```yaml
154    /// release:
155    ///   provider: github
156    ///   github:
157    ///     owner: my-org
158    ///     name: my-app
159    /// ```
160    #[serde(default, skip_serializing_if = "Option::is_none")]
161    pub provider: Option<ForceTokenKind>,
162    /// When `true`, a triggered rollback leaves this publisher's work in
163    /// place rather than attempting to undo it. Default `false`.
164    pub retain_on_rollback: Option<bool>,
165    /// In-process failure policy: what `anodizer release` does after a
166    /// release-pipeline failure. `rollback` (default) deletes the run's
167    /// release tag(s) and reverts the version-bump commit so the same
168    /// version can be re-cut; `hold` leaves everything in place for
169    /// forensics and manual recovery (`release --rollback-only
170    /// --from-run=<id>`). `rollback` automatically degrades to `hold`
171    /// the moment any one-way-door (Submitter) publisher has landed:
172    /// the version is burned at a registry that never accepts it twice,
173    /// so destructive rollback is refused and fix-forward is the only
174    /// path. Root-level policy — in workspace configs (lockstep or
175    /// per-crate) the top-level `release.on_failure` governs the whole
176    /// run; setting it in a crate-level `release:` block is rejected at
177    /// config load (`validate_on_failure_root_only`).
178    pub on_failure: Option<OnFailureConfig>,
179}
180
181impl ReleaseConfig {
182    /// Default release-name template (`"{{Tag}}"`).
183    /// Anodize uses Tera-style `{{ Tag }}` (no dot prefix); the rendered
184    /// value is identical for any tag the project produces.
185    pub const DEFAULT_NAME_TEMPLATE: &'static str = "{{ Tag }}";
186
187    /// Default release `mode` (empty string is treated as
188    /// "keep-existing" — keep current release notes, don't overwrite).
189    pub const DEFAULT_MODE: &'static str = "keep-existing";
190
191    /// Default minimum interval between successive asset-upload starts
192    /// (see [`Self::upload_pace`]). 200 ms smooths the initial burst at the
193    /// default concurrency of 4 without meaningfully slowing a release.
194    pub const DEFAULT_UPLOAD_PACE: std::time::Duration = std::time::Duration::from_millis(200);
195
196    /// Valid `mode:` values. Anything else is a config error.
197    pub const VALID_MODES: &[&'static str] = &["keep-existing", "append", "prepend", "replace"];
198
199    /// Resolve the `name_template`, falling back to
200    /// [`Self::DEFAULT_NAME_TEMPLATE`].
201    pub fn resolved_name_template(&self) -> &str {
202        self.name_template
203            .as_deref()
204            .unwrap_or(Self::DEFAULT_NAME_TEMPLATE)
205    }
206
207    /// Resolve the release `mode`, validating and falling back to
208    /// [`Self::DEFAULT_MODE`] when unset or empty. Returns an error when
209    /// the user supplied a value outside [`Self::VALID_MODES`] so the
210    /// invalid mode surfaces at the call site instead of producing a
211    /// silent no-op publish.
212    pub fn resolved_mode(&self) -> anyhow::Result<&str> {
213        match self.mode.as_deref() {
214            None | Some("") => Ok(Self::DEFAULT_MODE),
215            Some(m) if Self::VALID_MODES.contains(&m) => Ok(m),
216            Some(other) => Err(anyhow::anyhow!(
217                "release: invalid mode '{}', must be one of: {}",
218                other,
219                Self::VALID_MODES.join(", ")
220            )),
221        }
222    }
223
224    /// Resolve `draft`, falling back to `false`.
225    pub fn resolved_draft(&self) -> bool {
226        self.draft.unwrap_or(false)
227    }
228
229    /// Resolve `replace_existing_draft`, falling back to `false`.
230    pub fn resolved_replace_existing_draft(&self) -> bool {
231        self.replace_existing_draft.unwrap_or(false)
232    }
233
234    /// Resolve `replace_existing_artifacts`, falling back to `false`.
235    pub fn resolved_replace_existing_artifacts(&self) -> bool {
236        self.replace_existing_artifacts.unwrap_or(false)
237    }
238
239    /// Resolve `include_meta`, falling back to `false` (don't upload
240    /// metadata.json / artifacts.json as release assets by default).
241    pub fn resolved_include_meta(&self) -> bool {
242        self.include_meta.unwrap_or(false)
243    }
244
245    /// Resolve `use_existing_draft`, falling back to `false` (always
246    /// create a fresh draft when one isn't found by default).
247    pub fn resolved_use_existing_draft(&self) -> bool {
248        self.use_existing_draft.unwrap_or(false)
249    }
250
251    /// Resolve `on_failure`, falling back to
252    /// [`OnFailureConfig::Rollback`].
253    pub fn resolved_on_failure(&self) -> OnFailureConfig {
254        self.on_failure.unwrap_or_default()
255    }
256
257    /// Resolve the upload pace (minimum inter-upload-start interval) from the
258    /// config, applying [`Self::DEFAULT_UPLOAD_PACE`] when unset. A configured
259    /// `"0s"` resolves to `Duration::ZERO`, which the upload loop treats as
260    /// "pacing disabled".
261    ///
262    /// Note: the runtime env override `ANODIZER_GITHUB_UPLOAD_PACE_MS` takes
263    /// precedence and is applied at the call site (it needs the request-scoped
264    /// [`crate::Context`]), mirroring how `ANODIZER_GITHUB_UPLOAD_CONCURRENCY`
265    /// overrides [`Self::upload_concurrency`].
266    pub fn resolved_upload_pace(&self) -> std::time::Duration {
267        self.upload_pace
268            .map(|d| d.duration())
269            .unwrap_or(Self::DEFAULT_UPLOAD_PACE)
270    }
271}
272
273/// In-process failure policy for `anodizer release`. See
274/// [`ReleaseConfig::on_failure`].
275#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
276#[serde(rename_all = "lowercase")]
277pub enum OnFailureConfig {
278    /// Roll back reversible state (delete the run's release tags, revert
279    /// the version-bump commit) so the version can be re-cut. Degrades to
280    /// `Hold` when any one-way-door publisher already landed.
281    #[default]
282    Rollback,
283    /// Leave everything in place for forensics; exit nonzero with a
284    /// pointer at `release --rollback-only --from-run=<id>`.
285    Hold,
286}
287
288impl std::fmt::Display for OnFailureConfig {
289    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
290        match self {
291            OnFailureConfig::Rollback => f.write_str("rollback"),
292            OnFailureConfig::Hold => f.write_str("hold"),
293        }
294    }
295}
296
297/// Schema for prerelease: "auto" or boolean.
298fn prerelease_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
299    auto_or_bool_schema()
300}
301
302/// Schema for make_latest: "auto" or boolean.
303fn make_latest_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
304    auto_or_bool_schema()
305}
306
307/// Schema for skip_push: "auto" or boolean.
308pub(super) fn skip_push_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
309    auto_or_bool_schema()
310}
311
312/// A `oneOf` schema accepting the literal string `"auto"` or any boolean — the
313/// shape shared by `prerelease`, `make_latest`, and `skip_push` (each a
314/// tri-state where `"auto"` defers the value to release-time inference).
315fn auto_or_bool_schema() -> schemars::Schema {
316    schemars::json_schema!({
317        "oneOf": [
318            { "type": "string", "enum": ["auto"] },
319            { "type": "boolean" }
320        ]
321    })
322}
323
324#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
325#[serde(deny_unknown_fields)]
326pub struct ScmRepoConfig {
327    /// Repository owner (user or organization).
328    pub owner: String,
329    /// Repository name.
330    pub name: String,
331}
332
333/// Backward-compatible alias — existing code can continue to use `GitHubConfig`.
334pub type GitHubConfig = ScmRepoConfig;
335
336// ---------------------------------------------------------------------------
337// ForceTokenKind
338// ---------------------------------------------------------------------------
339
340/// Which SCM token to force for authentication, overriding automatic detection.
341#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
342#[serde(rename_all = "lowercase")]
343pub enum ForceTokenKind {
344    GitHub,
345    GitLab,
346    Gitea,
347}
348
349// ---------------------------------------------------------------------------
350// Platform URL configs (GitHub Enterprise, GitLab self-hosted, Gitea)
351// ---------------------------------------------------------------------------
352
353/// Custom GitHub API/upload/download URLs for GitHub Enterprise installations.
354/// GitHub API/download URL overrides.
355#[derive(Debug, Clone, Serialize, Deserialize, Default, JsonSchema)]
356#[serde(default, deny_unknown_fields)]
357pub struct GitHubUrlsConfig {
358    /// GitHub API base URL (e.g. `https://github.example.com/api/v3/`).
359    pub api: Option<String>,
360    /// GitHub upload URL for release assets (e.g. `https://github.example.com/api/uploads/`).
361    pub upload: Option<String>,
362    /// GitHub download URL for release assets (e.g. `https://github.example.com/`).
363    pub download: Option<String>,
364    /// When true, skip TLS certificate verification for the custom URLs.
365    pub skip_tls_verify: Option<bool>,
366}
367
368/// Custom GitLab API/download URLs for self-hosted GitLab installations.
369/// GitLab API/download URL overrides.
370#[derive(Debug, Clone, Serialize, Deserialize, Default, JsonSchema)]
371#[serde(default, deny_unknown_fields)]
372pub struct GitLabUrlsConfig {
373    /// GitLab API base URL (e.g. `https://gitlab.example.com/api/v4/`).
374    pub api: Option<String>,
375    /// GitLab download URL for release assets.
376    pub download: Option<String>,
377    /// When true, skip TLS certificate verification for the custom URLs.
378    pub skip_tls_verify: Option<bool>,
379    /// When true, use the GitLab Package Registry for uploads instead of Generic Packages.
380    pub use_package_registry: Option<bool>,
381    /// When true, use the CI_JOB_TOKEN for authentication instead of a personal token.
382    pub use_job_token: Option<bool>,
383}
384
385/// Custom Gitea API/download URLs for self-hosted Gitea installations.
386/// Gitea API/download URL overrides.
387#[derive(Debug, Clone, Serialize, Deserialize, Default, JsonSchema)]
388#[serde(default, deny_unknown_fields)]
389pub struct GiteaUrlsConfig {
390    /// Gitea API base URL (e.g. `https://gitea.example.com/api/v1/`).
391    pub api: Option<String>,
392    /// Gitea download URL for release assets.
393    pub download: Option<String>,
394    /// When true, skip TLS certificate verification for the custom URLs.
395    pub skip_tls_verify: Option<bool>,
396}
397
398// ---------------------------------------------------------------------------
399// "auto" | bool enum — shared serde implementation
400// ---------------------------------------------------------------------------
401
402/// Generates `Serialize` and `Deserialize` impls for enums with `Auto` and
403/// `Bool(bool)` variants that accept the string `"auto"` or a boolean in YAML.
404macro_rules! impl_auto_or_bool_serde {
405    ($ty:ty, $auto:path, $bool_variant:path) => {
406        impl Serialize for $ty {
407            fn serialize<S: serde::Serializer>(
408                &self,
409                serializer: S,
410            ) -> std::result::Result<S::Ok, S::Error> {
411                match self {
412                    $auto => serializer.serialize_str("auto"),
413                    $bool_variant(b) => serializer.serialize_bool(*b),
414                }
415            }
416        }
417
418        impl<'de> Deserialize<'de> for $ty {
419            fn deserialize<D: serde::Deserializer<'de>>(
420                deserializer: D,
421            ) -> std::result::Result<Self, D::Error> {
422                struct Visitor;
423                impl serde::de::Visitor<'_> for Visitor {
424                    type Value = $ty;
425                    fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
426                        write!(f, "\"auto\" or a boolean")
427                    }
428                    fn visit_bool<E: serde::de::Error>(
429                        self,
430                        v: bool,
431                    ) -> std::result::Result<$ty, E> {
432                        Ok($bool_variant(v))
433                    }
434                    fn visit_str<E: serde::de::Error>(
435                        self,
436                        v: &str,
437                    ) -> std::result::Result<$ty, E> {
438                        if v == "auto" {
439                            Ok($auto)
440                        } else {
441                            Err(E::custom(format!("expected \"auto\", got \"{}\"", v)))
442                        }
443                    }
444                }
445                deserializer.deserialize_any(Visitor)
446            }
447        }
448    };
449}
450
451/// `prerelease` can be the string `"auto"` or a boolean.
452#[derive(Debug, Clone, PartialEq, Eq)]
453pub enum PrereleaseConfig {
454    Auto,
455    Bool(bool),
456}
457
458impl_auto_or_bool_serde!(
459    PrereleaseConfig,
460    PrereleaseConfig::Auto,
461    PrereleaseConfig::Bool
462);
463
464/// `make_latest` can be the string `"auto"`, a boolean, or a template string.
465/// This field is rendered through the template engine at publish time,
466/// so we accept arbitrary strings (e.g. `"{{ if .IsSnapshot }}false{{ else }}true{{ end }}"`)
467/// and defer resolution to the release stage.
468#[derive(Debug, Clone, PartialEq, Eq)]
469pub enum MakeLatestConfig {
470    Auto,
471    Bool(bool),
472    /// An arbitrary template string to be rendered at publish time.
473    String(String),
474}
475
476impl Serialize for MakeLatestConfig {
477    fn serialize<S: serde::Serializer>(
478        &self,
479        serializer: S,
480    ) -> std::result::Result<S::Ok, S::Error> {
481        match self {
482            MakeLatestConfig::Auto => serializer.serialize_str("auto"),
483            MakeLatestConfig::Bool(b) => serializer.serialize_bool(*b),
484            MakeLatestConfig::String(s) => serializer.serialize_str(s),
485        }
486    }
487}
488
489impl<'de> Deserialize<'de> for MakeLatestConfig {
490    fn deserialize<D: serde::Deserializer<'de>>(
491        deserializer: D,
492    ) -> std::result::Result<Self, D::Error> {
493        struct Visitor;
494        impl serde::de::Visitor<'_> for Visitor {
495            type Value = MakeLatestConfig;
496            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
497                write!(f, "\"auto\", a boolean, or a template string")
498            }
499            fn visit_bool<E: serde::de::Error>(
500                self,
501                v: bool,
502            ) -> std::result::Result<MakeLatestConfig, E> {
503                Ok(MakeLatestConfig::Bool(v))
504            }
505            fn visit_str<E: serde::de::Error>(
506                self,
507                v: &str,
508            ) -> std::result::Result<MakeLatestConfig, E> {
509                match v {
510                    "auto" => Ok(MakeLatestConfig::Auto),
511                    "true" => Ok(MakeLatestConfig::Bool(true)),
512                    "false" => Ok(MakeLatestConfig::Bool(false)),
513                    other => Ok(MakeLatestConfig::String(other.to_string())),
514                }
515            }
516        }
517        deserializer.deserialize_any(Visitor)
518    }
519}
520
521/// `skip_push` can be `"auto"` (skip for prereleases), a boolean, or a template string.
522/// Template expressions like `"{{ if .IsSnapshot }}true{{ end }}"` are accepted.
523#[derive(Debug, Clone, PartialEq, Eq)]
524pub enum SkipPushConfig {
525    Auto,
526    Bool(bool),
527    /// Arbitrary template string — rendered at runtime, truthy result means skip push.
528    Template(String),
529}
530
531impl Serialize for SkipPushConfig {
532    fn serialize<S: serde::Serializer>(
533        &self,
534        serializer: S,
535    ) -> std::result::Result<S::Ok, S::Error> {
536        match self {
537            SkipPushConfig::Auto => serializer.serialize_str("auto"),
538            SkipPushConfig::Bool(b) => serializer.serialize_bool(*b),
539            SkipPushConfig::Template(s) => serializer.serialize_str(s),
540        }
541    }
542}
543
544impl<'de> Deserialize<'de> for SkipPushConfig {
545    fn deserialize<D: serde::Deserializer<'de>>(
546        deserializer: D,
547    ) -> std::result::Result<Self, D::Error> {
548        struct Visitor;
549        impl serde::de::Visitor<'_> for Visitor {
550            type Value = SkipPushConfig;
551            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
552                write!(f, "\"auto\", a boolean, or a template string")
553            }
554            fn visit_bool<E: serde::de::Error>(
555                self,
556                v: bool,
557            ) -> std::result::Result<SkipPushConfig, E> {
558                Ok(SkipPushConfig::Bool(v))
559            }
560            fn visit_str<E: serde::de::Error>(
561                self,
562                v: &str,
563            ) -> std::result::Result<SkipPushConfig, E> {
564                match v {
565                    "auto" => Ok(SkipPushConfig::Auto),
566                    "true" => Ok(SkipPushConfig::Bool(true)),
567                    "false" => Ok(SkipPushConfig::Bool(false)),
568                    other => Ok(SkipPushConfig::Template(other.to_string())),
569                }
570            }
571        }
572        deserializer.deserialize_any(Visitor)
573    }
574}
575
576#[cfg(test)]
577mod tests {
578    use super::*;
579
580    // The three `"auto" | bool | [template]` config enums share a hand-written
581    // serde `Visitor` per type; each arm (string-auto, bool, template fallback,
582    // and the bad-string error) is exercised here through a YAML round-trip.
583
584    #[test]
585    fn prerelease_config_parses_auto_and_bools() {
586        assert_eq!(
587            serde_yaml_ng::from_str::<PrereleaseConfig>("auto").unwrap(),
588            PrereleaseConfig::Auto
589        );
590        assert_eq!(
591            serde_yaml_ng::from_str::<PrereleaseConfig>("true").unwrap(),
592            PrereleaseConfig::Bool(true)
593        );
594        assert_eq!(
595            serde_yaml_ng::from_str::<PrereleaseConfig>("false").unwrap(),
596            PrereleaseConfig::Bool(false)
597        );
598    }
599
600    #[test]
601    fn prerelease_config_rejects_other_strings() {
602        // Unlike the templated siblings, `prerelease` only accepts "auto".
603        assert!(serde_yaml_ng::from_str::<PrereleaseConfig>("maybe").is_err());
604    }
605
606    #[test]
607    fn prerelease_config_round_trips_through_serialize() {
608        for v in [
609            PrereleaseConfig::Auto,
610            PrereleaseConfig::Bool(true),
611            PrereleaseConfig::Bool(false),
612        ] {
613            let yaml = serde_yaml_ng::to_string(&v).unwrap();
614            assert_eq!(
615                serde_yaml_ng::from_str::<PrereleaseConfig>(&yaml).unwrap(),
616                v
617            );
618        }
619    }
620
621    #[test]
622    fn make_latest_config_parses_all_arms() {
623        assert_eq!(
624            serde_yaml_ng::from_str::<MakeLatestConfig>("auto").unwrap(),
625            MakeLatestConfig::Auto
626        );
627        assert_eq!(
628            serde_yaml_ng::from_str::<MakeLatestConfig>("true").unwrap(),
629            MakeLatestConfig::Bool(true)
630        );
631        assert_eq!(
632            serde_yaml_ng::from_str::<MakeLatestConfig>("false").unwrap(),
633            MakeLatestConfig::Bool(false)
634        );
635        // A non-keyword string falls through to a deferred template.
636        assert_eq!(
637            serde_yaml_ng::from_str::<MakeLatestConfig>(
638                "\"{{ if .IsSnapshot }}false{{ else }}true{{ end }}\""
639            )
640            .unwrap(),
641            MakeLatestConfig::String(
642                "{{ if .IsSnapshot }}false{{ else }}true{{ end }}".to_string()
643            )
644        );
645    }
646
647    #[test]
648    fn make_latest_config_round_trips_through_serialize() {
649        for v in [
650            MakeLatestConfig::Auto,
651            MakeLatestConfig::Bool(false),
652            MakeLatestConfig::String("{{ .Env.LATEST }}".to_string()),
653        ] {
654            let yaml = serde_yaml_ng::to_string(&v).unwrap();
655            assert_eq!(
656                serde_yaml_ng::from_str::<MakeLatestConfig>(&yaml).unwrap(),
657                v
658            );
659        }
660    }
661
662    #[test]
663    fn skip_push_config_parses_all_arms() {
664        assert_eq!(
665            serde_yaml_ng::from_str::<SkipPushConfig>("auto").unwrap(),
666            SkipPushConfig::Auto
667        );
668        assert_eq!(
669            serde_yaml_ng::from_str::<SkipPushConfig>("true").unwrap(),
670            SkipPushConfig::Bool(true)
671        );
672        assert_eq!(
673            serde_yaml_ng::from_str::<SkipPushConfig>("false").unwrap(),
674            SkipPushConfig::Bool(false)
675        );
676        assert_eq!(
677            serde_yaml_ng::from_str::<SkipPushConfig>("\"{{ .IsSnapshot }}\"").unwrap(),
678            SkipPushConfig::Template("{{ .IsSnapshot }}".to_string())
679        );
680    }
681
682    #[test]
683    fn skip_push_config_round_trips_through_serialize() {
684        for v in [
685            SkipPushConfig::Auto,
686            SkipPushConfig::Bool(true),
687            SkipPushConfig::Template("{{ .IsSnapshot }}".to_string()),
688        ] {
689            let yaml = serde_yaml_ng::to_string(&v).unwrap();
690            assert_eq!(serde_yaml_ng::from_str::<SkipPushConfig>(&yaml).unwrap(), v);
691        }
692    }
693}