foundry_common/io/
macros.rs

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
/// Prints a message to [`stdout`][std::io::stdout] and reads a line from stdin into a String.
///
/// Returns `Result<T>`, so sometimes `T` must be explicitly specified, like in `str::parse`.
///
/// # Examples
///
/// ```no_run
/// use foundry_common::prompt;
///
/// let response: String = prompt!("Would you like to continue? [y/N] ")?;
/// if !matches!(response.as_str(), "y" | "Y") {
///     return Ok(())
/// }
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[macro_export]
macro_rules! prompt {
    () => {
        $crate::stdin::parse_line()
    };

    ($($tt:tt)+) => {{
        let _ = $crate::sh_print!($($tt)+);
        match ::std::io::Write::flush(&mut ::std::io::stdout()) {
            ::core::result::Result::Ok(()) => $crate::prompt!(),
            ::core::result::Result::Err(e) => ::core::result::Result::Err(::eyre::eyre!("Could not flush stdout: {e}"))
        }
    }};
}

/// Prints a formatted error to stderr.
///
/// **Note**: will log regardless of the verbosity level.
#[macro_export]
macro_rules! sh_err {
    ($($args:tt)*) => {
        $crate::__sh_dispatch!(error $($args)*)
    };
}

/// Prints a formatted warning to stderr.
///
/// **Note**: if `verbosity` is set to `Quiet`, this is a no-op.
#[macro_export]
macro_rules! sh_warn {
    ($($args:tt)*) => {
        $crate::__sh_dispatch!(warn $($args)*)
    };
}

/// Prints a raw formatted message to stdout.
///
/// **Note**: if `verbosity` is set to `Quiet`, this is a no-op.
#[macro_export]
macro_rules! sh_print {
    ($($args:tt)*) => {
        $crate::__sh_dispatch!(print_out $($args)*)
    };

    ($shell:expr, $($args:tt)*) => {
        $crate::__sh_dispatch!(print_out $shell, $($args)*)
    };
}

/// Prints a raw formatted message to stderr.
///
/// **Note**: if `verbosity` is set to `Quiet`, this is a no-op.
#[macro_export]
macro_rules! sh_eprint {
    ($($args:tt)*) => {
        $crate::__sh_dispatch!(print_err $($args)*)
    };

    ($shell:expr, $($args:tt)*) => {
        $crate::__sh_dispatch!(print_err $shell, $($args)*)
    };
}

/// Prints a raw formatted message to stdout, with a trailing newline.
///
/// **Note**: if `verbosity` is set to `Quiet`, this is a no-op.
#[macro_export]
macro_rules! sh_println {
    () => {
        $crate::sh_print!("\n")
    };

    ($fmt:literal $($args:tt)*) => {
        $crate::sh_print!("{}\n", ::core::format_args!($fmt $($args)*))
    };

    ($shell:expr $(,)?) => {
        $crate::sh_print!($shell, "\n").expect("failed to write newline")
    };

    ($shell:expr, $($args:tt)*) => {
        $crate::sh_print!($shell, "{}\n", ::core::format_args!($($args)*))
    };

    ($($args:tt)*) => {
        $crate::sh_print!("{}\n", ::core::format_args!($($args)*))
    };
}

/// Prints a raw formatted message to stderr, with a trailing newline.
///
/// **Note**: if `verbosity` is set to `Quiet`, this is a no-op.
#[macro_export]
macro_rules! sh_eprintln {
    () => {
        $crate::sh_eprint!("\n")
    };

    ($fmt:literal $($args:tt)*) => {
        $crate::sh_eprint!("{}\n", ::core::format_args!($fmt $($args)*))
    };

    ($shell:expr $(,)?) => {
        $crate::sh_eprint!($shell, "\n")
    };

    ($shell:expr, $($args:tt)*) => {
        $crate::sh_eprint!($shell, "{}\n", ::core::format_args!($($args)*))
    };

    ($($args:tt)*) => {
        $crate::sh_eprint!("{}\n", ::core::format_args!($($args)*))
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __sh_dispatch {
    ($f:ident $fmt:literal $($args:tt)*) => {
        $crate::__sh_dispatch!(@impl $f &mut *$crate::Shell::get(), $fmt $($args)*)
    };

    ($f:ident $shell:expr, $($args:tt)*) => {
        $crate::__sh_dispatch!(@impl $f $shell, $($args)*)
    };

    ($f:ident $($args:tt)*) => {
        $crate::__sh_dispatch!(@impl $f &mut *$crate::Shell::get(), $($args)*)
    };

    // Ensure that the global shell lock is held for as little time as possible.
    // Also avoids deadlocks in case of nested calls.
    (@impl $f:ident $shell:expr, $($args:tt)*) => {
        match ::core::format_args!($($args)*) {
            fmt => $crate::Shell::$f($shell, fmt),
        }
    };
}

#[cfg(test)]
mod tests {
    #[test]
    fn macros() -> eyre::Result<()> {
        sh_err!("err")?;
        sh_err!("err {}", "arg")?;

        sh_warn!("warn")?;
        sh_warn!("warn {}", "arg")?;

        sh_print!("print -")?;
        sh_print!("print {} -", "arg")?;

        sh_println!()?;
        sh_println!("println")?;
        sh_println!("println {}", "arg")?;

        sh_eprint!("eprint -")?;
        sh_eprint!("eprint {} -", "arg")?;

        sh_eprintln!()?;
        sh_eprintln!("eprintln")?;
        sh_eprintln!("eprintln {}", "arg")?;

        sh_println!("{:?}", {
            sh_println!("hi")?;
            "nested"
        })?;

        Ok(())
    }

    #[test]
    fn macros_with_shell() -> eyre::Result<()> {
        let shell = &mut crate::Shell::new();
        sh_eprintln!(shell)?;
        sh_eprintln!(shell,)?;
        sh_eprintln!(shell, "shelled eprintln")?;
        sh_eprintln!(shell, "shelled eprintln {}", "arg")?;
        sh_eprintln!(&mut crate::Shell::new(), "shelled eprintln {}", "arg")?;

        Ok(())
    }
}