shadow_rs/
build.rs

1use crate::date_time::DEFINE_SOURCE_DATE_EPOCH;
2use crate::hook::HookExt;
3use crate::shadow::DEFINE_SHADOW_RS;
4use crate::{SdResult, Shadow, CARGO_METADATA};
5use is_debug::is_debug;
6use std::collections::BTreeSet;
7use std::fmt::{Display, Formatter};
8
9/// `shadow-rs` build constant identifiers.
10pub type ShadowConst = &'static str;
11
12/// Since [cargo metadata](https://crates.io/crates/cargo_metadata) details about workspace
13/// membership and resolved dependencies for the current package, storing this data can result in
14/// significantly larger crate sizes. As such, the CARGO_METADATA const is disabled by default.
15///
16/// Should you choose to retain this information, you have the option to customize a deny_const
17/// object and override the `new_deny` method parameters accordingly.
18///
19#[allow(clippy::all, clippy::pedantic, clippy::restriction, clippy::nursery)]
20pub fn default_deny() -> BTreeSet<ShadowConst> {
21    BTreeSet::from([CARGO_METADATA])
22}
23
24/// Serialized values for build constants.
25#[derive(Debug, Clone)]
26pub struct ConstVal {
27    /// User-facing documentation for the build constant.
28    pub desc: String,
29    /// Serialized value of the build constant.
30    pub v: String,
31    /// Type of the build constant.
32    pub t: ConstType,
33}
34
35impl ConstVal {
36    pub fn new<S: Into<String>>(desc: S) -> ConstVal {
37        // Creates a new `ConstVal` with an empty string as its value and `Str` as its type.
38        ConstVal {
39            desc: desc.into(),
40            v: "".to_string(),
41            t: ConstType::Str,
42        }
43    }
44
45    pub fn new_bool<S: Into<String>>(desc: S) -> ConstVal {
46        // Creates a new `ConstVal` with "true" as its value and `Bool` as its type.
47        ConstVal {
48            desc: desc.into(),
49            v: "true".to_string(),
50            t: ConstType::Bool,
51        }
52    }
53
54    pub fn new_slice<S: Into<String>>(desc: S) -> ConstVal {
55        // Creates a new `ConstVal` with an empty string as its value and `Slice` as its type.
56        ConstVal {
57            desc: desc.into(),
58            v: "".to_string(),
59            t: ConstType::Slice,
60        }
61    }
62}
63
64/// Supported types of build constants.
65#[derive(Debug, Clone)]
66pub enum ConstType {
67    /// [`&str`](`str`).
68    Str,
69    /// [`bool`].
70    Bool,
71    /// [`&[u8]`].
72    Slice,
73}
74
75impl Display for ConstType {
76    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
77        match self {
78            ConstType::Str => write!(f, "&str"),
79            ConstType::Bool => write!(f, "bool"),
80            ConstType::Slice => write!(f, "&[u8]"),
81        }
82    }
83}
84
85/// The BuildPattern enum defines strategies for triggering package rebuilding.
86///
87/// Default mode is `Lazy`.
88///
89/// * `Lazy`: The lazy mode. In this mode, if the current Rust environment is set to `debug`,
90///   the rebuild package will not run every time the build script is triggered.
91///   If the environment is set to `release`, it behaves the same as the `RealTime` mode.
92/// * `RealTime`: The real-time mode. It will always trigger rebuilding a package upon any change,
93///   regardless of whether the Rust environment is set to `debug` or `release`.
94/// * `Custom`: The custom build mode, an enhanced version of `RealTime` mode, allowing for user-defined conditions
95///   to trigger rebuilding a package.
96///
97#[derive(Debug, Default, Clone)]
98pub enum BuildPattern {
99    #[default]
100    Lazy,
101    RealTime,
102    Custom {
103        /// A list of paths that, if changed, will trigger a rebuild.
104        /// See <https://doc.rust-lang.org/cargo/reference/build-scripts.html#rerun-if-changed>
105        if_path_changed: Vec<String>,
106        /// A list of environment variables that, if changed, will trigger a rebuild.
107        /// See <https://doc.rust-lang.org/cargo/reference/build-scripts.html#rerun-if-env-changed>
108        if_env_changed: Vec<String>,
109    },
110}
111
112impl BuildPattern {
113    /// Determines when Cargo should rerun the build script based on the configured pattern.
114    ///
115    /// # Arguments
116    ///
117    /// * `other_keys` - An iterator over additional keys that should trigger a rebuild if they change.
118    /// * `out_dir` - The output directory where generated files are placed.
119    pub(crate) fn rerun_if<'a>(
120        &self,
121        other_keys: impl Iterator<Item = &'a ShadowConst>,
122        out_dir: &str,
123    ) {
124        match self {
125            BuildPattern::Lazy => {
126                if is_debug() {
127                    return;
128                }
129            }
130            BuildPattern::RealTime => {}
131            BuildPattern::Custom {
132                if_path_changed,
133                if_env_changed,
134            } => {
135                if_env_changed
136                    .iter()
137                    .for_each(|key| println!("cargo:rerun-if-env-changed={key}"));
138                if_path_changed
139                    .iter()
140                    .for_each(|p| println!("cargo:rerun-if-changed={p}"));
141            }
142        }
143
144        other_keys.for_each(|key| println!("cargo:rerun-if-env-changed={key}"));
145        println!("cargo:rerun-if-env-changed={}", DEFINE_SOURCE_DATE_EPOCH);
146        println!("cargo:rerun-if-changed={}/{}", out_dir, DEFINE_SHADOW_RS);
147    }
148}
149
150/// A builder pattern structure to construct a `Shadow` instance.
151///
152/// This struct allows for configuring various aspects of how shadow-rs will be built into your Rust project.
153/// It provides methods to set up hooks, specify build patterns, define paths, and deny certain build constants.
154///
155/// # Fields
156///
157/// * `hook`: An optional hook that can be used during the build process. Hooks implement the `HookExt` trait.
158/// * `build_pattern`: Determines the strategy for triggering package rebuilds (`Lazy`, `RealTime`, or `Custom`).
159/// * `deny_const`: A set of build constant identifiers that should not be included in the build.
160/// * `src_path`: The source path from which files are read for building.
161/// * `out_path`: The output path where generated files will be placed.
162///
163pub struct ShadowBuilder<'a> {
164    hook: Option<Box<dyn HookExt + 'a>>,
165    build_pattern: BuildPattern,
166    deny_const: BTreeSet<ShadowConst>,
167    src_path: Option<String>,
168    out_path: Option<String>,
169}
170
171impl<'a> ShadowBuilder<'a> {
172    /// Creates a new `ShadowBuilder` with default settings.
173    ///
174    /// Initializes the builder with the following defaults:
175    /// - `hook`: None
176    /// - `build_pattern`: `BuildPattern::Lazy`
177    /// - `deny_const`: Uses the result from `default_deny()`
178    /// - `src_path`: Attempts to get the manifest directory using `CARGO_MANIFEST_DIR` environment variable.
179    /// - `out_path`: Attempts to get the output directory using `OUT_DIR` environment variable.
180    ///
181    /// # Returns
182    ///
183    /// A new instance of `ShadowBuilder`.
184    pub fn builder() -> Self {
185        let default_src_path = std::env::var("CARGO_MANIFEST_DIR").ok();
186        let default_out_path = std::env::var("OUT_DIR").ok();
187        Self {
188            hook: None,
189            build_pattern: BuildPattern::default(),
190            deny_const: default_deny(),
191            src_path: default_src_path,
192            out_path: default_out_path,
193        }
194    }
195
196    /// Sets the build hook for this builder.
197    ///
198    /// # Arguments
199    ///
200    /// * `hook` - An object implementing the `HookExt` trait that defines custom behavior for the build process.
201    ///
202    /// # Returns
203    ///
204    /// A new `ShadowBuilder` instance with the specified hook applied.
205    pub fn hook(mut self, hook: impl HookExt + 'a) -> Self {
206        self.hook = Some(Box::new(hook));
207        self
208    }
209
210    /// Sets the source path for this builder.
211    ///
212    /// # Arguments
213    ///
214    /// * `src_path` - A string reference that specifies the source directory for the build.
215    ///
216    /// # Returns
217    ///
218    /// A new `ShadowBuilder` instance with the specified source path.
219    pub fn src_path<P: AsRef<str>>(mut self, src_path: P) -> Self {
220        self.src_path = Some(src_path.as_ref().to_owned());
221        self
222    }
223
224    /// Sets the output path for this builder.
225    ///
226    /// # Arguments
227    ///
228    /// * `out_path` - A string reference that specifies the output directory for the build.
229    ///
230    /// # Returns
231    ///
232    /// A new `ShadowBuilder` instance with the specified output path.
233    pub fn out_path<P: AsRef<str>>(mut self, out_path: P) -> Self {
234        self.out_path = Some(out_path.as_ref().to_owned());
235        self
236    }
237
238    /// Sets the build pattern for this builder.
239    ///
240    /// # Arguments
241    ///
242    /// * `pattern` - A `BuildPattern` that determines when the package should be rebuilt.
243    ///
244    /// # Returns
245    ///
246    /// A new `ShadowBuilder` instance with the specified build pattern.
247    pub fn build_pattern(mut self, pattern: BuildPattern) -> Self {
248        self.build_pattern = pattern;
249        self
250    }
251
252    /// Sets the denied constants for this builder.
253    ///
254    /// # Arguments
255    ///
256    /// * `deny_const` - A set of `ShadowConst` that should be excluded from the build.
257    ///
258    /// # Returns
259    ///
260    /// A new `ShadowBuilder` instance with the specified denied constants.
261    pub fn deny_const(mut self, deny_const: BTreeSet<ShadowConst>) -> Self {
262        self.deny_const = deny_const;
263        self
264    }
265
266    /// Builds a `Shadow` instance based on the current configuration.
267    ///
268    /// # Returns
269    ///
270    /// A `SdResult<Shadow>` that represents the outcome of the build operation.
271    pub fn build(self) -> SdResult<Shadow> {
272        Shadow::build_inner(self)
273    }
274
275    /// Gets the source path if it has been set.
276    ///
277    /// # Returns
278    ///
279    /// A `SdResult<&String>` containing the source path or an error if the path is missing.
280    pub fn get_src_path(&self) -> SdResult<&String> {
281        let src_path = self.src_path.as_ref().ok_or("missing `src_path`")?;
282        Ok(src_path)
283    }
284
285    /// Gets the output path if it has been set.
286    ///
287    /// # Returns
288    ///
289    /// A `SdResult<&String>` containing the output path or an error if the path is missing.
290    pub fn get_out_path(&self) -> SdResult<&String> {
291        let out_path = self.out_path.as_ref().ok_or("missing `out_path`")?;
292        Ok(out_path)
293    }
294
295    /// Gets the build pattern.
296    ///
297    /// # Returns
298    ///
299    /// A reference to the `BuildPattern` currently configured for this builder.
300    pub fn get_build_pattern(&self) -> &BuildPattern {
301        &self.build_pattern
302    }
303
304    /// Gets the denied constants.
305    ///
306    /// # Returns
307    ///
308    /// A reference to the set of `ShadowConst` that are denied for this build.
309    pub fn get_deny_const(&self) -> &BTreeSet<ShadowConst> {
310        &self.deny_const
311    }
312
313    /// Gets the build hook if it has been set.
314    ///
315    /// # Returns
316    ///
317    /// An option containing a reference to the hook if one is present.
318    pub fn get_hook(&'a self) -> Option<&'a (dyn HookExt + 'a)> {
319        self.hook.as_deref()
320    }
321}