cargo_emit/rerun_if_env_changed.rs
1/// Tells Cargo to run again if the file or directory at `$key` changes.
2///
3/// This is equivalent to:
4///
5/// ```
6/// println!("cargo:rerun-if-env-changed=$key");
7/// ```
8///
9/// `$key` is the name of an environment variable which indicates that if the
10/// environment variable's value changes the build script should be rerun. This
11/// basically behaves the same as [`rerun_if_changed!`] except that it works
12/// with environment variables instead. Note that the environment variables here
13/// are intended for global environment variables like `CC` and such, it's not
14/// necessary to use this for env vars like `TARGET` that Cargo sets. Also note
15/// that if [`rerun_if_env_changed!`] is used then Cargo will only rerun the
16/// build script if those environment variables change or if files printed out
17/// by [`rerun_if_changed!`] change.
18///
19/// # Examples
20///
21/// This is useful for tracking build-dependent files that Cargo does not
22/// already know.
23///
24/// ```
25/// cargo_emit::rerun_if_env_changed!("MY_DEPENDENCY", "PATH");
26/// ```
27///
28/// or, in case you want it to emit to a custom stream:
29///
30/// ```
31/// let mut stdout = std::io::stdout();
32/// cargo_emit::rerun_if_env_changed!(
33/// to: stdout,
34/// "MY_DEPENDENCY", "PATH"
35/// );
36/// ```
37///
38/// [`rerun_if_changed!`]: macro.rerun_if_changed.html
39/// [`rerun_if_env_changed!`]: macro.rerun_if_env_changed.html
40#[macro_export]
41macro_rules! rerun_if_env_changed {
42 (to: $stream:expr, $($key:expr),+ $(,)?) => {
43 $($crate::pair!(to: $stream, "rerun-if-env-changed", "{}", $key);)+
44 };
45 ($($key:expr),+ $(,)?) => {
46 $crate::rerun_if_env_changed!(to: std::io::stdout(), "{}", $($key),+);
47 };
48}
49
50#[cfg(test)]
51mod tests {
52 #[test]
53 fn single() {
54 insta::assert_display_snapshot!(
55 crate::capture_output(|output| {
56 crate::rerun_if_env_changed!(
57 to: output,
58 "KEY"
59 );
60 }),
61 @"cargo:rerun-if-env-changed=KEY\n"
62 );
63 }
64
65 #[test]
66 fn multiple() {
67 insta::assert_display_snapshot!(
68 crate::capture_output(|output| {
69 crate::rerun_if_env_changed!(
70 to: output,
71 "KEY1",
72 "KEY2",
73 "KEY3",
74 );
75 }),
76 @"cargo:rerun-if-env-changed=KEY1\n\
77 cargo:rerun-if-env-changed=KEY2\n\
78 cargo:rerun-if-env-changed=KEY3\n"
79 );
80 }
81}