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
use crate::VergenKey;

use anyhow::{Error, Result};
use getset::Getters;
use std::collections::BTreeMap;

/// The map used to emit `cargo:rustc-env=NAME=VALUE` cargo instructions
pub type CargoRustcEnvMap = BTreeMap<VergenKey, String>;
/// The vector of strings used to emit `cargo:rerun-if-changed=VALUE` cargo instructions
pub type CargoRerunIfChanged = Vec<String>;
/// The vector of strings used to emit `cargo:warning=VALUE` cargo instructions
pub type CargoWarning = Vec<String>;

/// The default configuration to use when an issue has occured generating instructions
#[derive(Debug, Getters)]
#[getset(get = "pub")]
pub struct DefaultConfig {
    /// Should we fail if an error occurs or output idempotent values on error?
    fail_on_error: bool,
    /// The error that caused us to try default instruction output.
    error: Error,
}

impl DefaultConfig {
    /// Create a new [`DefaultConfig`] struct with the given values.
    #[must_use]
    pub fn new(fail_on_error: bool, error: Error) -> Self {
        Self {
            fail_on_error,
            error,
        }
    }
}

/// This trait should be implemented to allow the `vergen` emitter
/// to properly emit instructions for your feature.
pub trait Add {
    /// Try to add instructions entries to the various given arguments.
    ///
    /// * Write to the `cargo_rustc_env` map to emit 'cargo:rustc-env=NAME=VALUE' instructions.
    /// * Write to the `cargo_rerun_if_changed` vector to emit 'cargo:rerun-if-changed=VALUE' instructions.
    /// * Write to the `cargo_warning` vector to emit 'cargo:warning=VALUE' instructions.
    ///
    /// # Errors
    ///
    /// If an error occurs, the `vergen` emitter will use `add_default_entries` to generate output.
    /// This assumes generating instructions may fail in some manner so a [`anyhow::Result`] is returned.
    ///
    fn add_map_entries(
        &self,
        idempotent: bool,
        cargo_rustc_env: &mut CargoRustcEnvMap,
        cargo_rerun_if_changed: &mut CargoRerunIfChanged,
        cargo_warning: &mut CargoWarning,
    ) -> Result<()>;

    /// Based on the given configuration, emit either default idempotent output or generate a failue.
    ///
    /// * Write to the `cargo_rustc_env` map to emit 'cargo:rustc-env=NAME=VALUE' instructions.
    /// * Write to the `cargo_rerun_if_changed` vector to emit 'cargo:rerun-if-changed=VALUE' instructions.
    /// * Write to the `cargo_warning` vector to emit 'cargo:warning=VALUE' instructions.
    ///
    /// # Errors
    ///
    /// This assumes generating instructions may fail in some manner so a [`anyhow::Result`] is returned.
    ///
    fn add_default_entries(
        &self,
        config: &DefaultConfig,
        cargo_rustc_env_map: &mut CargoRustcEnvMap,
        cargo_rerun_if_changed: &mut CargoRerunIfChanged,
        cargo_warning: &mut CargoWarning,
    ) -> Result<()>;
}

/// This trait should be implemented to allow the `vergen` emitter to properly emit your custom instructions.
pub trait AddCustom<K: Into<String> + Ord, V: Into<String>> {
    /// Try to add instructions entries to the various given arguments.
    ///
    /// * Write to the `cargo_rustc_env` map to emit 'cargo:rustc-env=NAME=VALUE' instructions.
    /// * Write to the `cargo_rerun_if_changed` vector to emit 'cargo:rerun-if-changed=VALUE' instructions.
    /// * Write to the `cargo_warning` vector to emit 'cargo:warning=VALUE' instructions.
    ///
    /// # Errors
    ///
    /// If an error occurs, the `vergen` emitter will use `add_default_entries` to generate output.
    /// This assumes generating instructions may fail in some manner so a [`anyhow::Result`] is returned.
    ///
    fn add_calculated_entries(
        &self,
        idempotent: bool,
        cargo_rustc_env_map: &mut BTreeMap<K, V>,
        cargo_rerun_if_changed: &mut CargoRerunIfChanged,
        cargo_warning: &mut CargoWarning,
    ) -> Result<()>;

    /// Based on the given configuration, emit either default idempotent output or generate a failue.
    ///
    /// * Write to the `cargo_rustc_env` map to emit 'cargo:rustc-env=NAME=VALUE' instructions.
    /// * Write to the `cargo_rerun_if_changed` vector to emit 'cargo:rerun-if-changed=VALUE' instructions.
    /// * Write to the `cargo_warning` vector to emit 'cargo:warning=VALUE' instructions.
    ///
    /// # Errors
    ///
    /// This assumes generating instructions may fail in some manner so a [`anyhow::Result`] is returned.
    ///
    fn add_default_entries(
        &self,
        config: &DefaultConfig,
        cargo_rustc_env_map: &mut BTreeMap<K, V>,
        cargo_rerun_if_changed: &mut CargoRerunIfChanged,
        cargo_warning: &mut CargoWarning,
    ) -> Result<()>;
}

#[doc(hidden)]
pub(crate) mod test_gen {
    use crate::{AddCustomEntries, CargoRerunIfChanged, CargoWarning};
    use anyhow::{anyhow, Result};
    use derive_builder::Builder;
    use std::collections::BTreeMap;

    #[doc(hidden)]
    #[derive(Builder, Clone, Copy, Debug, Default)]
    pub struct CustomInsGen {
        fail: bool,
    }

    impl AddCustomEntries<&str, &str> for CustomInsGen {
        fn add_calculated_entries(
            &self,
            idempotent: bool,
            cargo_rustc_env_map: &mut BTreeMap<&str, &str>,
            _cargo_rerun_if_changed: &mut CargoRerunIfChanged,
            _cargo_warning: &mut CargoWarning,
        ) -> Result<()> {
            if self.fail {
                Err(anyhow!("We have failed"))
            } else {
                if idempotent {
                    let _ = cargo_rustc_env_map.insert("test", "VERGEN_IDEMPOTENT_OUTPUT");
                } else {
                    let _ = cargo_rustc_env_map.insert("test", "value");
                }
                Ok(())
            }
        }

        fn add_default_entries(
            &self,
            config: &crate::DefaultConfig,
            cargo_rustc_env_map: &mut BTreeMap<&str, &str>,
            _cargo_rerun_if_changed: &mut CargoRerunIfChanged,
            _cargo_warning: &mut CargoWarning,
        ) -> Result<()> {
            if *config.fail_on_error() {
                let error = anyhow!(format!("{}", config.error()));
                Err(error)
            } else {
                let _ = cargo_rustc_env_map.insert("test", "VERGEN_IDEMPOTENT_OUTPUT");
                Ok(())
            }
        }
    }
}

#[cfg(test)]
mod test {
    use super::DefaultConfig;
    use anyhow::{anyhow, Result};
    use std::io::Write;

    #[test]
    fn default_config_debug() -> Result<()> {
        let config = DefaultConfig::new(true, anyhow!("blah"));
        let mut buf = vec![];
        write!(buf, "{config:?}")?;
        assert!(!buf.is_empty());
        Ok(())
    }
}