Skip to main content

anodizer_core/config/
snapshot_nightly.rs

1use schemars::JsonSchema;
2use serde::{Deserialize, Serialize};
3
4use super::{CommitAuthorConfig, ContentSource};
5
6// ---------------------------------------------------------------------------
7// SnapshotConfig
8// ---------------------------------------------------------------------------
9
10#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
11#[serde(deny_unknown_fields)]
12pub struct SnapshotConfig {
13    /// Version string template for snapshot builds (e.g., "{{ Commit }}-SNAPSHOT").
14    /// Accepts the deprecated `name_template:` alias (renamed to
15    /// `version_template`): a non-empty `name_template` is folded into
16    /// `version_template`.
17    /// A deprecation warning is emitted at config-load time when the alias
18    /// is hit (see `apply_snapshot_legacy_aliases`).
19    #[serde(alias = "name_template")]
20    pub version_template: String,
21}
22
23// ---------------------------------------------------------------------------
24// NightlyConfig
25// ---------------------------------------------------------------------------
26
27#[derive(Debug, Clone, Serialize, Deserialize, Default, JsonSchema)]
28#[serde(default, deny_unknown_fields)]
29pub struct NightlyConfig {
30    /// Template for the rendered version string the nightly run sets on
31    /// `Version` / `RawVersion`. Default:
32    /// `"{{ incpatch(v=Version) }}-{{ ShortCommit }}-nightly"` — produces
33    /// commit-immutable nightly versions (two same-day commits yield two
34    /// distinct nightly versions).
35    ///
36    /// The `{{ NightlyBuild }}` template var (a stateless per-base-version
37    /// build counter derived from `git rev-list --count <last-tag>..HEAD`)
38    /// enables nushell-style schemes such as
39    /// `"{{ Base }}-nightly.{{ NightlyBuild }}+{{ ShortCommit }}"`.
40    pub version_template: Option<String>,
41    /// Template for the release name. Default: `"{{ ProjectName }}-nightly"`.
42    pub name_template: Option<String>,
43    /// Tag name used for the nightly release. Default: `"nightly"`.
44    /// Templates allowed.
45    pub tag_name: Option<String>,
46    /// Whether to publish a GitHub Release at all. Default: `true`.
47    /// Set `false` for nightly-only docker pushes / blob uploads.
48    pub publish_release: Option<bool>,
49    /// Publish the nightly release to a DIFFERENT repository than the source
50    /// repo, in `"owner/repo"` form (e.g. `"nushell/nightly"`). Default
51    /// (`None`) publishes to the configured `release.github` repo, unchanged.
52    ///
53    /// When set, the nightly release create, asset upload, AND retention
54    /// (`keep_single_release` / `retention.keep_last`) delete calls all
55    /// target this repo. The active SCM token is assumed to have write
56    /// access to `publish_repo`. GitHub-only (the nushell adoption target).
57    pub publish_repo: Option<String>,
58    /// Delete the prior release that points at the same tag before
59    /// creating the new one. Default: `false`. Set `true` to maintain a
60    /// single rolling nightly release on GitHub.
61    ///
62    /// Back-compat alias for `retention: { keep_last: 1 }`. When both
63    /// `keep_single_release` and `retention` are set, `retention` wins.
64    /// Destructive: deletes a published release via the GitHub Releases API.
65    /// GitHub-only.
66    pub keep_single_release: Option<bool>,
67    /// Retention policy for nightly releases on GitHub. Generalizes
68    /// `keep_single_release` (which is `keep_last: 1`): keeps the N newest
69    /// nightly releases matching the nightly tag/name and deletes the rest
70    /// (releases + the tags anodizer created for them). Operates on
71    /// `publish_repo` when set. Default (`None`): no retention sweep.
72    pub retention: Option<RetentionConfig>,
73    /// Override `release.draft` for nightly runs only.
74    /// `None` falls through to `release.draft`; `Some(v)` overrides it.
75    pub draft: Option<bool>,
76}
77
78/// Retention policy for nightly releases on the publish repo.
79///
80/// `keep_last: N` keeps the N newest nightly releases (matched by the
81/// nightly tag/name) and deletes the older ones, including the git tags
82/// anodizer created for them.
83#[derive(Debug, Clone, Serialize, Deserialize, Default, JsonSchema)]
84#[serde(default, deny_unknown_fields)]
85pub struct RetentionConfig {
86    /// Number of newest nightly releases to keep. `0` is treated as `1`
87    /// (never delete every nightly), matching the `keep_single_release`
88    /// floor. nushell keeps 10.
89    pub keep_last: usize,
90}
91
92impl NightlyConfig {
93    /// Resolve the effective `keep_last` retention count, or `None` when no
94    /// retention is requested.
95    ///
96    /// Precedence: an explicit `retention:` block wins over the legacy
97    /// `keep_single_release:` alias. `keep_single_release: true` (with no
98    /// `retention`) maps to `keep_last: 1`; `false` maps to `None`. A
99    /// `retention.keep_last: 0` is floored to `1` so a retention sweep
100    /// never deletes the just-created release.
101    pub fn resolved_keep_last(&self) -> Option<usize> {
102        if let Some(r) = self.retention.as_ref() {
103            return Some(r.keep_last.max(1));
104        }
105        if self.keep_single_release == Some(true) {
106            return Some(1);
107        }
108        None
109    }
110}
111
112/// Validate `nightly.publish_repo` is `"owner/repo"` shaped.
113///
114/// Returns `Ok(())` when unset or well-formed. A malformed value (missing
115/// `/`, empty owner/repo, extra path segments, or whitespace) is a
116/// config-time error rather than a confusing 404 at publish time.
117pub fn validate_nightly_publish_repo(config: &crate::config::Config) -> Result<(), String> {
118    let Some(nightly) = config.nightly.as_ref() else {
119        return Ok(());
120    };
121    let Some(repo) = nightly.publish_repo.as_deref() else {
122        return Ok(());
123    };
124    let parts: Vec<&str> = repo.split('/').collect();
125    let well_formed = parts.len() == 2
126        && parts
127            .iter()
128            .all(|p| !p.trim().is_empty() && !p.contains(char::is_whitespace));
129    if well_formed {
130        Ok(())
131    } else {
132        Err(format!(
133            "nightly.publish_repo must be in \"owner/repo\" form (got {repo:?})"
134        ))
135    }
136}
137
138// ---------------------------------------------------------------------------
139// MetadataConfig
140// ---------------------------------------------------------------------------
141
142#[derive(Debug, Clone, Serialize, Deserialize, Default, JsonSchema)]
143#[serde(default, deny_unknown_fields)]
144pub struct MetadataConfig {
145    /// Human-readable project description (exposed as `{{ Metadata.Description }}`).
146    pub description: Option<String>,
147    /// Project homepage URL (exposed as `{{ Metadata.Homepage }}`).
148    pub homepage: Option<String>,
149    /// Project documentation URL, e.g. a docs.rs or hosted-docs link
150    /// (exposed as `{{ Metadata.Documentation }}`). Derived from
151    /// `Cargo.toml [package].documentation` when unset.
152    pub documentation: Option<String>,
153    /// Project license identifier, e.g. "MIT" or "Apache-2.0" (exposed as `{{ Metadata.License }}`).
154    pub license: Option<String>,
155    /// Project source-repository URL, e.g. a GitHub URL (exposed as
156    /// `{{ Metadata.Repository }}`). Derived from `Cargo.toml [package].repository`
157    /// when unset; feeds the npm `package.json` `repository` field, which npm
158    /// provenance validates against the OIDC-claimed repository.
159    // Omit-when-None so adding this field leaves `dist/config.yaml` byte-identical
160    // for configs that don't set it — a republish/backfill of an older tag's
161    // preserved dist re-renders config.yaml and hash-verifies it against the
162    // determinism shards, which a new always-emitted `repository: null` line would
163    // break. The sibling fields predate this invariant and stay as-is.
164    #[serde(skip_serializing_if = "Option::is_none")]
165    pub repository: Option<String>,
166    /// List of project maintainers (exposed as `{{ Metadata.Maintainers }}`).
167    pub maintainers: Option<Vec<String>>,
168    /// Global modification timestamp for metadata output files (metadata.json and artifacts.json).
169    /// Template string (e.g. "{{ CommitTimestamp }}") or unix timestamp.
170    /// When set, rendered late in the pipeline and applied as file mtime.
171    /// Exposed as `{{ Metadata.ModTimestamp }}`.
172    pub mod_timestamp: Option<String>,
173    /// Long-form project description. Supports inline
174    /// string, `from_file`, or `from_url`. Exposed as `{{ Metadata.FullDescription }}`.
175    /// FromUrl is resolved lazily (requires the release stage); FromFile is resolved
176    /// at context-populate time with template-rendered path.
177    pub full_description: Option<ContentSource>,
178    /// Commit author identity for commit workflows.
179    /// Reuses the shared `CommitAuthorConfig` (name + email + optional signing).
180    /// Exposed as `{{ Metadata.CommitAuthor.Name }}` / `{{ Metadata.CommitAuthor.Email }}`.
181    pub commit_author: Option<CommitAuthorConfig>,
182}
183
184#[cfg(test)]
185mod tests {
186    use super::*;
187    use crate::config::Config;
188
189    #[test]
190    fn resolved_keep_last_maps_keep_single_release_alias() {
191        let n = NightlyConfig {
192            keep_single_release: Some(true),
193            ..Default::default()
194        };
195        assert_eq!(n.resolved_keep_last(), Some(1));
196    }
197
198    #[test]
199    fn resolved_keep_last_none_when_neither_set() {
200        let n = NightlyConfig::default();
201        assert_eq!(n.resolved_keep_last(), None);
202        let n = NightlyConfig {
203            keep_single_release: Some(false),
204            ..Default::default()
205        };
206        assert_eq!(n.resolved_keep_last(), None);
207    }
208
209    #[test]
210    fn resolved_keep_last_retention_wins_over_alias() {
211        // Both set: retention.keep_last wins over the legacy alias.
212        let n = NightlyConfig {
213            keep_single_release: Some(true),
214            retention: Some(RetentionConfig { keep_last: 10 }),
215            ..Default::default()
216        };
217        assert_eq!(n.resolved_keep_last(), Some(10));
218    }
219
220    #[test]
221    fn resolved_keep_last_floors_zero_to_one() {
222        let n = NightlyConfig {
223            retention: Some(RetentionConfig { keep_last: 0 }),
224            ..Default::default()
225        };
226        assert_eq!(n.resolved_keep_last(), Some(1));
227    }
228
229    #[test]
230    fn keep_single_release_yaml_alias_round_trips() {
231        // Back-compat: an existing keep_single_release config still parses
232        // and resolves to keep_last: 1.
233        let n: NightlyConfig = serde_yaml_ng::from_str("keep_single_release: true").unwrap();
234        assert_eq!(n.resolved_keep_last(), Some(1));
235    }
236
237    fn config_with_publish_repo(repo: Option<&str>) -> Config {
238        Config {
239            nightly: Some(NightlyConfig {
240                publish_repo: repo.map(str::to_string),
241                ..Default::default()
242            }),
243            ..Default::default()
244        }
245    }
246
247    #[test]
248    fn validate_publish_repo_accepts_owner_repo() {
249        let c = config_with_publish_repo(Some("nushell/nightly"));
250        assert!(validate_nightly_publish_repo(&c).is_ok());
251    }
252
253    #[test]
254    fn validate_publish_repo_ok_when_unset() {
255        assert!(validate_nightly_publish_repo(&config_with_publish_repo(None)).is_ok());
256        assert!(validate_nightly_publish_repo(&Config::default()).is_ok());
257    }
258
259    #[test]
260    fn validate_publish_repo_rejects_malformed() {
261        for bad in ["nushell", "a/b/c", "/nightly", "nushell/", "owner repo/x"] {
262            let c = config_with_publish_repo(Some(bad));
263            assert!(
264                validate_nightly_publish_repo(&c).is_err(),
265                "expected {bad:?} to be rejected"
266            );
267        }
268    }
269
270    #[test]
271    fn metadata_repository_omitted_when_none_keeps_config_yaml_byte_stable() {
272        // A metadata block that does NOT set repository must serialize WITHOUT a
273        // `repository` key, so introducing the field leaves dist/config.yaml
274        // byte-identical and a backfill's hash-verify against older preserved
275        // determinism shards still passes.
276        let m = MetadataConfig {
277            homepage: Some("https://example.com".into()),
278            ..Default::default()
279        };
280        let yaml = serde_yaml_ng::to_string(&m).expect("serialize");
281        assert!(
282            !yaml.contains("repository"),
283            "unset repository must be omitted, got:\n{yaml}"
284        );
285        // When set, it is emitted (npm provenance / template var still work).
286        let m2 = MetadataConfig {
287            repository: Some("https://github.com/x/y".into()),
288            ..Default::default()
289        };
290        assert!(
291            serde_yaml_ng::to_string(&m2)
292                .expect("serialize")
293                .contains("repository: https://github.com/x/y"),
294        );
295    }
296}