anodizer-core 0.22.2

Core configuration, context, and template engine for the anodizer release tool
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use super::{
    ContentSource, ExtraFileSpec, HumanDuration, StringOrBool, TemplatedExtraFile,
    deserialize_string_or_bool_opt,
};

// ---------------------------------------------------------------------------
// ReleaseConfig
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize, Deserialize, Default, JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct ReleaseConfig {
    /// GitHub repository to release to (owner and name).
    pub github: Option<ScmRepoConfig>,
    /// GitLab repository to release to (owner and name).
    pub gitlab: Option<ScmRepoConfig>,
    /// Gitea repository to release to (owner and name).
    pub gitea: Option<ScmRepoConfig>,
    /// When true, create the release as a draft (unpublished).
    pub draft: Option<bool>,
    #[schemars(schema_with = "prerelease_schema")]
    /// Mark release as pre-release: true, false, or "auto" (inferred from tag).
    pub prerelease: Option<PrereleaseConfig>,
    #[schemars(schema_with = "make_latest_schema")]
    /// Mark release as latest: true, false, or "auto" (latest non-prerelease).
    pub make_latest: Option<MakeLatestConfig>,
    /// Release title template (supports templates).
    pub name_template: Option<String>,
    /// Text prepended to the release body (inline string, from_file, or from_url).
    pub header: Option<ContentSource>,
    /// Text appended to the release body (inline string, from_file, or from_url).
    pub footer: Option<ContentSource>,
    /// Extra files to upload to the release beyond build artifacts.
    ///
    /// Paths / globs are resolved relative to the project root. `..`
    /// segments are accepted, so an entry
    /// like `../sibling/dist/*` will reach outside the project tree —
    /// security-conscious users should keep the entries inside the repo or
    /// canonicalise them before invoking the release pipeline.
    pub extra_files: Option<Vec<ExtraFileSpec>>,
    /// Extra files whose contents are rendered through the template engine before upload.
    /// Unlike `extra_files` which copy as-is, template variables like `{{ Tag }}` are expanded.
    ///
    /// Same path-traversal caveat as `extra_files`: `..` segments reach
    /// outside the project tree.
    pub templated_extra_files: Option<Vec<TemplatedExtraFile>>,
    /// Skip uploading artifacts: true, false, or "auto" (skip for snapshots).
    /// Accepts bool or template string.
    #[serde(deserialize_with = "deserialize_string_or_bool_opt", default)]
    pub skip_upload: Option<StringOrBool>,
    /// When true, replace an existing draft release instead of failing.
    pub replace_existing_draft: Option<bool>,
    /// When true, replace existing release artifacts with the same name.
    pub replace_existing_artifacts: Option<bool>,
    /// Skip the release stage. Accepts bool or template string
    /// (e.g. `"{{ if IsSnapshot }}true{{ endif }}"` for conditional skip).
    /// Template strings are supported here.
    /// Accepts the legacy `disable:` spelling via serde alias for back-compat
    /// with imported configs (the legacy `disable:` spelling).
    #[serde(
        default,
        alias = "disable",
        deserialize_with = "deserialize_string_or_bool_opt"
    )]
    pub skip: Option<StringOrBool>,
    /// Release mode: "keep-existing", "append", "prepend", or "replace".
    pub mode: Option<String>,
    /// Artifact IDs filter for uploads. Release-wide artifacts (checksums,
    /// source archive, extra files, metadata) always upload regardless of
    /// the filter, and derived artifacts (signatures, certificates, SBOMs)
    /// inherit the verdict of the artifact they derive from — a signature
    /// uploads iff the artifact it signs uploads.
    pub ids: Option<Vec<String>>,
    /// Glob patterns matched against each release asset's file name; anodizer
    /// drops any asset whose name matches at least one glob before attaching it
    /// to THIS GitHub release only (a mirror configured elsewhere is
    /// unaffected). Use it to keep heavy sidecars (checksums, signatures,
    /// SBOMs) off the GitHub release while archives still attach. Composes with
    /// `ids:` (both filters apply). `None`/empty keeps everything.
    ///
    /// ```yaml
    /// release:
    ///   github: { owner: my-org, name: my-repo }
    ///   exclude: ["*.sha256", "*.sig", "*.cdx.json"]
    /// ```
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exclude: Option<Vec<String>>,
    /// Target branch or SHA for the release tag.
    pub target_commitish: Option<String>,
    /// GitHub Discussion category name for the release.
    pub discussion_category_name: Option<String>,
    /// Upload metadata.json and artifacts.json as release assets.
    pub include_meta: Option<bool>,
    /// Reuse an existing draft release instead of creating a new one.
    pub use_existing_draft: Option<bool>,
    /// Override the release tag (template string). When set, this tag is used
    /// as the `tag_name` in the GitHub release API instead of the crate's
    /// `tag_template`. Useful in monorepo setups to strip a tag prefix
    /// (e.g. `"{{ Tag }}"` to publish `v1.0.0` instead of `myapp/v1.0.0`).
    /// A cross-platform publishing feature provided for free by anodizer.
    pub tag: Option<String>,
    /// Maximum number of asset-upload requests in flight simultaneously.
    /// Applies to asset uploads on every release forge (GitHub, GitLab,
    /// Gitea).
    ///
    /// GitHub's secondary rate-limit is triggered by burst traffic. Keeping
    /// this value low avoids tripping the limit even for releases with many
    /// artifacts. Default: 4. Override at runtime with
    /// `ANODIZER_GITHUB_UPLOAD_CONCURRENCY`.
    pub upload_concurrency: Option<u32>,
    /// Minimum interval between successive asset-upload *starts* (a humantime
    /// string, e.g. `"200ms"`, `"1s"`, `"0s"`). Applies to asset uploads on
    /// every release forge (GitHub, GitLab, Gitea).
    ///
    /// This is a *proactive* pace that smooths the initial burst of upload
    /// requests, layered on top of [`Self::upload_concurrency`] (the
    /// concurrency cap) and the reactive secondary-rate-limit backoff. With
    /// the concurrency cap alone, the first N uploads fire in the same instant
    /// — exactly the burst pattern that trips GitHub's secondary rate limit.
    /// Spacing each upload's *start* by this interval (with ±20% jitter so
    /// concurrent releases don't synchronise) makes the burst far less likely
    /// to trip the limit in the first place.
    ///
    /// Default: `"200ms"` — at the default concurrency of 4 this caps the
    /// initial start rate at ~5/s, which is below the burst threshold yet adds
    /// negligible wall-clock to a normal release (upload time is dominated by
    /// transfer, not start-spacing). Set to `"0s"` to disable pacing entirely
    /// (rely on the concurrency cap + reactive backoff). Override at runtime
    /// with `ANODIZER_GITHUB_UPLOAD_PACE_MS` (integer milliseconds; `0`
    /// disables).
    pub upload_pace: Option<HumanDuration>,
    /// Override whether this publisher failing should fail the overall release.
    ///
    /// Default: `true` — a failure here aborts the release.
    /// Set to `false` to log failures but continue.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub required: Option<bool>,
    /// Explicit publish target — the SCM provider whose `release.<provider>`
    /// block the publisher uses. When set, overrides the implicit
    /// token-type fallback chain in
    /// [`crate::scm::resolve_token_type`].
    ///
    /// Use this for **cross-platform publishing**
    /// pattern: source repo on one provider (e.g. GitLab) but releases
    /// land on another (e.g. GitHub). Without it, the publish target
    /// is inferred from which `*_TOKEN` env-var is set — fine for
    /// single-provider setups but ambiguous when both tokens are
    /// available.
    ///
    /// ```yaml
    /// release:
    ///   provider: github
    ///   github:
    ///     owner: my-org
    ///     name: my-app
    /// ```
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider: Option<ForceTokenKind>,
    /// When `true`, a triggered rollback leaves this publisher's work in
    /// place rather than attempting to undo it. Default `false`.
    pub retain_on_rollback: Option<bool>,
    /// In-process failure policy: what `anodizer release` does after a
    /// release-pipeline failure. `rollback` (default) deletes the run's
    /// release tag(s) and reverts the version-bump commit so the same
    /// version can be re-cut; `hold` leaves everything in place for
    /// forensics and manual recovery (`release --rollback-only
    /// --from-run=<id>`). `rollback` automatically degrades to `hold`
    /// the moment any one-way-door (Submitter) publisher has landed:
    /// the version is burned at a registry that never accepts it twice,
    /// so destructive rollback is refused and fix-forward is the only
    /// path. Root-level policy — in workspace configs (lockstep or
    /// per-crate) the top-level `release.on_failure` governs the whole
    /// run; setting it in a crate-level `release:` block is rejected at
    /// config load (`validate_on_failure_root_only`).
    pub on_failure: Option<OnFailureConfig>,
}

impl ReleaseConfig {
    /// Default release-name template (`"{{Tag}}"`).
    /// Anodize uses Tera-style `{{ Tag }}` (no dot prefix); the rendered
    /// value is identical for any tag the project produces.
    pub const DEFAULT_NAME_TEMPLATE: &'static str = "{{ Tag }}";

    /// Default release `mode` (empty string is treated as
    /// "keep-existing" — keep current release notes, don't overwrite).
    pub const DEFAULT_MODE: &'static str = "keep-existing";

    /// Default minimum interval between successive asset-upload starts
    /// (see [`Self::upload_pace`]). 200 ms smooths the initial burst at the
    /// default concurrency of 4 without meaningfully slowing a release.
    pub const DEFAULT_UPLOAD_PACE: std::time::Duration = std::time::Duration::from_millis(200);

    /// Valid `mode:` values. Anything else is a config error.
    pub const VALID_MODES: &[&'static str] = &["keep-existing", "append", "prepend", "replace"];

    /// Resolve the `name_template`, falling back to
    /// [`Self::DEFAULT_NAME_TEMPLATE`].
    pub fn resolved_name_template(&self) -> &str {
        self.name_template
            .as_deref()
            .unwrap_or(Self::DEFAULT_NAME_TEMPLATE)
    }

    /// Resolve the release `mode`, validating and falling back to
    /// [`Self::DEFAULT_MODE`] when unset or empty. Returns an error when
    /// the user supplied a value outside [`Self::VALID_MODES`] so the
    /// invalid mode surfaces at the call site instead of producing a
    /// silent no-op publish.
    pub fn resolved_mode(&self) -> anyhow::Result<&str> {
        match self.mode.as_deref() {
            None | Some("") => Ok(Self::DEFAULT_MODE),
            Some(m) if Self::VALID_MODES.contains(&m) => Ok(m),
            Some(other) => Err(anyhow::anyhow!(
                "release: invalid mode '{}', must be one of: {}",
                other,
                Self::VALID_MODES.join(", ")
            )),
        }
    }

    /// Resolve `draft`, falling back to `false`.
    pub fn resolved_draft(&self) -> bool {
        self.draft.unwrap_or(false)
    }

    /// Resolve `replace_existing_draft`, falling back to `false`.
    pub fn resolved_replace_existing_draft(&self) -> bool {
        self.replace_existing_draft.unwrap_or(false)
    }

    /// Resolve `replace_existing_artifacts`, falling back to `false`.
    pub fn resolved_replace_existing_artifacts(&self) -> bool {
        self.replace_existing_artifacts.unwrap_or(false)
    }

    /// Resolve `include_meta`, falling back to `false` (don't upload
    /// metadata.json / artifacts.json as release assets by default).
    pub fn resolved_include_meta(&self) -> bool {
        self.include_meta.unwrap_or(false)
    }

    /// Resolve `use_existing_draft`, falling back to `false` (always
    /// create a fresh draft when one isn't found by default).
    pub fn resolved_use_existing_draft(&self) -> bool {
        self.use_existing_draft.unwrap_or(false)
    }

    /// Resolve `on_failure`, falling back to
    /// [`OnFailureConfig::Rollback`].
    pub fn resolved_on_failure(&self) -> OnFailureConfig {
        self.on_failure.unwrap_or_default()
    }

    /// Resolve the upload pace (minimum inter-upload-start interval) from the
    /// config, applying [`Self::DEFAULT_UPLOAD_PACE`] when unset. A configured
    /// `"0s"` resolves to `Duration::ZERO`, which the upload loop treats as
    /// "pacing disabled".
    ///
    /// Note: the runtime env override `ANODIZER_GITHUB_UPLOAD_PACE_MS` takes
    /// precedence and is applied at the call site (it needs the request-scoped
    /// [`crate::Context`]), mirroring how `ANODIZER_GITHUB_UPLOAD_CONCURRENCY`
    /// overrides [`Self::upload_concurrency`].
    pub fn resolved_upload_pace(&self) -> std::time::Duration {
        self.upload_pace
            .map(|d| d.duration())
            .unwrap_or(Self::DEFAULT_UPLOAD_PACE)
    }
}

/// In-process failure policy for `anodizer release`. See
/// [`ReleaseConfig::on_failure`].
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum OnFailureConfig {
    /// Roll back reversible state (delete the run's release tags, revert
    /// the version-bump commit) so the version can be re-cut. Degrades to
    /// `Hold` when any one-way-door publisher already landed.
    #[default]
    Rollback,
    /// Leave everything in place for forensics; exit nonzero with a
    /// pointer at `release --rollback-only --from-run=<id>`.
    Hold,
}

impl std::fmt::Display for OnFailureConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            OnFailureConfig::Rollback => f.write_str("rollback"),
            OnFailureConfig::Hold => f.write_str("hold"),
        }
    }
}

/// Schema for prerelease: "auto" or boolean.
fn prerelease_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
    auto_or_bool_schema()
}

/// Schema for make_latest: "auto" or boolean.
fn make_latest_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
    auto_or_bool_schema()
}

/// Schema for skip_push: "auto" or boolean.
pub(super) fn skip_push_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
    auto_or_bool_schema()
}

/// A `oneOf` schema accepting the literal string `"auto"` or any boolean — the
/// shape shared by `prerelease`, `make_latest`, and `skip_push` (each a
/// tri-state where `"auto"` defers the value to release-time inference).
fn auto_or_bool_schema() -> schemars::Schema {
    schemars::json_schema!({
        "oneOf": [
            { "type": "string", "enum": ["auto"] },
            { "type": "boolean" }
        ]
    })
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ScmRepoConfig {
    /// Repository owner (user or organization).
    pub owner: String,
    /// Repository name.
    pub name: String,
    /// Auth token override for this repository, instead of the default one.
    /// Useful when the release repository requires a different token than
    /// the one used to build from — for instance, when publishing to a
    /// repository in another organization. Supports templates
    /// (environment variables). Unset falls back to the pipeline token.
    ///
    /// ```yaml
    /// release:
    ///   github:
    ///     owner: my-org
    ///     name: my-repo
    ///     token: "{{ .Env.RELEASE_GITHUB_TOKEN }}"
    /// ```
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub token: Option<String>,
}

/// Backward-compatible alias — existing code can continue to use `GitHubConfig`.
pub type GitHubConfig = ScmRepoConfig;

// ---------------------------------------------------------------------------
// ForceTokenKind
// ---------------------------------------------------------------------------

/// Which SCM token to force for authentication, overriding automatic detection.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum ForceTokenKind {
    GitHub,
    GitLab,
    Gitea,
}

// ---------------------------------------------------------------------------
// Platform URL configs (GitHub Enterprise, GitLab self-hosted, Gitea)
// ---------------------------------------------------------------------------

/// Custom GitHub API/upload/download URLs for GitHub Enterprise installations.
/// GitHub API/download URL overrides.
#[derive(Debug, Clone, Serialize, Deserialize, Default, JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct GitHubUrlsConfig {
    /// GitHub API base URL (e.g. `https://github.example.com/api/v3/`).
    pub api: Option<String>,
    /// GitHub upload URL for release assets (e.g. `https://github.example.com/api/uploads/`).
    pub upload: Option<String>,
    /// GitHub download URL for release assets (e.g. `https://github.example.com/`).
    pub download: Option<String>,
    /// When true, skip TLS certificate verification for the custom URLs.
    pub skip_tls_verify: Option<bool>,
}

/// Custom GitLab API/download URLs for self-hosted GitLab installations.
/// GitLab API/download URL overrides.
#[derive(Debug, Clone, Serialize, Deserialize, Default, JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct GitLabUrlsConfig {
    /// GitLab API base URL (e.g. `https://gitlab.example.com/api/v4/`).
    pub api: Option<String>,
    /// GitLab download URL for release assets.
    pub download: Option<String>,
    /// When true, skip TLS certificate verification for the custom URLs.
    pub skip_tls_verify: Option<bool>,
    /// When true, use the GitLab Package Registry for uploads instead of Generic Packages.
    pub use_package_registry: Option<bool>,
    /// When true, use the CI_JOB_TOKEN for authentication instead of a personal token.
    pub use_job_token: Option<bool>,
}

/// Custom Gitea API/download URLs for self-hosted Gitea installations.
/// Gitea API/download URL overrides.
#[derive(Debug, Clone, Serialize, Deserialize, Default, JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct GiteaUrlsConfig {
    /// Gitea API base URL (e.g. `https://gitea.example.com/api/v1/`).
    pub api: Option<String>,
    /// Gitea download URL for release assets.
    pub download: Option<String>,
    /// When true, skip TLS certificate verification for the custom URLs.
    pub skip_tls_verify: Option<bool>,
}

// ---------------------------------------------------------------------------
// "auto" | bool enum — shared serde implementation
// ---------------------------------------------------------------------------

/// Generates `Serialize` and `Deserialize` impls for enums with `Auto` and
/// `Bool(bool)` variants that accept the string `"auto"` or a boolean in YAML.
macro_rules! impl_auto_or_bool_serde {
    ($ty:ty, $auto:path, $bool_variant:path) => {
        impl Serialize for $ty {
            fn serialize<S: serde::Serializer>(
                &self,
                serializer: S,
            ) -> std::result::Result<S::Ok, S::Error> {
                match self {
                    $auto => serializer.serialize_str("auto"),
                    $bool_variant(b) => serializer.serialize_bool(*b),
                }
            }
        }

        impl<'de> Deserialize<'de> for $ty {
            fn deserialize<D: serde::Deserializer<'de>>(
                deserializer: D,
            ) -> std::result::Result<Self, D::Error> {
                struct Visitor;
                impl serde::de::Visitor<'_> for Visitor {
                    type Value = $ty;
                    fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                        write!(f, "\"auto\" or a boolean")
                    }
                    fn visit_bool<E: serde::de::Error>(
                        self,
                        v: bool,
                    ) -> std::result::Result<$ty, E> {
                        Ok($bool_variant(v))
                    }
                    fn visit_str<E: serde::de::Error>(
                        self,
                        v: &str,
                    ) -> std::result::Result<$ty, E> {
                        if v == "auto" {
                            Ok($auto)
                        } else {
                            Err(E::custom(format!("expected \"auto\", got \"{}\"", v)))
                        }
                    }
                }
                deserializer.deserialize_any(Visitor)
            }
        }
    };
}

/// `prerelease` can be the string `"auto"` or a boolean.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PrereleaseConfig {
    Auto,
    Bool(bool),
}

impl_auto_or_bool_serde!(
    PrereleaseConfig,
    PrereleaseConfig::Auto,
    PrereleaseConfig::Bool
);

/// `make_latest` can be the string `"auto"`, a boolean, or a template string.
/// This field is rendered through the template engine at publish time,
/// so we accept arbitrary strings (e.g. `"{{ if .IsSnapshot }}false{{ else }}true{{ end }}"`)
/// and defer resolution to the release stage.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MakeLatestConfig {
    Auto,
    Bool(bool),
    /// An arbitrary template string to be rendered at publish time.
    String(String),
}

impl Serialize for MakeLatestConfig {
    fn serialize<S: serde::Serializer>(
        &self,
        serializer: S,
    ) -> std::result::Result<S::Ok, S::Error> {
        match self {
            MakeLatestConfig::Auto => serializer.serialize_str("auto"),
            MakeLatestConfig::Bool(b) => serializer.serialize_bool(*b),
            MakeLatestConfig::String(s) => serializer.serialize_str(s),
        }
    }
}

impl<'de> Deserialize<'de> for MakeLatestConfig {
    fn deserialize<D: serde::Deserializer<'de>>(
        deserializer: D,
    ) -> std::result::Result<Self, D::Error> {
        struct Visitor;
        impl serde::de::Visitor<'_> for Visitor {
            type Value = MakeLatestConfig;
            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(f, "\"auto\", a boolean, or a template string")
            }
            fn visit_bool<E: serde::de::Error>(
                self,
                v: bool,
            ) -> std::result::Result<MakeLatestConfig, E> {
                Ok(MakeLatestConfig::Bool(v))
            }
            fn visit_str<E: serde::de::Error>(
                self,
                v: &str,
            ) -> std::result::Result<MakeLatestConfig, E> {
                match v {
                    "auto" => Ok(MakeLatestConfig::Auto),
                    "true" => Ok(MakeLatestConfig::Bool(true)),
                    "false" => Ok(MakeLatestConfig::Bool(false)),
                    other => Ok(MakeLatestConfig::String(other.to_string())),
                }
            }
        }
        deserializer.deserialize_any(Visitor)
    }
}

/// `skip_push` can be `"auto"` (skip for prereleases), a boolean, or a template string.
/// Template expressions like `"{{ if .IsSnapshot }}true{{ end }}"` are accepted.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SkipPushConfig {
    Auto,
    Bool(bool),
    /// Arbitrary template string — rendered at runtime, truthy result means skip push.
    Template(String),
}

impl Serialize for SkipPushConfig {
    fn serialize<S: serde::Serializer>(
        &self,
        serializer: S,
    ) -> std::result::Result<S::Ok, S::Error> {
        match self {
            SkipPushConfig::Auto => serializer.serialize_str("auto"),
            SkipPushConfig::Bool(b) => serializer.serialize_bool(*b),
            SkipPushConfig::Template(s) => serializer.serialize_str(s),
        }
    }
}

impl<'de> Deserialize<'de> for SkipPushConfig {
    fn deserialize<D: serde::Deserializer<'de>>(
        deserializer: D,
    ) -> std::result::Result<Self, D::Error> {
        struct Visitor;
        impl serde::de::Visitor<'_> for Visitor {
            type Value = SkipPushConfig;
            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(f, "\"auto\", a boolean, or a template string")
            }
            fn visit_bool<E: serde::de::Error>(
                self,
                v: bool,
            ) -> std::result::Result<SkipPushConfig, E> {
                Ok(SkipPushConfig::Bool(v))
            }
            fn visit_str<E: serde::de::Error>(
                self,
                v: &str,
            ) -> std::result::Result<SkipPushConfig, E> {
                match v {
                    "auto" => Ok(SkipPushConfig::Auto),
                    "true" => Ok(SkipPushConfig::Bool(true)),
                    "false" => Ok(SkipPushConfig::Bool(false)),
                    other => Ok(SkipPushConfig::Template(other.to_string())),
                }
            }
        }
        deserializer.deserialize_any(Visitor)
    }
}

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

    // The three `"auto" | bool | [template]` config enums share a hand-written
    // serde `Visitor` per type; each arm (string-auto, bool, template fallback,
    // and the bad-string error) is exercised here through a YAML round-trip.

    #[test]
    fn prerelease_config_parses_auto_and_bools() {
        assert_eq!(
            serde_yaml_ng::from_str::<PrereleaseConfig>("auto").unwrap(),
            PrereleaseConfig::Auto
        );
        assert_eq!(
            serde_yaml_ng::from_str::<PrereleaseConfig>("true").unwrap(),
            PrereleaseConfig::Bool(true)
        );
        assert_eq!(
            serde_yaml_ng::from_str::<PrereleaseConfig>("false").unwrap(),
            PrereleaseConfig::Bool(false)
        );
    }

    #[test]
    fn prerelease_config_rejects_other_strings() {
        // Unlike the templated siblings, `prerelease` only accepts "auto".
        assert!(serde_yaml_ng::from_str::<PrereleaseConfig>("maybe").is_err());
    }

    #[test]
    fn prerelease_config_round_trips_through_serialize() {
        for v in [
            PrereleaseConfig::Auto,
            PrereleaseConfig::Bool(true),
            PrereleaseConfig::Bool(false),
        ] {
            let yaml = serde_yaml_ng::to_string(&v).unwrap();
            assert_eq!(
                serde_yaml_ng::from_str::<PrereleaseConfig>(&yaml).unwrap(),
                v
            );
        }
    }

    #[test]
    fn make_latest_config_parses_all_arms() {
        assert_eq!(
            serde_yaml_ng::from_str::<MakeLatestConfig>("auto").unwrap(),
            MakeLatestConfig::Auto
        );
        assert_eq!(
            serde_yaml_ng::from_str::<MakeLatestConfig>("true").unwrap(),
            MakeLatestConfig::Bool(true)
        );
        assert_eq!(
            serde_yaml_ng::from_str::<MakeLatestConfig>("false").unwrap(),
            MakeLatestConfig::Bool(false)
        );
        // A non-keyword string falls through to a deferred template.
        assert_eq!(
            serde_yaml_ng::from_str::<MakeLatestConfig>(
                "\"{{ if .IsSnapshot }}false{{ else }}true{{ end }}\""
            )
            .unwrap(),
            MakeLatestConfig::String(
                "{{ if .IsSnapshot }}false{{ else }}true{{ end }}".to_string()
            )
        );
    }

    #[test]
    fn make_latest_config_round_trips_through_serialize() {
        for v in [
            MakeLatestConfig::Auto,
            MakeLatestConfig::Bool(false),
            MakeLatestConfig::String("{{ .Env.LATEST }}".to_string()),
        ] {
            let yaml = serde_yaml_ng::to_string(&v).unwrap();
            assert_eq!(
                serde_yaml_ng::from_str::<MakeLatestConfig>(&yaml).unwrap(),
                v
            );
        }
    }

    #[test]
    fn skip_push_config_parses_all_arms() {
        assert_eq!(
            serde_yaml_ng::from_str::<SkipPushConfig>("auto").unwrap(),
            SkipPushConfig::Auto
        );
        assert_eq!(
            serde_yaml_ng::from_str::<SkipPushConfig>("true").unwrap(),
            SkipPushConfig::Bool(true)
        );
        assert_eq!(
            serde_yaml_ng::from_str::<SkipPushConfig>("false").unwrap(),
            SkipPushConfig::Bool(false)
        );
        assert_eq!(
            serde_yaml_ng::from_str::<SkipPushConfig>("\"{{ .IsSnapshot }}\"").unwrap(),
            SkipPushConfig::Template("{{ .IsSnapshot }}".to_string())
        );
    }

    #[test]
    fn skip_push_config_round_trips_through_serialize() {
        for v in [
            SkipPushConfig::Auto,
            SkipPushConfig::Bool(true),
            SkipPushConfig::Template("{{ .IsSnapshot }}".to_string()),
        ] {
            let yaml = serde_yaml_ng::to_string(&v).unwrap();
            assert_eq!(serde_yaml_ng::from_str::<SkipPushConfig>(&yaml).unwrap(), v);
        }
    }

    #[test]
    fn resolved_upload_pace_defaults_and_honors_override() {
        // Unset → the 200ms default that smooths the initial upload burst.
        assert_eq!(
            ReleaseConfig::default().resolved_upload_pace(),
            ReleaseConfig::DEFAULT_UPLOAD_PACE
        );
        // A configured humantime value is used verbatim.
        let cfg = ReleaseConfig {
            upload_pace: Some(HumanDuration(std::time::Duration::from_secs(1))),
            ..Default::default()
        };
        assert_eq!(
            cfg.resolved_upload_pace(),
            std::time::Duration::from_secs(1)
        );
        // "0s" disables pacing (resolves to ZERO, not the default).
        let disabled = ReleaseConfig {
            upload_pace: Some(HumanDuration(std::time::Duration::ZERO)),
            ..Default::default()
        };
        assert_eq!(disabled.resolved_upload_pace(), std::time::Duration::ZERO);
    }

    #[test]
    fn on_failure_config_display_and_default() {
        assert_eq!(OnFailureConfig::default(), OnFailureConfig::Rollback);
        assert_eq!(OnFailureConfig::Rollback.to_string(), "rollback");
        assert_eq!(OnFailureConfig::Hold.to_string(), "hold");
        // The lowercase serde form round-trips.
        assert_eq!(
            serde_yaml_ng::from_str::<OnFailureConfig>("hold").unwrap(),
            OnFailureConfig::Hold
        );
    }
}