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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
use std::collections::HashMap;

use schemars::JsonSchema;
use serde::{Deserialize, Deserializer, Serialize};

use super::{
    ArchiveHooksConfig, SignConfig, StringOrBool, StringOrU32, deserialize_string_or_bool_opt,
};

// ---------------------------------------------------------------------------
// ArchivesConfig — untagged enum: false => Disabled, array => Configs
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, JsonSchema)]
pub enum ArchivesConfig {
    Disabled,
    Configs(Vec<ArchiveConfig>),
}

impl Serialize for ArchivesConfig {
    fn serialize<S: serde::Serializer>(
        &self,
        serializer: S,
    ) -> std::result::Result<S::Ok, S::Error> {
        match self {
            ArchivesConfig::Disabled => serializer.serialize_bool(false),
            ArchivesConfig::Configs(configs) => configs.serialize(serializer),
        }
    }
}

impl Default for ArchivesConfig {
    fn default() -> Self {
        ArchivesConfig::Configs(vec![])
    }
}

/// Custom deserializer for ArchivesConfig.
/// Accepts:
///   - boolean `false`  → Disabled
///   - array            → Configs(...)
///   - missing/null     → Configs([])  (via serde default)
pub(super) fn deserialize_archives_config<'de, D>(
    deserializer: D,
) -> Result<ArchivesConfig, D::Error>
where
    D: Deserializer<'de>,
{
    use serde::de::{self, Visitor};

    struct ArchivesVisitor;

    impl<'de> Visitor<'de> for ArchivesVisitor {
        type Value = ArchivesConfig;

        fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.write_str("false or a list of archive configs")
        }

        fn visit_bool<E: de::Error>(self, v: bool) -> Result<Self::Value, E> {
            if !v {
                Ok(ArchivesConfig::Disabled)
            } else {
                Err(E::custom(
                    "archives: true is not valid; use false or a list",
                ))
            }
        }

        fn visit_seq<A: de::SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
            let mut configs = Vec::new();
            while let Some(item) = seq.next_element::<ArchiveConfig>()? {
                configs.push(item);
            }
            Ok(ArchivesConfig::Configs(configs))
        }

        // Handle YAML null / missing when serde calls the deserializer explicitly.
        fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
            Ok(ArchivesConfig::Configs(vec![]))
        }

        fn visit_none<E: de::Error>(self) -> Result<Self::Value, E> {
            Ok(ArchivesConfig::Configs(vec![]))
        }
    }

    deserializer.deserialize_any(ArchivesVisitor)
}

/// Custom deserializer for the `signs` / `sign` field.
/// Accepts:
///   - null/missing → empty vec (via serde default)
///   - a single object → vec of one SignConfig
///   - an array → vec of SignConfig
pub(super) fn deserialize_signs<'de, D>(deserializer: D) -> Result<Vec<SignConfig>, D::Error>
where
    D: Deserializer<'de>,
{
    use serde::de::{self, Visitor};

    struct SignsVisitor;

    impl<'de> Visitor<'de> for SignsVisitor {
        type Value = Vec<SignConfig>;

        fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.write_str("a sign config object or an array of sign config objects")
        }

        fn visit_seq<A: de::SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
            let mut configs = Vec::new();
            while let Some(item) = seq.next_element::<SignConfig>()? {
                configs.push(item);
            }
            Ok(configs)
        }

        fn visit_map<M: de::MapAccess<'de>>(self, map: M) -> Result<Self::Value, M::Error> {
            let config = SignConfig::deserialize(de::value::MapAccessDeserializer::new(map))?;
            Ok(vec![config])
        }

        fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
            Ok(Vec::new())
        }

        fn visit_none<E: de::Error>(self) -> Result<Self::Value, E> {
            Ok(Vec::new())
        }
    }

    deserializer.deserialize_any(SignsVisitor)
}

// `binary_signs[].artifacts` is constrained at deserialize time (not as a
// serde-typed enum) because `SignConfig` is shared with the top-level `signs:`
// field, which legitimately accepts a wider set (`all`, `archive`, `binary`,
// `checksum`, `package`, `sbom`, `none`). Promoting `artifacts` to an enum
// would either narrow that surface or require a parallel `BinarySignConfig`
// type duplicating every `SignConfig` field — the runtime check below keeps
// `SignConfig` a single shared shape while still rejecting misconfigured
// `binary_signs` entries at config-load time.
//
// The JSON schema for `binary_signs[]` therefore inherits `SignConfig`'s
// unconstrained `artifacts: Option<String>` — the constraint lives in the
// custom deserializer below and is exercised by the parse-time tests
// `test_binary_signs_artifacts_*` further down this file.

/// Wraps [`deserialize_signs`] and enforces that each entry's `artifacts`
/// is one of the binary-only allowed values (`binary`, `none`, or omitted).
/// Catches misconfiguration at load time instead of producing a silent
/// no-op signing pipe.
pub(super) fn deserialize_binary_signs<'de, D>(deserializer: D) -> Result<Vec<SignConfig>, D::Error>
where
    D: Deserializer<'de>,
{
    let configs = deserialize_signs(deserializer)?;
    for (idx, cfg) in configs.iter().enumerate() {
        if let Some(art) = cfg.artifacts.as_deref()
            && art != "binary"
            && art != "none"
        {
            return Err(serde::de::Error::custom(format!(
                "binary_signs[{idx}].artifacts: '{art}' is not allowed; \
                 binary_signs accepts only 'binary' or 'none' (use top-level \
                 `signs:` for broader artifact filters)"
            )));
        }
    }
    Ok(configs)
}

// ---------------------------------------------------------------------------
// WrapInDirectory – accepts bool (true = default dir name) or string
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
#[serde(untagged)]
pub enum WrapInDirectory {
    Bool(bool),
    Name(String),
}

impl<'de> serde::Deserialize<'de> for WrapInDirectory {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let value = serde_yaml_ng::Value::deserialize(deserializer)?;
        match value {
            serde_yaml_ng::Value::Bool(b) => Ok(WrapInDirectory::Bool(b)),
            serde_yaml_ng::Value::String(s) => Ok(WrapInDirectory::Name(s)),
            _ => Err(serde::de::Error::custom("expected bool or string")),
        }
    }
}

impl WrapInDirectory {
    /// Resolve the directory name to wrap archive contents in.
    ///
    /// When `true`, uses `default_name` (typically the archive stem).
    /// When `false` or an empty string, returns `None` (no wrapping).
    /// Otherwise returns the custom name.
    pub fn directory_name(&self, default_name: &str) -> Option<String> {
        match self {
            WrapInDirectory::Bool(true) => Some(default_name.to_string()),
            WrapInDirectory::Bool(false) => None,
            WrapInDirectory::Name(s) if s.is_empty() => None,
            WrapInDirectory::Name(s) => Some(s.clone()),
        }
    }
}

// ---------------------------------------------------------------------------
// ArchiveConfig
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize, Default, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ArchiveConfig {
    /// Unique identifier for cross-referencing this archive from other configs.
    /// Defaults to `"default"` so a parse->serialise->reparse round-trip is
    /// stable (stored verbatim, not as an Option).
    pub id: Option<String>,
    /// Archive filename template (supports templates, e.g., "{{ ProjectName }}_{{ Version }}_{{ Os }}_{{ Arch }}").
    pub name_template: Option<String>,
    /// Archive formats: tar.gz, tar.xz, tar.zst, tar, zip, gz, xz, or binary.
    /// `gz` and `xz` are single-file compressors — supplying multiple input
    /// files errors. Plural list; one archive per format is produced for each
    /// target.
    pub formats: Option<Vec<String>>,
    /// Per-OS format overrides for this archive config.
    pub format_overrides: Option<Vec<FormatOverride>>,
    /// Extra files to include in the archive (glob patterns or detailed src/dst specs).
    pub files: Option<Vec<ArchiveFileSpec>>,
    /// Binary names to include (defaults to all binaries from matched builds).
    pub binaries: Option<Vec<String>>,
    /// When set, wrap archive contents in a top-level directory.
    /// Accepts `true` (use archive stem as directory name), `false` (no wrapping),
    /// or a string template for a custom directory name.
    pub wrap_in_directory: Option<WrapInDirectory>,
    /// Build IDs filter: only include artifacts from builds whose `id` is in this list.
    pub ids: Option<Vec<String>>,
    /// When true, create archive with no binaries (metadata-only).
    pub meta: Option<bool>,
    /// File permissions applied to binaries in archives.
    pub builds_info: Option<ArchiveFileInfo>,
    /// Strip binary parent directory in archive (place binaries at archive root).
    pub strip_binary_directory: Option<bool>,
    /// Allow different binary counts across targets. Default false (warn on mismatch).
    pub allow_different_binary_count: Option<bool>,
    /// Pre/post archive hooks (`before`/`after`).
    pub hooks: Option<ArchiveHooksConfig>,
    /// Templated files scoped to this archive entry. Rendered per-archive
    /// (so each entry's `dst:` and contents see `.Os`, `.Arch`, `.Target`,
    /// `.Format`, etc.) and packed into the archive at the rendered `dst:`
    /// path. The `archives[].templated_files:` field.
    pub templated_files: Option<Vec<super::TemplateFileConfig>>,
    /// Template-conditional gate: when the rendered result is falsy
    /// (`"false"` / `"0"` / `"no"` / empty), the archive entry is skipped
    /// entirely (no archives produced for this `id`). Render failure
    /// hard-errors. "Filter artifacts with `if` statements" is listed as a
    /// blanket promise — anodizer surfaces it explicitly to keep imported
    /// configs portable).
    #[serde(rename = "if")]
    pub if_condition: Option<String>,
    /// Turnkey shell-completion generation: auto-generate (or harvest, or
    /// copy) completion files and bundle them into every archive produced by
    /// this entry. See [`CompletionsConfig`] for the three generation modes.
    pub completions: Option<super::CompletionsConfig>,
    /// Turnkey man-page generation: auto-generate (or harvest, or copy) man
    /// pages and bundle them into every archive produced by this entry. See
    /// [`ManpagesConfig`] for the three generation modes.
    pub manpages: Option<super::ManpagesConfig>,
}

/// Fold a deprecated singular `format: tar.gz` into the canonical
/// `formats: [tar.gz]` list, emitting a `tracing::warn!` deprecation notice
/// keyed by `context_label` (the archive id or override `os=` so the user
/// can locate the offending entry). Returns the folded list (creating one
/// if `formats` was `None` and `legacy` is `Some`).
///
/// Shared by `ArchiveConfig` and `FormatOverride` to keep the deprecation
/// message + fold semantics in one place.
fn fold_format_into_formats(
    context_label: &str,
    context_kind: &str,
    formats: Option<Vec<String>>,
    legacy: Option<String>,
) -> Option<Vec<String>> {
    let mut formats = formats;
    if let Some(legacy) = legacy {
        tracing::warn!(
            "DEPRECATION: {}[{}]: 'format: {}' is deprecated; \
             use 'formats: [{}]' instead.",
            context_kind,
            context_label,
            legacy,
            legacy
        );
        formats.get_or_insert_with(Vec::new).push(legacy);
    }
    formats
}

// Custom Deserialize that accepts deprecated aliases:
// - `format: tar.gz` (singular String) folded into `formats: [tar.gz]`
//
// - `builds: [foo]` folded into `ids: [foo]`
//
// Each alias hit emits a `tracing::warn!` deprecation notice.
impl<'de> Deserialize<'de> for ArchiveConfig {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize, Default)]
        #[serde(default, deny_unknown_fields)]
        struct Raw {
            id: Option<String>,
            name_template: Option<String>,
            formats: Option<Vec<String>>,
            format: Option<String>,
            format_overrides: Option<Vec<FormatOverride>>,
            files: Option<Vec<ArchiveFileSpec>>,
            binaries: Option<Vec<String>>,
            wrap_in_directory: Option<WrapInDirectory>,
            ids: Option<Vec<String>>,
            builds: Option<Vec<String>>,
            meta: Option<bool>,
            builds_info: Option<ArchiveFileInfo>,
            strip_binary_directory: Option<bool>,
            allow_different_binary_count: Option<bool>,
            hooks: Option<ArchiveHooksConfig>,
            templated_files: Option<Vec<super::TemplateFileConfig>>,
            #[serde(rename = "if")]
            if_condition: Option<String>,
            completions: Option<super::CompletionsConfig>,
            manpages: Option<super::ManpagesConfig>,
        }

        let raw = Raw::deserialize(deserializer)?;

        let id_label = raw.id.clone().unwrap_or_else(|| "default".to_string());
        let formats = fold_format_into_formats(
            &format!("id={}", id_label),
            "archives",
            raw.formats,
            raw.format,
        );
        let mut ids = raw.ids;
        if let Some(legacy) = raw.builds {
            tracing::warn!(
                "DEPRECATION: archives[id={}]: 'builds: {:?}' is deprecated; \
                 use 'ids: [...]' instead.",
                id_label,
                legacy
            );
            let target = ids.get_or_insert_with(Vec::new);
            target.extend(legacy);
        }

        Ok(ArchiveConfig {
            id: raw.id.or_else(|| Some("default".to_string())),
            name_template: raw.name_template,
            formats,
            format_overrides: raw.format_overrides,
            files: raw.files,
            binaries: raw.binaries,
            wrap_in_directory: raw.wrap_in_directory,
            ids,
            meta: raw.meta,
            builds_info: raw.builds_info,
            strip_binary_directory: raw.strip_binary_directory,
            allow_different_binary_count: raw.allow_different_binary_count,
            hooks: raw.hooks,
            templated_files: raw.templated_files,
            if_condition: raw.if_condition,
            completions: raw.completions,
            manpages: raw.manpages,
        })
    }
}

#[derive(Debug, Clone, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct FormatOverride {
    /// Operating system this override applies to (e.g., "windows", "darwin", "linux").
    pub os: String,
    /// Plural format overrides for this OS: tar.gz, tar.xz, tar.zst, tar, zip,
    /// gz, xz, or binary.
    pub formats: Option<Vec<String>>,
}

// Custom Deserialize that accepts both `formats: [tar.gz]` (canonical) and
// the deprecated singular `format: tar.gz`. The legacy spelling is folded
// into `formats` at parse time via the shared `fold_format_into_formats`
// helper, which also emits the deprecation warning.
impl<'de> Deserialize<'de> for FormatOverride {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize, Default)]
        #[serde(default, deny_unknown_fields)]
        struct Raw {
            os: String,
            formats: Option<Vec<String>>,
            format: Option<String>,
        }
        let raw = Raw::deserialize(deserializer)?;
        let formats = fold_format_into_formats(
            &format!("os={}", raw.os),
            "archives.format_overrides",
            raw.formats,
            raw.format,
        );
        Ok(FormatOverride {
            os: raw.os,
            formats,
        })
    }
}

/// Specifies a file to include in archives. Can be a simple glob string or a
/// detailed object with src/dst/info fields for controlling archive placement
/// and file metadata.
///
/// NOTE: This is intentionally a separate type from [`ExtraFileSpec`] (used for
/// checksum/release extra_files). `ArchiveFileSpec` needs `src`/`dst`/`info`
/// fields for archive placement and file metadata (owner, group, mode, mtime),
/// while `ExtraFileSpec` needs `glob`/`name_template` for checksumming and
/// upload renaming. The fields and semantics are different enough that a unified
/// type would be confusing.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(untagged)]
pub enum ArchiveFileSpec {
    Glob(String),
    Detailed {
        src: String,
        dst: Option<String>,
        info: Option<ArchiveFileInfo>,
        /// When true, strip the parent directory from the file path in the archive.
        strip_parent: Option<bool>,
    },
}

impl PartialEq<&str> for ArchiveFileSpec {
    fn eq(&self, other: &&str) -> bool {
        match self {
            ArchiveFileSpec::Glob(s) => s.as_str() == *other,
            _ => false,
        }
    }
}

/// Shared file metadata (owner, group, mode, mtime) used by both archive entries
/// and nFPM package contents. Previously duplicated as `ArchiveFileInfo` and
/// `NfpmFileInfo`; now unified.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default, JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct FileInfo {
    /// File owner name (e.g., "root").
    pub owner: Option<String>,
    /// File group name (e.g., "root").
    pub group: Option<String>,
    /// File permission mode. Accepts a YAML int (decimal, e.g. `420` for
    /// `0o644`) or an octal-prefixed string (`"0o644"`, `"0644"`). This
    /// a `uint32` type for `Mode` on archive/nfpm contents
    /// while letting users spell octal naturally in YAML.
    pub mode: Option<StringOrU32>,
    /// File modification time in RFC3339 format (e.g., "2024-01-01T00:00:00Z").
    pub mtime: Option<String>,
}

/// Backward-compatible alias for archive code.
pub type ArchiveFileInfo = FileInfo;

/// Parse an octal mode string into a `u32`, handling common YAML-friendly
/// representations: `"0755"`, `"0o755"`, `"0O755"`, `"755"`, and `"0"`.
pub fn parse_octal_mode(s: &str) -> Option<u32> {
    let cleaned = s
        .strip_prefix("0o")
        .or_else(|| s.strip_prefix("0O"))
        .unwrap_or(s);
    let cleaned = if cleaned.is_empty() { "0" } else { cleaned };
    u32::from_str_radix(cleaned, 8).ok()
}

/// The set of archive format strings recognised by the archive stage.
/// Used for early validation so typos are caught at config load time rather
/// than mid-pipeline.
pub const VALID_ARCHIVE_FORMATS: &[&str] = &[
    "tar.gz", "tgz", "tar.xz", "txz", "tar.zst", "tzst", "tar", "zip", "gz", "xz", "binary", "none",
];

// ---------------------------------------------------------------------------
// ChecksumConfig
// ---------------------------------------------------------------------------

/// Specifies an extra file to include in checksums or release uploads. Can be a
/// simple glob string or a detailed object with glob and name_template fields.
///
/// See [`ArchiveFileSpec`] doc comment for why this is a separate type.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(untagged)]
pub enum ExtraFileSpec {
    Glob(String),
    Detailed {
        glob: String,
        /// Optional override for the upload filename.
        #[serde(default)]
        name_template: Option<String>,
        /// When true, treat a glob that matches zero files as a no-op
        /// rather than a hard error. Useful for assets produced only in
        /// CI (e.g. signing public keys derived from a secret) that
        /// must not break local snapshot/dry-run flows. Defaults to
        /// false, matching the prior fail-fast behavior.
        #[serde(default)]
        allow_empty: bool,
    },
}

impl ExtraFileSpec {
    /// Return the glob pattern for this spec.
    pub fn glob(&self) -> &str {
        match self {
            ExtraFileSpec::Glob(s) => s,
            ExtraFileSpec::Detailed { glob, .. } => glob,
        }
    }

    /// Return the optional name_template (only present in Detailed variant).
    pub fn name_template(&self) -> Option<&str> {
        match self {
            ExtraFileSpec::Glob(_) => None,
            ExtraFileSpec::Detailed { name_template, .. } => name_template.as_deref(),
        }
    }

    /// Return whether this spec allows a zero-match glob without erroring
    /// (Detailed variant only; the bare string form is always fail-fast).
    pub fn allow_empty(&self) -> bool {
        match self {
            ExtraFileSpec::Glob(_) => false,
            ExtraFileSpec::Detailed { allow_empty, .. } => *allow_empty,
        }
    }
}

/// A file whose contents are rendered through the template engine before use.
/// Used by `templated_extra_files` across multiple stages.
#[derive(Debug, Clone, Serialize, Deserialize, Default, JsonSchema, PartialEq)]
#[serde(default, deny_unknown_fields)]
pub struct TemplatedExtraFile {
    /// Source template file path.
    pub src: String,
    /// Destination filename for the rendered output.
    /// Supports template variables (e.g. `"{{ ProjectName }}-NOTES.txt"`).
    pub dst: Option<String>,
    /// File permissions in octal notation as a string, e.g. `"0755"`.
    /// Parsed at runtime via `parse_octal_mode()` to avoid YAML interpreting as decimal.
    pub mode: Option<String>,
}

/// Content format for per-artifact sidecars written in `split` mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum ChecksumSplitFormat {
    /// Only the raw hex hash, no filename, no trailing newline. Matches
    /// GoReleaser's split-checksum output. Default.
    #[default]
    Bare,
    /// `<hash>  <filename>` with a trailing newline — the coreutils / BSD
    /// digest format, so the sidecar verifies directly with
    /// `shasum -c` / `sha256sum -c` from the directory holding the artifact.
    Coreutils,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default, JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct ChecksumConfig {
    /// Checksum filename template (default: "{{ ProjectName }}_{{ Version }}_checksums.txt").
    pub name_template: Option<String>,
    /// Hash algorithm (default: `sha256`). Accepted values: `sha1`, `sha224`,
    /// `sha256`, `sha384`, `sha512`, `sha3-224`, `sha3-256`, `sha3-384`,
    /// `sha3-512`, `blake2b`, `blake2s`, `blake3`, `crc32`, `md5`. An
    /// unrecognized value is rejected at checksum-stage entry. The authoritative
    /// set is [`ChecksumConfig::SUPPORTED_ALGORITHMS`].
    pub algorithm: Option<String>,
    /// Disable checksums. Accepts bool or template string.
    /// Accepts the legacy `disable:` spelling via serde alias for back-compat.
    #[serde(
        alias = "disable",
        deserialize_with = "deserialize_string_or_bool_opt",
        default
    )]
    pub skip: Option<StringOrBool>,
    /// Extra files to include in the checksum file (beyond build artifacts).
    pub extra_files: Option<Vec<ExtraFileSpec>>,
    /// Extra files whose contents are rendered through the template engine before inclusion.
    /// Unlike `extra_files` which copy as-is, template variables like `{{ Tag }}` are expanded.
    pub templated_extra_files: Option<Vec<TemplatedExtraFile>>,
    /// Build IDs filter: only checksum artifacts from builds whose `id` is in this list.
    pub ids: Option<Vec<String>>,
    /// When true, produce one checksum file per artifact instead of a combined file.
    pub split: Option<bool>,
    /// Sidecar content format when `split: true` (default: `bare`). Set to
    /// `coreutils` to write `<hash>  <filename>` so each sidecar verifies with
    /// `shasum -c`. Ignored in combined mode (the combined file is always
    /// coreutils-format).
    pub split_format: Option<ChecksumSplitFormat>,
}

impl ChecksumConfig {
    /// Default checksum filename template (combined mode). Mirrors
    /// the checksums config.
    pub const DEFAULT_NAME_TEMPLATE: &'static str = "{{ ProjectName }}_{{ Version }}_checksums.txt";

    /// Default hash algorithm (`sha256`).
    pub const DEFAULT_ALGORITHM: &'static str = "sha256";

    /// The closed set of accepted [`Self::algorithm`] values. This is the
    /// authoritative list the checksum stage's hash dispatch and
    /// `validate_algorithm` are kept in sync with (a `stage-checksum`
    /// drift-guard test asserts the two never diverge), so the config rustdoc
    /// can name the full set without hand-copying a list that rots.
    pub const SUPPORTED_ALGORITHMS: &'static [&'static str] = &[
        "sha1", "sha224", "sha256", "sha384", "sha512", "sha3-224", "sha3-256", "sha3-384",
        "sha3-512", "blake2b", "blake2s", "blake3", "crc32", "md5",
    ];

    /// Resolve the hash algorithm, falling back to the project default
    /// when the user did not specify one. Stages MUST call this rather
    /// than reading `self.algorithm` directly, so a future default change
    /// (or user-facing override resolution) lands in one place.
    pub fn resolved_algorithm(&self) -> &str {
        self.algorithm.as_deref().unwrap_or(Self::DEFAULT_ALGORITHM)
    }

    /// Whether split-mode (one sidecar per artifact) is requested.
    /// Defaults to `false` (combined-file mode).
    pub fn resolved_split(&self) -> bool {
        self.split.unwrap_or(false)
    }

    /// Resolve the combined-mode checksum filename template, falling back
    /// to the canonical default. Returns the raw template
    /// string; the caller still renders it through Tera.
    ///
    /// Split mode constructs sidecar names per-artifact at the call site
    /// (`<artifact>.<algo>` literal format) and intentionally does NOT
    /// route through this accessor — that path needs no template rendering.
    pub fn resolved_combined_name_template(&self) -> &str {
        self.name_template
            .as_deref()
            .unwrap_or(Self::DEFAULT_NAME_TEMPLATE)
    }

    /// Resolve the combined-checksums `name_template` for a crate, applying the
    /// canonical precedence — the crate's own `checksum.name_template`, then the
    /// global `defaults.checksum.name_template`, then [`Self::DEFAULT_NAME_TEMPLATE`].
    ///
    /// The single source of truth shared by the checksum stage (which writes the
    /// file) and the install-script stage (which references it in the generated
    /// `install.sh`), so the two can never derive different names.
    pub fn resolve_combined_name_template<'a>(
        crate_checksum: Option<&'a ChecksumConfig>,
        global_checksum: Option<&'a ChecksumConfig>,
    ) -> &'a str {
        crate_checksum
            .and_then(|c| c.name_template.as_deref())
            .or_else(|| global_checksum.and_then(|c| c.name_template.as_deref()))
            .unwrap_or(Self::DEFAULT_NAME_TEMPLATE)
    }
}

// ---------------------------------------------------------------------------
// ContentSource — inline string, from_file, or from_url
// ---------------------------------------------------------------------------

/// A content source that can be an inline string, read from a file, or fetched
/// from a URL. Used for release header/footer values.
///
/// YAML examples:
///   header: "inline text"
///   header:
///     from_file: ./RELEASE_HEADER.md
///   header:
///     from_url: https://example.com/header.md
///   header:
///     from_url: https://example.com/header.md
///     headers:
///       X-API-Token: "{{ Env.API_TOKEN }}"
///       Accept: "text/markdown"
///
/// Both `from_file` path and `from_url` URL are template-rendered before use.
/// Header values are template-rendered.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(untagged)]
pub enum ContentSource {
    Inline(String),
    FromFile {
        from_file: String,
    },
    FromUrl {
        from_url: String,
        /// Optional HTTP headers (value templates allowed). Enables private
        /// mirrors and authenticated endpoints.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        headers: Option<HashMap<String, String>>,
    },
}

impl PartialEq for ContentSource {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Inline(a), Self::Inline(b)) => a == b,
            (Self::FromFile { from_file: a }, Self::FromFile { from_file: b }) => a == b,
            (
                Self::FromUrl {
                    from_url: a,
                    headers: ha,
                },
                Self::FromUrl {
                    from_url: b,
                    headers: hb,
                },
            ) => a == b && ha == hb,
            _ => false,
        }
    }
}

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

    // The `archives`/`signs`/`binary_signs` fields use hand-written
    // deserializers (untagged shapes serde can't derive). Each visitor arm —
    // bool, sequence, single-map, null — is driven here through a wrapper
    // struct that mirrors the real field attributes.

    #[derive(Deserialize)]
    struct ArchivesWrapper {
        #[serde(default, deserialize_with = "deserialize_archives_config")]
        archives: ArchivesConfig,
    }

    #[test]
    fn archives_false_is_disabled() {
        let w: ArchivesWrapper = serde_yaml_ng::from_str("archives: false").unwrap();
        assert!(matches!(w.archives, ArchivesConfig::Disabled));
    }

    #[test]
    fn archives_true_is_rejected() {
        // `true` is meaningless for archives — only `false` (disable) or a list.
        let r: Result<ArchivesWrapper, _> = serde_yaml_ng::from_str("archives: true");
        assert!(r.is_err(), "archives: true must be rejected");
    }

    #[test]
    fn archives_list_becomes_configs() {
        let w: ArchivesWrapper =
            serde_yaml_ng::from_str("archives:\n  - id: a\n  - id: b\n").unwrap();
        match w.archives {
            ArchivesConfig::Configs(c) => assert_eq!(c.len(), 2),
            other => panic!("expected Configs, got {other:?}"),
        }
    }

    #[test]
    fn archives_null_defaults_to_empty_configs() {
        let w: ArchivesWrapper = serde_yaml_ng::from_str("archives: null").unwrap();
        match w.archives {
            ArchivesConfig::Configs(c) => assert!(c.is_empty()),
            other => panic!("expected empty Configs, got {other:?}"),
        }
    }

    #[derive(Deserialize)]
    struct SignsWrapper {
        #[serde(default, deserialize_with = "deserialize_signs")]
        signs: Vec<SignConfig>,
    }

    #[test]
    fn signs_single_object_becomes_one_element_vec() {
        // A single sign-config map (not wrapped in a list) is accepted.
        let w: SignsWrapper = serde_yaml_ng::from_str("signs:\n  artifacts: all\n").unwrap();
        assert_eq!(w.signs.len(), 1);
        assert_eq!(w.signs[0].artifacts.as_deref(), Some("all"));
    }

    #[test]
    fn signs_sequence_collects_all() {
        let w: SignsWrapper =
            serde_yaml_ng::from_str("signs:\n  - artifacts: all\n  - artifacts: checksum\n")
                .unwrap();
        assert_eq!(w.signs.len(), 2);
    }

    #[test]
    fn signs_null_is_empty_vec() {
        let w: SignsWrapper = serde_yaml_ng::from_str("signs: null").unwrap();
        assert!(w.signs.is_empty());
    }

    #[derive(Deserialize)]
    struct BinarySignsWrapper {
        #[serde(default, deserialize_with = "deserialize_binary_signs")]
        binary_signs: Vec<SignConfig>,
    }

    #[test]
    fn binary_signs_accepts_binary_and_none() {
        let w: BinarySignsWrapper =
            serde_yaml_ng::from_str("binary_signs:\n  - artifacts: binary\n").unwrap();
        assert_eq!(w.binary_signs.len(), 1);
        let w2: BinarySignsWrapper =
            serde_yaml_ng::from_str("binary_signs:\n  - artifacts: none\n").unwrap();
        assert_eq!(w2.binary_signs.len(), 1);
    }

    #[test]
    fn binary_signs_rejects_broad_artifact_filter() {
        // `all` is valid for top-level `signs:` but not the binary-only field.
        let r: Result<BinarySignsWrapper, _> =
            serde_yaml_ng::from_str("binary_signs:\n  - artifacts: all\n");
        assert!(
            r.is_err(),
            "binary_signs must reject a non-binary artifact filter"
        );
    }

    // --- WrapInDirectory ---------------------------------------------------

    #[test]
    fn wrap_in_directory_bool_true_uses_default_name() {
        assert_eq!(
            WrapInDirectory::Bool(true).directory_name("myapp_1.0"),
            Some("myapp_1.0".to_string())
        );
    }

    #[test]
    fn wrap_in_directory_bool_false_disables_wrapping() {
        assert_eq!(
            WrapInDirectory::Bool(false).directory_name("myapp_1.0"),
            None
        );
    }

    #[test]
    fn wrap_in_directory_empty_string_disables_wrapping() {
        // An empty custom name is treated as "no wrapping", not a dir named "".
        assert_eq!(
            WrapInDirectory::Name(String::new()).directory_name("fallback"),
            None
        );
    }

    #[test]
    fn wrap_in_directory_custom_name_overrides_default() {
        assert_eq!(
            WrapInDirectory::Name("custom".into()).directory_name("fallback"),
            Some("custom".to_string())
        );
    }

    #[derive(Deserialize)]
    struct WrapWrapper {
        wrap_in_directory: WrapInDirectory,
    }

    #[test]
    fn wrap_in_directory_deserializes_bool_and_string() {
        let b: WrapWrapper = serde_yaml_ng::from_str("wrap_in_directory: true").unwrap();
        assert_eq!(b.wrap_in_directory, WrapInDirectory::Bool(true));
        let s: WrapWrapper = serde_yaml_ng::from_str("wrap_in_directory: dist").unwrap();
        assert_eq!(s.wrap_in_directory, WrapInDirectory::Name("dist".into()));
    }

    #[test]
    fn wrap_in_directory_rejects_non_scalar() {
        // A list is neither a bool nor a string — the hand-written deserializer
        // must error rather than coerce.
        let r: Result<WrapWrapper, _> = serde_yaml_ng::from_str("wrap_in_directory:\n  - a\n");
        assert!(r.is_err());
    }

    // --- parse_octal_mode --------------------------------------------------

    #[test]
    fn parse_octal_mode_accepts_common_forms() {
        assert_eq!(parse_octal_mode("0755"), Some(0o755));
        assert_eq!(parse_octal_mode("0o755"), Some(0o755));
        assert_eq!(parse_octal_mode("0O755"), Some(0o755));
        assert_eq!(parse_octal_mode("755"), Some(0o755));
        // Bare "0o"/"0O" with nothing after → the cleaned string is empty and
        // is normalized to "0".
        assert_eq!(parse_octal_mode("0o"), Some(0));
        assert_eq!(parse_octal_mode("0"), Some(0));
    }

    #[test]
    fn parse_octal_mode_rejects_non_octal() {
        // 8 and 9 are not octal digits.
        assert_eq!(parse_octal_mode("0o899"), None);
        assert_eq!(parse_octal_mode("garbage"), None);
    }

    // --- ChecksumConfig::resolve_combined_name_template (static precedence) --

    #[test]
    fn resolve_combined_name_template_prefers_crate_then_global_then_default() {
        let crate_cfg = ChecksumConfig {
            name_template: Some("crate.txt".into()),
            ..Default::default()
        };
        let global_cfg = ChecksumConfig {
            name_template: Some("global.txt".into()),
            ..Default::default()
        };
        // Crate value wins over global and default.
        assert_eq!(
            ChecksumConfig::resolve_combined_name_template(Some(&crate_cfg), Some(&global_cfg)),
            "crate.txt"
        );
        // With no crate override, global wins.
        let bare = ChecksumConfig::default();
        assert_eq!(
            ChecksumConfig::resolve_combined_name_template(Some(&bare), Some(&global_cfg)),
            "global.txt"
        );
        // Neither set → the canonical default.
        assert_eq!(
            ChecksumConfig::resolve_combined_name_template(None, None),
            ChecksumConfig::DEFAULT_NAME_TEMPLATE
        );
    }

    // --- ChecksumSplitFormat ----------------------------------------------

    #[test]
    fn checksum_split_format_defaults_to_bare() {
        assert_eq!(ChecksumSplitFormat::default(), ChecksumSplitFormat::Bare);
    }

    #[test]
    fn checksum_split_format_deserializes_lowercase() {
        assert_eq!(
            serde_yaml_ng::from_str::<ChecksumSplitFormat>("bare").unwrap(),
            ChecksumSplitFormat::Bare
        );
        assert_eq!(
            serde_yaml_ng::from_str::<ChecksumSplitFormat>("coreutils").unwrap(),
            ChecksumSplitFormat::Coreutils
        );
        assert!(serde_yaml_ng::from_str::<ChecksumSplitFormat>("Coreutils").is_err());
    }

    // --- ExtraFileSpec::allow_empty ---------------------------------------

    #[test]
    fn extra_file_spec_allow_empty_only_true_for_detailed_opt_in() {
        // Bare glob form is always fail-fast (allow_empty == false).
        let bare: ExtraFileSpec = serde_yaml_ng::from_str("dist/*.sig").unwrap();
        assert!(!bare.allow_empty());
        // Detailed with allow_empty: true opts in.
        let opt_in: ExtraFileSpec =
            serde_yaml_ng::from_str("glob: keys/*.pub\nallow_empty: true").unwrap();
        assert!(opt_in.allow_empty());
        assert_eq!(opt_in.glob(), "keys/*.pub");
        // Detailed defaulting allow_empty stays false.
        let default_off: ExtraFileSpec = serde_yaml_ng::from_str("glob: docs/*.pdf").unwrap();
        assert!(!default_off.allow_empty());
    }

    // --- ArchiveFileSpec PartialEq<&str> ----------------------------------

    #[test]
    fn archive_file_spec_str_eq_matches_glob_only() {
        assert!(ArchiveFileSpec::Glob("README.md".into()) == "README.md");
        assert!(ArchiveFileSpec::Glob("README.md".into()) != "other");
        // The Detailed variant never equals a bare string.
        let detailed = ArchiveFileSpec::Detailed {
            src: "README.md".into(),
            dst: None,
            info: None,
            strip_parent: None,
        };
        assert!(detailed != "README.md");
    }

    // --- ArchiveConfig deprecation folds ----------------------------------

    #[test]
    fn archive_config_folds_singular_format_into_formats() {
        // The deprecated `format: tar.gz` singular folds into `formats`.
        let c: ArchiveConfig = serde_yaml_ng::from_str("format: tar.gz").unwrap();
        assert_eq!(c.formats.as_deref().unwrap(), ["tar.gz"]);
    }

    #[test]
    fn archive_config_folds_deprecated_builds_into_ids() {
        let c: ArchiveConfig = serde_yaml_ng::from_str("ids: [keep]\nbuilds: [legacy]").unwrap();
        let ids = c.ids.unwrap();
        assert!(ids.contains(&"keep".to_string()));
        assert!(ids.contains(&"legacy".to_string()));
    }

    #[test]
    fn archive_config_defaults_id_to_default() {
        // A parse->serialise round-trip must be stable, so `id` materializes
        // to "default" when omitted.
        let c: ArchiveConfig = serde_yaml_ng::from_str("name_template: x").unwrap();
        assert_eq!(c.id.as_deref(), Some("default"));
        // An explicit id is preserved verbatim.
        let named: ArchiveConfig = serde_yaml_ng::from_str("id: bins").unwrap();
        assert_eq!(named.id.as_deref(), Some("bins"));
    }

    #[test]
    fn format_override_folds_singular_format() {
        let o: FormatOverride = serde_yaml_ng::from_str("os: windows\nformat: zip").unwrap();
        assert_eq!(o.os, "windows");
        assert_eq!(o.formats.as_deref().unwrap(), ["zip"]);
    }

    // --- ContentSource PartialEq ------------------------------------------

    #[test]
    fn content_source_partial_eq_by_variant_and_payload() {
        assert_eq!(
            ContentSource::Inline("a".into()),
            ContentSource::Inline("a".into())
        );
        assert_ne!(
            ContentSource::Inline("a".into()),
            ContentSource::Inline("b".into())
        );
        // Same string but different variant must not compare equal.
        assert_ne!(
            ContentSource::Inline("a".into()),
            ContentSource::FromFile {
                from_file: "a".into()
            }
        );
        // FromUrl equality includes the headers map.
        let mut h = HashMap::new();
        h.insert("Accept".to_string(), "text/plain".to_string());
        let with_headers = ContentSource::FromUrl {
            from_url: "u".into(),
            headers: Some(h.clone()),
        };
        assert_eq!(
            with_headers,
            ContentSource::FromUrl {
                from_url: "u".into(),
                headers: Some(h),
            }
        );
        assert_ne!(
            with_headers,
            ContentSource::FromUrl {
                from_url: "u".into(),
                headers: None,
            }
        );
    }

    #[test]
    fn content_source_from_url_deserializes_headers() {
        let cs: ContentSource = serde_yaml_ng::from_str(
            "from_url: https://example.com/h.md\nheaders:\n  X-Token: abc\n",
        )
        .unwrap();
        match cs {
            ContentSource::FromUrl { from_url, headers } => {
                assert_eq!(from_url, "https://example.com/h.md");
                assert_eq!(headers.unwrap().get("X-Token").unwrap(), "abc");
            }
            other => panic!("expected FromUrl, got {other:?}"),
        }
    }

    // --- TemplatedExtraFile -----------------------------------------------

    #[test]
    fn templated_extra_file_parses_and_defaults() {
        let full: TemplatedExtraFile = serde_yaml_ng::from_str(
            "src: NOTES.tera\ndst: \"{{ ProjectName }}-NOTES.txt\"\nmode: \"0644\"",
        )
        .unwrap();
        assert_eq!(full.src, "NOTES.tera");
        assert_eq!(full.dst.as_deref(), Some("{{ ProjectName }}-NOTES.txt"));
        assert_eq!(full.mode.as_deref(), Some("0644"));
        // Only `src` is required; dst/mode default to None.
        let minimal: TemplatedExtraFile = serde_yaml_ng::from_str("src: NOTES.tera").unwrap();
        assert!(minimal.dst.is_none());
        assert!(minimal.mode.is_none());
        // Unknown fields are rejected.
        assert!(serde_yaml_ng::from_str::<TemplatedExtraFile>("src: x\nbogus: y").is_err());
    }
}