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    /// [`usize`].
74    Usize,
75}
76
77impl Display for ConstType {
78    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
79        match self {
80            ConstType::Str => write!(f, "&str"),
81            ConstType::Bool => write!(f, "bool"),
82            ConstType::Slice => write!(f, "&[u8]"),
83            ConstType::Usize => write!(f, "usize"),
84        }
85    }
86}
87
88/// The BuildPattern enum defines strategies for triggering package rebuilding.
89///
90/// Default mode is `Lazy`.
91///
92/// * `Lazy`: The lazy mode. In this mode, if the current Rust environment is set to `debug`,
93///   the rebuild package will not run every time the build script is triggered.
94///   If the environment is set to `release`, it behaves the same as the `RealTime` mode.
95/// * `RealTime`: The real-time mode. It will always trigger rebuilding a package upon any change,
96///   regardless of whether the Rust environment is set to `debug` or `release`.
97/// * `Custom`: The custom build mode, an enhanced version of `RealTime` mode, allowing for user-defined conditions
98///   to trigger rebuilding a package.
99///
100#[derive(Debug, Default, Clone)]
101pub enum BuildPattern {
102    #[default]
103    Lazy,
104    RealTime,
105    Custom {
106        /// A list of paths that, if changed, will trigger a rebuild.
107        /// See <https://doc.rust-lang.org/cargo/reference/build-scripts.html#rerun-if-changed>
108        if_path_changed: Vec<String>,
109        /// A list of environment variables that, if changed, will trigger a rebuild.
110        /// See <https://doc.rust-lang.org/cargo/reference/build-scripts.html#rerun-if-env-changed>
111        if_env_changed: Vec<String>,
112    },
113}
114
115impl BuildPattern {
116    /// Determines when Cargo should rerun the build script based on the configured pattern.
117    ///
118    /// # Arguments
119    ///
120    /// * `other_keys` - An iterator over additional keys that should trigger a rebuild if they change.
121    /// * `out_dir` - The output directory where generated files are placed.
122    pub(crate) fn rerun_if<'a>(
123        &self,
124        other_keys: impl Iterator<Item = &'a ShadowConst>,
125        out_dir: &str,
126    ) {
127        match self {
128            BuildPattern::Lazy => {
129                if is_debug() {
130                    return;
131                }
132            }
133            BuildPattern::RealTime => {}
134            BuildPattern::Custom {
135                if_path_changed,
136                if_env_changed,
137            } => {
138                if_env_changed
139                    .iter()
140                    .for_each(|key| println!("cargo:rerun-if-env-changed={key}"));
141                if_path_changed
142                    .iter()
143                    .for_each(|p| println!("cargo:rerun-if-changed={p}"));
144            }
145        }
146
147        other_keys.for_each(|key| println!("cargo:rerun-if-env-changed={key}"));
148        println!("cargo:rerun-if-env-changed={}", DEFINE_SOURCE_DATE_EPOCH);
149        println!("cargo:rerun-if-changed={}/{}", out_dir, DEFINE_SHADOW_RS);
150    }
151}
152
153/// A builder pattern structure to construct a `Shadow` instance.
154///
155/// This struct allows for configuring various aspects of how shadow-rs will be built into your Rust project.
156/// It provides methods to set up hooks, specify build patterns, define paths, and deny certain build constants.
157///
158/// # Fields
159///
160/// * `hook`: An optional hook that can be used during the build process. Hooks implement the `HookExt` trait.
161/// * `build_pattern`: Determines the strategy for triggering package rebuilds (`Lazy`, `RealTime`, or `Custom`).
162/// * `deny_const`: A set of build constant identifiers that should not be included in the build.
163/// * `src_path`: The source path from which files are read for building.
164/// * `out_path`: The output path where generated files will be placed.
165///
166pub struct ShadowBuilder<'a> {
167    hook: Option<Box<dyn HookExt + 'a>>,
168    build_pattern: BuildPattern,
169    deny_const: BTreeSet<ShadowConst>,
170    src_path: Option<String>,
171    out_path: Option<String>,
172}
173
174impl<'a> ShadowBuilder<'a> {
175    /// Creates a new `ShadowBuilder` with default settings.
176    ///
177    /// Initializes the builder with the following defaults:
178    /// - `hook`: None
179    /// - `build_pattern`: `BuildPattern::Lazy`
180    /// - `deny_const`: Uses the result from `default_deny()`
181    /// - `src_path`: Attempts to get the manifest directory using `CARGO_MANIFEST_DIR` environment variable.
182    /// - `out_path`: Attempts to get the output directory using `OUT_DIR` environment variable.
183    ///
184    /// # Returns
185    ///
186    /// A new instance of `ShadowBuilder`.
187    pub fn builder() -> Self {
188        let default_src_path = std::env::var("CARGO_MANIFEST_DIR").ok();
189        let default_out_path = std::env::var("OUT_DIR").ok();
190        Self {
191            hook: None,
192            build_pattern: BuildPattern::default(),
193            deny_const: default_deny(),
194            src_path: default_src_path,
195            out_path: default_out_path,
196        }
197    }
198
199    /// Sets the build hook for this builder.
200    ///
201    /// # Arguments
202    ///
203    /// * `hook` - An object implementing the `HookExt` trait that defines custom behavior for the build process.
204    ///
205    /// # Returns
206    ///
207    /// A new `ShadowBuilder` instance with the specified hook applied.
208    pub fn hook(mut self, hook: impl HookExt + 'a) -> Self {
209        self.hook = Some(Box::new(hook));
210        self
211    }
212
213    /// Sets the source path for this builder.
214    ///
215    /// # Arguments
216    ///
217    /// * `src_path` - A string reference that specifies the source directory for the build.
218    ///
219    /// # Returns
220    ///
221    /// A new `ShadowBuilder` instance with the specified source path.
222    pub fn src_path<P: AsRef<str>>(mut self, src_path: P) -> Self {
223        self.src_path = Some(src_path.as_ref().to_owned());
224        self
225    }
226
227    /// Sets the output path for this builder.
228    ///
229    /// # Arguments
230    ///
231    /// * `out_path` - A string reference that specifies the output directory for the build.
232    ///
233    /// # Returns
234    ///
235    /// A new `ShadowBuilder` instance with the specified output path.
236    pub fn out_path<P: AsRef<str>>(mut self, out_path: P) -> Self {
237        self.out_path = Some(out_path.as_ref().to_owned());
238        self
239    }
240
241    /// Sets the build pattern for this builder.
242    ///
243    /// # Arguments
244    ///
245    /// * `pattern` - A `BuildPattern` that determines when the package should be rebuilt.
246    ///
247    /// # Returns
248    ///
249    /// A new `ShadowBuilder` instance with the specified build pattern.
250    pub fn build_pattern(mut self, pattern: BuildPattern) -> Self {
251        self.build_pattern = pattern;
252        self
253    }
254
255    /// Sets the denied constants for this builder.
256    ///
257    /// # Arguments
258    ///
259    /// * `deny_const` - A set of `ShadowConst` that should be excluded from the build.
260    ///
261    /// # Returns
262    ///
263    /// A new `ShadowBuilder` instance with the specified denied constants.
264    pub fn deny_const(mut self, deny_const: BTreeSet<ShadowConst>) -> Self {
265        self.deny_const = deny_const;
266        self
267    }
268
269    /// Builds a `Shadow` instance based on the current configuration.
270    ///
271    /// # Returns
272    ///
273    /// A `SdResult<Shadow>` that represents the outcome of the build operation.
274    pub fn build(self) -> SdResult<Shadow> {
275        Shadow::build_inner(self)
276    }
277
278    /// Gets the source path if it has been set.
279    ///
280    /// # Returns
281    ///
282    /// A `SdResult<&String>` containing the source path or an error if the path is missing.
283    pub fn get_src_path(&self) -> SdResult<&String> {
284        let src_path = self.src_path.as_ref().ok_or("missing `src_path`")?;
285        Ok(src_path)
286    }
287
288    /// Gets the output path if it has been set.
289    ///
290    /// # Returns
291    ///
292    /// A `SdResult<&String>` containing the output path or an error if the path is missing.
293    pub fn get_out_path(&self) -> SdResult<&String> {
294        let out_path = self.out_path.as_ref().ok_or("missing `out_path`")?;
295        Ok(out_path)
296    }
297
298    /// Gets the build pattern.
299    ///
300    /// # Returns
301    ///
302    /// A reference to the `BuildPattern` currently configured for this builder.
303    pub fn get_build_pattern(&self) -> &BuildPattern {
304        &self.build_pattern
305    }
306
307    /// Gets the denied constants.
308    ///
309    /// # Returns
310    ///
311    /// A reference to the set of `ShadowConst` that are denied for this build.
312    pub fn get_deny_const(&self) -> &BTreeSet<ShadowConst> {
313        &self.deny_const
314    }
315
316    /// Gets the build hook if it has been set.
317    ///
318    /// # Returns
319    ///
320    /// An option containing a reference to the hook if one is present.
321    pub fn get_hook(&'a self) -> Option<&'a (dyn HookExt + 'a)> {
322        self.hook.as_deref()
323    }
324}