shadow-rs 1.7.1

A build-time information stored in your rust project
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
use crate::build::{ConstType, ConstVal};
use crate::ci::CiType;
use crate::date_time::now_date_time;
use crate::env::{new_project, new_system_env};
use crate::gen_const::{
    clap_long_version_branch_const, clap_long_version_tag_const, version_branch_const,
    version_tag_const, BUILD_CONST_CLAP_LONG_VERSION, BUILD_CONST_VERSION,
};
use crate::git::new_git;
use crate::{
    get_std_env, BuildPattern, SdResult, ShadowBuilder, ShadowConst, CARGO_CLIPPY_ALLOW_ALL, TAG,
};
use std::collections::{BTreeMap, BTreeSet};
use std::fs::File;
use std::io::Write;
use std::path::Path;

pub(crate) const DEFINE_SHADOW_RS: &str = "shadow.rs";

/// `shadow-rs` configuration.
///
/// This struct encapsulates the configuration for the `shadow-rs` build process. It allows for fine-grained control over
/// various aspects of the build, including file output, build constants, environment variables, deny lists, and build patterns.
///
/// While it is possible to construct a [`Shadow`] instance manually, it is highly recommended to use the [`ShadowBuilder`] builder pattern structure
/// provided by `shadow-rs`. The builder pattern simplifies the setup process and ensures that all necessary configurations are properly set up,
/// allowing you to customize multiple aspects simultaneously, such as using a denylist and a hook function at the same time.
///
/// # Fields
///
/// * `f`: The file that `shadow-rs` writes build information to. This file will contain serialized build constants and other metadata.
/// * `map`: A map of build constant identifiers to their corresponding `ConstVal`. These are the values that will be written into the file.
/// * `std_env`: A map of environment variables obtained through [`std::env::vars`]. These variables can influence the build process.
/// * `deny_const`: A set of build constant identifiers that should be excluded from the build process. This can be populated via [`ShadowBuilder::deny_const`].
/// * `out_path`: The path where the generated files will be placed. This is usually derived from the `OUT_DIR` environment variable but can be customized via [`ShadowBuilder::out_path`].
/// * `build_pattern`: Determines the strategy for triggering package rebuilds (`Lazy`, `RealTime`, or `Custom`). This affects when Cargo will rerun the build script and can be configured via [`ShadowBuilder::build_pattern`].
///
/// # Example
///
/// ```no_run
/// use std::collections::BTreeSet;
/// use shadow_rs::{ShadowBuilder, BuildPattern, CARGO_TREE, CARGO_METADATA};
///
/// ShadowBuilder::builder()
///    .build_pattern(BuildPattern::RealTime)
///    .deny_const(BTreeSet::from([CARGO_TREE, CARGO_METADATA]))
///    .build().unwrap();
/// ```
///
#[derive(Debug)]
pub struct Shadow {
    /// The file that `shadow-rs` writes build information to.
    ///
    /// This file will contain all the necessary information about the build, including serialized build constants and other metadata.
    pub f: File,

    /// The values of build constants to be written.
    ///
    /// This is a mapping from `ShadowConst` identifiers to their corresponding `ConstVal` objects. Each entry in this map represents a build constant that will be included in the final build.
    pub map: BTreeMap<ShadowConst, ConstVal>,

    /// Build environment variables, obtained through [`std::env::vars`].
    ///
    /// These environment variables can affect the build process and are captured here for consistency and reproducibility.
    pub std_env: BTreeMap<String, String>,

    /// Constants in the deny list, passed through [`ShadowBuilder::deny_const`].
    ///
    /// This set contains build constant identifiers that should be excluded from the build process. By specifying these, you can prevent certain constants from being written into the build file.
    pub deny_const: BTreeSet<ShadowConst>,

    /// The output path where generated files will be placed.
    ///
    /// This specifies the directory where the build script will write its output. It's typically set using the `OUT_DIR` environment variable but can be customized using [`ShadowBuilder::out_path`].
    pub out_path: String,

    /// Determines the strategy for triggering package rebuilds.
    ///
    /// This field sets the pattern for how often the package should be rebuilt. Options include `Lazy`, `RealTime`, and `Custom`, each with its own implications on the build frequency and conditions under which a rebuild is triggered.
    /// It can be configured using [`ShadowBuilder::build_pattern`].
    pub build_pattern: BuildPattern,
}

impl Shadow {
    /// Write the build configuration specified by this [`Shadow`] instance.
    /// The hook function is run as well, allowing it to append to `shadow-rs`'s output.
    pub fn hook<F>(&self, f: F) -> SdResult<()>
    where
        F: Fn(&File) -> SdResult<()>,
    {
        let desc = r#"// Below code generated by project custom from by build.rs"#;
        writeln!(&self.f, "\n{desc}\n")?;
        f(&self.f)?;
        Ok(())
    }

    /// Try to infer the CI system that we're currently running under.
    ///
    /// TODO: Recognize other CI types, especially Travis and Jenkins.
    fn try_ci(&self) -> CiType {
        if let Some(c) = self.std_env.get("GITLAB_CI") {
            if c == "true" {
                return CiType::Gitlab;
            }
        }

        if let Some(c) = self.std_env.get("GITHUB_ACTIONS") {
            if c == "true" {
                return CiType::Github;
            }
        }

        CiType::None
    }

    /// Checks if the specified build constant is in the deny list.
    ///
    /// # Arguments
    /// * `deny_const` - A value of type `ShadowConst` representing the build constant to check.
    ///
    /// # Returns
    /// * `true` if the build constant is present in the deny list; otherwise, `false`.
    pub fn deny_contains(&self, deny_const: ShadowConst) -> bool {
        self.deny_const.contains(&deny_const)
    }

    pub(crate) fn build_inner(builder: ShadowBuilder) -> SdResult<Shadow> {
        let out_path = builder.get_out_path()?;
        let src_path = builder.get_src_path()?;
        let build_pattern = builder.get_build_pattern().clone();
        let deny_const = builder.get_deny_const().clone();

        let out = {
            let path = Path::new(out_path);
            if !out_path.ends_with('/') {
                path.join(format!("{out_path}/{DEFINE_SHADOW_RS}"))
            } else {
                path.join(DEFINE_SHADOW_RS)
            }
        };

        let mut shadow = Shadow {
            f: File::create(out)?,
            map: Default::default(),
            std_env: Default::default(),
            deny_const,
            out_path: out_path.to_string(),
            build_pattern,
        };
        shadow.std_env = get_std_env();

        let ci_type = shadow.try_ci();
        let src_path = Path::new(src_path.as_str());

        let mut map = new_git(src_path, ci_type, &shadow.std_env);
        for (k, v) in new_project(&shadow.std_env) {
            map.insert(k, v);
        }
        for (k, v) in new_system_env(&shadow) {
            map.insert(k, v);
        }
        shadow.map = map;

        // deny const
        shadow.filter_deny();

        shadow.write_all()?;

        // handle hook
        if let Some(h) = builder.get_hook() {
            shadow.hook(h.hook_inner())?
        }

        Ok(shadow)
    }

    fn filter_deny(&mut self) {
        self.deny_const.iter().for_each(|x| {
            self.map.remove(x);
        })
    }

    fn write_all(&mut self) -> SdResult<()> {
        self.gen_header()?;

        self.gen_const()?;

        //write version function
        let gen_version = self.gen_version()?;

        self.gen_build_in(gen_version)?;

        Ok(())
    }

    fn gen_const(&mut self) -> SdResult<()> {
        let out_dir = &self.out_path;
        self.build_pattern.rerun_if(self.map.keys(), out_dir);

        for (k, v) in &self.map {
            self.write_const(k, v)?;
        }
        Ok(())
    }

    fn gen_header(&self) -> SdResult<()> {
        let desc = format!(
            r#"// Code automatically generated by `shadow-rs` (https://github.com/baoyachi/shadow-rs), do not edit.
// Author: https://www.github.com/baoyachi
// Generation time: {}
"#,
            now_date_time().to_rfc2822()
        );
        writeln!(&self.f, "{desc}\n\n")?;
        Ok(())
    }

    fn write_const(&self, shadow_const: ShadowConst, val: &ConstVal) -> SdResult<()> {
        let desc = format!("#[doc=r#\"{}\"#]", val.desc);
        let define = match val.t {
            ConstType::Str => format!(
                "#[allow(dead_code)]\n\
                {}\n\
            pub const {} :{} = r#\"{}\"#;",
                CARGO_CLIPPY_ALLOW_ALL,
                shadow_const.to_ascii_uppercase(),
                ConstType::Str,
                val.v
            ),
            ConstType::Bool => format!(
                "#[allow(dead_code)]\n\
            	{}\n\
            pub const {} :{} = {};",
                CARGO_CLIPPY_ALLOW_ALL,
                shadow_const.to_ascii_uppercase(),
                ConstType::Bool,
                val.v.parse::<bool>().unwrap()
            ),
            ConstType::Slice => format!(
                "#[allow(dead_code)]\n\
            	{}\n\
            pub const {} :{} = &{:?};",
                CARGO_CLIPPY_ALLOW_ALL,
                shadow_const.to_ascii_uppercase(),
                ConstType::Slice,
                val.v.as_bytes()
            ),
            ConstType::Usize => format!(
                "#[allow(dead_code)]\n\
                {}\n\
            pub const {} :{} = {};",
                CARGO_CLIPPY_ALLOW_ALL,
                shadow_const.to_ascii_uppercase(),
                ConstType::Usize,
                val.v.parse::<usize>().unwrap_or_default()
            ),
            ConstType::Int => format!(
                "#[allow(dead_code)]\n\
                {}\n\
            pub const {} :{} = {};",
                CARGO_CLIPPY_ALLOW_ALL,
                shadow_const.to_ascii_uppercase(),
                ConstType::Int,
                val.v.parse::<i64>().unwrap_or_default()
            ),
        };

        writeln!(&self.f, "{desc}")?;
        writeln!(&self.f, "{define}\n")?;
        Ok(())
    }

    fn gen_version(&mut self) -> SdResult<Vec<&'static str>> {
        let (ver_fn, clap_long_ver_fn) = match self.map.get(TAG) {
            None => (version_branch_const(), clap_long_version_branch_const()),
            Some(tag) => {
                if !tag.v.is_empty() {
                    (version_tag_const(), clap_long_version_tag_const())
                } else {
                    (version_branch_const(), clap_long_version_branch_const())
                }
            }
        };
        writeln!(&self.f, "{ver_fn}\n")?;
        writeln!(&self.f, "{clap_long_ver_fn}\n")?;

        Ok(vec![BUILD_CONST_VERSION, BUILD_CONST_CLAP_LONG_VERSION])
    }

    fn gen_build_in(&self, gen_const: Vec<&'static str>) -> SdResult<()> {
        let mut print_val = String::from("\n");
        let mut params = String::from("\n");
        let mut default = String::from("\n");
        let mut all = String::from("\n");

        // append gen const
        for (k, v) in &self.map {
            let tmp = match v.t {
                ConstType::Str | ConstType::Bool | ConstType::Usize | ConstType::Int => {
                    default.push_str(&format!("\t\t\t{k}: true,\n"));
                    all.push_str(&format!("\t\t\t{k}: true,\n"));
                    format!(
                        r#"{}if self.{k} {{ writeln!(f, "{k}:{{{k}}}\n")?; }}{}"#,
                        "\t\t", "\n"
                    )
                }
                ConstType::Slice => {
                    default.push_str(&format!("\t\t\t{k}: false,\n"));
                    all.push_str(&format!("\t\t\t{k}: true,\n"));
                    format!(
                        r#"{}if self.{k} {{ writeln!(f, "{k}:{{:?}}\n",{})?; }}{}"#,
                        "\t\t", k, "\n",
                    )
                }
            };
            print_val.push_str(tmp.as_str());
            params.push_str(&format!("\tpub {k}: bool,\n"));
        }

        // append gen fn
        for k in gen_const {
            let tmp = format!(
                r#"{}if self.{k} {{ writeln!(f, "{k}:{{{k}}}\n")?; }}{}"#,
                "\t\t", "\n"
            );
            print_val.push_str(tmp.as_str());
            params.push_str(&format!("\tpub {k}: bool,\n"));
            default.push_str(&format!("\t\t\t{k}: true,\n"));
            all.push_str(&format!("\t\t\t{k}: true,\n"));
        }

        default.push_str("\t\t");
        all.push_str("\t\t");
        print_val.push_str("\t\tOk(())\n\t");

        let build_info_display_define = format!(
            "/// A struct that implements [`core::fmt::Display`] which\n\
            /// writes consts generated by `shadow-rs` to it's formatter\n\
            #[allow(non_snake_case)]\n\
            {CARGO_CLIPPY_ALLOW_ALL}\n\
            pub struct BuildInfoDisplay {\
                {{params}}\
            }\n\n\
            impl Default for BuildInfoDisplay {{\n\
                \t#[allow(dead_code)]\n\
                \t{CARGO_CLIPPY_ALLOW_ALL}\n\
                \t/// Every constant that `shadow-rs` tracks will be printed\n\
                \t/// except for slices (CARGO_METADATA for example)\n\
                \tfn default() -> Self {{\n\
                    \t\tSelf {\
                        {{default}}\
                    }\n\
                \t}}\n\
            }}\n\n\
            impl BuildInfoDisplay {{\n\
                \t#[allow(dead_code)]\n\
                \t{CARGO_CLIPPY_ALLOW_ALL}\n\
                \t/// Every constant that `shadow-rs` tracks will be printed\n\
                \tpub fn all() -> Self {{\n\
                    \t\tSelf {\
                        {{all}}\
                    }\n\
                \t}}\n\
            }}\n\n\
            impl core::fmt::Display for BuildInfoDisplay {{\n\
                \t#[allow(dead_code)]\n\
                \t{CARGO_CLIPPY_ALLOW_ALL}\n\
                \tfn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\
                    {{print_val}}\
                }\n\
            }}\n",
        );

        writeln!(&self.f, "{build_info_display_define}")?;

        #[cfg(not(feature = "no_std"))]
        {
            let print_build_in_define = format!(
                "/// Prints all built-in `shadow-rs` build constants\n\
                /// (except for slices) to standard output.\n\
            #[allow(dead_code)]\n\
            {CARGO_CLIPPY_ALLOW_ALL}\n\
            pub fn print_build_in() {{\n\
                \tprintln!(\"{{}}\", BuildInfoDisplay::default());\n\
            }}\n"
            );

            writeln!(&self.f, "{print_build_in_define}")?;

            #[cfg(feature = "metadata")]
            {
                use crate::gen_const::cargo_metadata_fn;
                writeln!(&self.f, "{}", cargo_metadata_fn(self))?;
            }
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::CARGO_TREE;
    use std::fs;

    #[test]
    fn test_build() -> SdResult<()> {
        ShadowBuilder::builder()
            .src_path("./")
            .out_path("./")
            .build()?;
        let shadow = fs::read_to_string(DEFINE_SHADOW_RS)?;
        assert!(!shadow.is_empty());
        assert!(shadow.lines().count() > 0);

        fs::remove_file(DEFINE_SHADOW_RS)?;

        ShadowBuilder::builder()
            .src_path("./")
            .out_path("./")
            .deny_const(BTreeSet::from([CARGO_TREE]))
            .build()?;

        let content = fs::read_to_string(DEFINE_SHADOW_RS)?;
        assert!(!content.is_empty());
        assert!(content.lines().count() > 0);
        let expect = "pub const CARGO_TREE :&str";
        assert!(!content.contains(expect));

        Ok(())
    }
}