Skip to main content

anodizer_core/config/
source.rs

1use schemars::JsonSchema;
2use serde::{Deserialize, Deserializer, Serialize};
3
4use super::StringOrU32;
5
6// ---------------------------------------------------------------------------
7// SourceConfig
8// ---------------------------------------------------------------------------
9
10/// An individual file entry for the source archive, supporting src/dst mapping
11/// and file metadata overrides.
12#[derive(Debug, Clone, Serialize, Deserialize, Default, JsonSchema)]
13#[serde(default, deny_unknown_fields)]
14pub struct SourceFileEntry {
15    /// Source file path or glob pattern.
16    pub src: String,
17    /// Destination path within the archive prefix directory.
18    pub dst: Option<String>,
19    /// Strip the parent directory from the source path.
20    pub strip_parent: Option<bool>,
21    /// File metadata overrides.
22    pub info: Option<SourceFileInfo>,
23}
24
25/// File metadata overrides for source archive entries.
26#[derive(Debug, Clone, Serialize, Deserialize, Default, JsonSchema)]
27#[serde(default, deny_unknown_fields)]
28pub struct SourceFileInfo {
29    /// File owner.
30    pub owner: Option<String>,
31    /// File group.
32    pub group: Option<String>,
33    /// File permissions mode. Accepts a YAML int (decimal) or an
34    /// octal-prefixed string (`"0o755"`, `"0755"`). Stored as a `u32` after
35    /// parsing — see [`StringOrU32`].
36    pub mode: Option<StringOrU32>,
37    /// Modification time in RFC3339 format (supports templates).
38    pub mtime: Option<String>,
39}
40
41#[derive(Debug, Clone, Serialize, Deserialize, Default, JsonSchema)]
42#[serde(default, deny_unknown_fields)]
43pub struct SourceConfig {
44    /// When true, generate a source code archive for the release.
45    pub enabled: Option<bool>,
46    /// Archive format for the source tarball: tar.gz, tgz, tar, or zip (default: tar.gz).
47    pub format: Option<String>,
48    /// Filename template for the source archive (supports templates).
49    pub name_template: Option<String>,
50    /// Prefix prepended to all paths inside the archive (supports templates).
51    /// Defaults to name_template value. Use this to set a different prefix than the archive name.
52    pub prefix_template: Option<String>,
53    /// Extra files to include in the source archive. Accepts strings (glob patterns) or objects with src/dst/info.
54    #[serde(default, deserialize_with = "deserialize_source_files")]
55    #[schemars(schema_with = "source_files_schema")]
56    pub files: Vec<SourceFileEntry>,
57}
58
59impl SourceConfig {
60    /// Whether source archive generation is enabled (default: false).
61    pub fn is_enabled(&self) -> bool {
62        self.enabled.unwrap_or(false)
63    }
64
65    /// Archive format to use (default: "tar.gz").
66    pub fn archive_format(&self) -> &str {
67        self.format.as_deref().unwrap_or("tar.gz")
68    }
69
70    /// Apply defaults to `prefix_template`: when unset and `name_template` is
71    /// set, default `prefix_template` to the same string as `name_template`.
72    ///
73    /// Q-src3: the doc has long claimed "Defaults to `name_template` value",
74    /// but downstream consumers were reading the raw `Option<String>` and
75    /// substituting empty string. Filling the field at defaults-resolution
76    /// time honors the documented contract — stage code that already
77    /// renders the (now-Some) field needs no behavioral change.
78    ///
79    /// Defaults to
80    /// empty; this is anodize-additive (more ergonomic default), aligning
81    /// behavior with the long-standing doc.
82    pub fn apply_prefix_template_default(&mut self) {
83        if self.prefix_template.is_none()
84            && let Some(ref name_tpl) = self.name_template
85        {
86            self.prefix_template = Some(name_tpl.clone());
87        }
88    }
89}
90
91/// Helper schema function for the source files field (accepts strings, objects, or mixed arrays).
92fn source_files_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
93    let mut schema = generator.subschema_for::<Vec<SourceFileEntry>>();
94    schema.ensure_object().insert(
95        "description".to_owned(),
96        "Extra files for the source archive. Accepts strings (glob patterns), objects with src/dst/info, or a mixed array.".into(),
97    );
98    schema
99}
100
101/// Custom deserializer for the source `files` field.
102/// Accepts:
103///   - null/missing → empty vec (via serde default)
104///   - a single string → vec of one SourceFileEntry with that src
105///   - a single object → vec of one SourceFileEntry
106///   - an array of mixed strings/objects → vec of SourceFileEntry
107fn deserialize_source_files<'de, D>(deserializer: D) -> Result<Vec<SourceFileEntry>, D::Error>
108where
109    D: Deserializer<'de>,
110{
111    use serde::de::{self, SeqAccess, Visitor};
112
113    struct SourceFilesVisitor;
114
115    impl<'de> Visitor<'de> for SourceFilesVisitor {
116        type Value = Vec<SourceFileEntry>;
117
118        fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
119            f.write_str("a string, a source file entry object, or an array of strings/objects")
120        }
121
122        fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
123            Ok(vec![SourceFileEntry {
124                src: v.to_string(),
125                ..Default::default()
126            }])
127        }
128
129        fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
130            let mut entries = Vec::new();
131            while let Some(value) = seq.next_element::<serde_yaml_ng::Value>()? {
132                match value {
133                    serde_yaml_ng::Value::String(s) => {
134                        entries.push(SourceFileEntry {
135                            src: s,
136                            ..Default::default()
137                        });
138                    }
139                    other => {
140                        let entry =
141                            SourceFileEntry::deserialize(other).map_err(de::Error::custom)?;
142                        entries.push(entry);
143                    }
144                }
145            }
146            Ok(entries)
147        }
148
149        fn visit_map<M: de::MapAccess<'de>>(self, map: M) -> Result<Self::Value, M::Error> {
150            let entry = SourceFileEntry::deserialize(de::value::MapAccessDeserializer::new(map))?;
151            Ok(vec![entry])
152        }
153
154        fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
155            Ok(Vec::new())
156        }
157
158        fn visit_none<E: de::Error>(self) -> Result<Self::Value, E> {
159            Ok(Vec::new())
160        }
161    }
162
163    deserializer.deserialize_any(SourceFilesVisitor)
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169
170    fn parse(yaml: &str) -> SourceConfig {
171        serde_yaml_ng::from_str(yaml).expect("valid SourceConfig YAML")
172    }
173
174    #[test]
175    fn is_enabled_defaults_false_when_unset() {
176        let cfg = SourceConfig::default();
177        assert!(!cfg.is_enabled());
178    }
179
180    #[test]
181    fn is_enabled_honors_explicit_values() {
182        assert!(parse("enabled: true").is_enabled());
183        assert!(!parse("enabled: false").is_enabled());
184    }
185
186    #[test]
187    fn archive_format_defaults_to_tar_gz() {
188        assert_eq!(SourceConfig::default().archive_format(), "tar.gz");
189    }
190
191    #[test]
192    fn archive_format_uses_explicit_format() {
193        assert_eq!(parse("format: zip").archive_format(), "zip");
194    }
195
196    #[test]
197    fn prefix_default_copies_name_template_when_prefix_unset() {
198        let mut cfg = parse("name_template: \"{{ .ProjectName }}-{{ .Version }}\"");
199        assert!(cfg.prefix_template.is_none());
200        cfg.apply_prefix_template_default();
201        assert_eq!(
202            cfg.prefix_template.as_deref(),
203            Some("{{ .ProjectName }}-{{ .Version }}")
204        );
205    }
206
207    #[test]
208    fn prefix_default_preserves_explicit_prefix() {
209        let mut cfg = parse("name_template: name-tpl\nprefix_template: prefix-tpl");
210        cfg.apply_prefix_template_default();
211        assert_eq!(cfg.prefix_template.as_deref(), Some("prefix-tpl"));
212    }
213
214    #[test]
215    fn prefix_default_noop_when_name_template_also_unset() {
216        let mut cfg = SourceConfig::default();
217        cfg.apply_prefix_template_default();
218        assert!(cfg.prefix_template.is_none());
219    }
220
221    #[test]
222    fn files_missing_is_empty_vec() {
223        assert!(parse("enabled: true").files.is_empty());
224    }
225
226    #[test]
227    fn files_single_string_becomes_one_entry() {
228        let cfg = parse("files: LICENSE");
229        assert_eq!(cfg.files.len(), 1);
230        assert_eq!(cfg.files[0].src, "LICENSE");
231        assert!(cfg.files[0].dst.is_none());
232    }
233
234    #[test]
235    fn files_single_object_becomes_one_entry() {
236        let cfg = parse("files:\n  src: README.md\n  dst: docs/README.md");
237        assert_eq!(cfg.files.len(), 1);
238        assert_eq!(cfg.files[0].src, "README.md");
239        assert_eq!(cfg.files[0].dst.as_deref(), Some("docs/README.md"));
240    }
241
242    #[test]
243    fn files_mixed_array_parses_strings_and_objects() {
244        let cfg = parse("files:\n  - LICENSE\n  - src: README.md\n    dst: docs/README.md\n");
245        assert_eq!(cfg.files.len(), 2);
246        assert_eq!(cfg.files[0].src, "LICENSE");
247        assert!(cfg.files[0].dst.is_none());
248        assert_eq!(cfg.files[1].src, "README.md");
249        assert_eq!(cfg.files[1].dst.as_deref(), Some("docs/README.md"));
250    }
251
252    #[test]
253    fn files_null_is_empty_vec() {
254        let cfg = parse("files: null");
255        assert!(cfg.files.is_empty());
256    }
257
258    #[test]
259    fn file_entry_info_mode_parses_octal_string() {
260        let cfg = parse(
261            "files:\n  - src: bin/app\n    info:\n      owner: root\n      mode: \"0o755\"\n",
262        );
263        let info = cfg.files[0].info.as_ref().expect("info present");
264        assert_eq!(info.owner.as_deref(), Some("root"));
265        assert_eq!(info.mode.map(|m| m.value()), Some(0o755));
266    }
267
268    #[test]
269    fn deny_unknown_fields_rejects_typos() {
270        let err = serde_yaml_ng::from_str::<SourceConfig>("enabledd: true");
271        assert!(err.is_err(), "unknown field must be rejected");
272    }
273
274    #[test]
275    fn archive_format_passes_through_tgz_tar_and_zip() {
276        // archive_format only overrides the default when format is Some; each
277        // explicit value must survive verbatim (no normalization).
278        assert_eq!(parse("format: tgz").archive_format(), "tgz");
279        assert_eq!(parse("format: tar").archive_format(), "tar");
280        assert_eq!(parse("format: zip").archive_format(), "zip");
281    }
282
283    #[test]
284    fn prefix_default_keeps_explicit_prefix_when_name_template_absent() {
285        // The unset-name guard must not clobber a prefix the user set alone.
286        let mut cfg = parse("prefix_template: only-prefix");
287        cfg.apply_prefix_template_default();
288        assert_eq!(cfg.prefix_template.as_deref(), Some("only-prefix"));
289    }
290
291    #[test]
292    fn file_entry_strip_parent_round_trips() {
293        let cfg = parse("files:\n  - src: a/b/c.txt\n    strip_parent: true\n");
294        assert_eq!(cfg.files[0].strip_parent, Some(true));
295        // unset on a plain string entry, not defaulted to a value
296        let bare = parse("files: a/b/c.txt");
297        assert_eq!(bare.files[0].strip_parent, None);
298    }
299
300    #[test]
301    fn file_info_mode_accepts_bare_decimal_int() {
302        // A bare YAML int is decimal: 493 == 0o755. Distinct path from the
303        // octal-prefixed-string case already covered above.
304        let cfg = parse("files:\n  - src: bin/app\n    info:\n      mode: 493\n");
305        let info = cfg.files[0].info.as_ref().expect("info present");
306        assert_eq!(info.mode.map(|m| m.value()), Some(0o755));
307    }
308
309    #[test]
310    fn file_info_captures_group_and_mtime() {
311        let cfg = parse(
312            "files:\n  - src: f\n    info:\n      group: staff\n      mtime: \"2024-01-01T00:00:00Z\"\n",
313        );
314        let info = cfg.files[0].info.as_ref().unwrap();
315        assert_eq!(info.group.as_deref(), Some("staff"));
316        assert_eq!(info.mtime.as_deref(), Some("2024-01-01T00:00:00Z"));
317        assert!(info.owner.is_none());
318    }
319
320    #[test]
321    fn nested_file_entry_rejects_unknown_field() {
322        let err = serde_yaml_ng::from_str::<SourceConfig>("files:\n  - src: f\n    bogus: 1\n");
323        assert!(err.is_err(), "SourceFileEntry must deny unknown fields");
324    }
325
326    #[test]
327    fn nested_file_info_rejects_unknown_field() {
328        let err = serde_yaml_ng::from_str::<SourceConfig>(
329            "files:\n  - src: f\n    info:\n      moed: 7\n",
330        );
331        assert!(err.is_err(), "SourceFileInfo must deny unknown fields");
332    }
333
334    #[test]
335    fn empty_array_files_is_empty_vec() {
336        // visit_seq with zero elements is a distinct branch from visit_none.
337        let cfg = parse("files: []");
338        assert!(cfg.files.is_empty());
339    }
340
341    #[test]
342    fn files_array_of_objects_only() {
343        let cfg = parse("files:\n  - src: a\n    dst: x/a\n  - src: b\n");
344        assert_eq!(cfg.files.len(), 2);
345        assert_eq!(cfg.files[0].dst.as_deref(), Some("x/a"));
346        assert_eq!(cfg.files[1].src, "b");
347        assert!(cfg.files[1].dst.is_none());
348    }
349
350    #[test]
351    fn config_round_trips_through_serde() {
352        let cfg = parse(
353            "enabled: true\nformat: zip\nname_template: src-{{ .Version }}\nfiles:\n  - LICENSE\n",
354        );
355        let yaml = serde_yaml_ng::to_string(&cfg).unwrap();
356        let back: SourceConfig = serde_yaml_ng::from_str(&yaml).unwrap();
357        assert!(back.is_enabled());
358        assert_eq!(back.archive_format(), "zip");
359        assert_eq!(back.files.len(), 1);
360        assert_eq!(back.files[0].src, "LICENSE");
361    }
362}