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
use std::env;
use std::ffi::OsStr;
use std::path::{Path, PathBuf};

use anyhow::{bail, Result};

/// Build a [`PathBuf`].
///
/// # Examples
///
/// ```
/// use std::path::Path;
/// use embuild::path_buf;
/// assert_eq!(path_buf!["/foo", "bar"].as_path(), Path::new("/foo/bar"));
/// ```
#[macro_export]
macro_rules! path_buf {
    ($($e: expr),*) => {{
        use std::path::PathBuf;
        let mut pb = PathBuf::new();
        $(
            pb.push($e);
        )*
        pb
    }}
}

/// Spawn a command and return its handle.
///
/// This is a simple wrapper over the [`std::process::Command`] API. It expects at least
/// one argument for the program to run. Every comma seperated argument thereafter is
/// added to the command's arguments. Arguments after an `@`-sign specify collections of
/// arguments (specifically `impl IntoIterator<Item = impl AsRef<OsStr>`). The opional
/// `key=value` arguments after a semicolon are simply translated to calling the
/// `std::process::Command::<key>` method with `value` as its arguments.
///
/// **Note:**
///  `@`-arguments must be followed by at least one normal argument. For example
/// `cmd!("cmd", @args)` will not compile but `cmd!("cmd", @args, "other")` will. You can
/// use `key=value` arguments to work around this limitation: `cmd!("cmd"; args=(args))`.
///
/// After building the command [`std::process::Command::spawn`] is called and its return
/// value returned.
///
/// # Examples
/// ```ignore
/// let args_list = ["--foo", "--bar", "value"];
/// cmd_spawn!("git", @args_list, "clone"; arg=("url.com"), env=("var", "value"));
/// ```
#[macro_export]
macro_rules! cmd_spawn {
    ($cmd:expr $(, $(@$cmdargs:expr,)* $cmdarg:expr)* $(; $($k:ident = $v:tt),*)?) => {{
        let cmd = &($cmd);
        let mut builder = std::process::Command::new(cmd);
        $(
            $(builder.args($cmdargs);)*
            builder.arg($cmdarg);
        )*
        $($(builder. $k $v;)*)?

        builder.spawn()
    }};
}

/// Run a command to completion.
///
/// This is a simple wrapper over the [`std::process::Command`] API. It expects at least
/// one argument for the program to run. Every comma seperated argument thereafter is
/// added to the command's arguments. Arguments after an `@`-sign specify collections of
/// arguments (specifically `impl IntoIterator<Item = impl AsRef<OsStr>`). The opional
/// `key=value` arguments after a semicolon are simply translated to calling the
/// `std::process::Command::<key>` method with `value` as its arguments.
///
/// **Note:**
///  `@`-arguments must be followed by at least one normal argument. For example
/// `cmd!("cmd", @args)` will not compile but `cmd!("cmd", @args, "other")` will. You can
/// use `key=value` arguments to work around this limitation: `cmd!("cmd"; args=(args))`.
///
/// After building the command [`std::process::Command::status`] is called and its return
/// value returned if the command was executed sucessfully otherwise an error is returned.
/// If `status` is specified as the first `key=value` argument, the result of
/// [`Command::status`](std::process::Command::status) will be returned without checking
/// if the command succeeded.
///
/// # Examples
/// ```ignore
/// let args_list = ["--foo", "--bar", "value"];
/// cmd!("git", @args_list, "clone"; arg=("url.com"), env=("var", "value"));
/// ```
#[macro_export]
macro_rules! cmd {
    ($cmd:expr $(, $(@$cmdargs:expr,)* $cmdarg:expr)*; status, $($k:ident = $v:tt),*) => {{
        let cmd = &($cmd);
        let mut builder = std::process::Command::new(cmd);
        $(
            $(builder.args($cmdargs);)*
            builder.arg($cmdarg);
        )*
        $(builder. $k $v;)*

        use $crate::anyhow::Context;
        // TODO: add custom error type using `thiserror` to avoid repeating this code
        builder
            .status()
            .with_context(|| format!("Command '{:?}' failed to execute", &builder))
    }};
    ($cmd:expr $(, $(@$cmdargs:expr,)* $cmdarg:expr)* $(; $($k:ident = $v:tt),*)?) => {{
        let cmd = &($cmd);
        let mut builder = std::process::Command::new(cmd);
        $(
            $(builder.args($cmdargs);)*
            builder.arg($cmdarg);
        )*

        $($(builder. $k $v;)*)?

        match builder.status() {
            Err(err) => {
                Err(
                    $crate::anyhow::Error::new(err)
                        .context(format!("Command '{:?}' failed to execute", &builder))
                )
            },
            Ok(result) => {
                if !result.success() {
                    Err($crate::anyhow::anyhow!("Command '{:?}' failed with exit code {:?}.", &builder, result.code()))
                }
                else {
                    Ok(result)
                }
            }
        }
    }};
}

/// Run a command to completion and gets its `stdout` output.
///
/// This is a simple wrapper over the [`std::process::Command`] API. It expects at least
/// one argument for the program to run. Every comma seperated argument thereafter is
/// added to the command's arguments. Arguments after an `@`-sign specify collections of
/// arguments (specifically `impl IntoIterator<Item = impl AsRef<OsStr>`). The opional
/// `key=value` arguments after a semicolon are simply translated to calling the
/// `std::process::Command::<key>` method with `value` as its arguments.
///
/// **Note:**
///  `@`-arguments must be followed by at least one normal argument. For example
/// `cmd!("cmd", @args)` will not compile but `cmd!("cmd", @args, "other")` will. You can
/// use `key=value` arguments to work around this limitation: `cmd!("cmd"; args=(args))`.
///
/// After building the command [`std::process::Command::output`] is called. If the command
/// succeeded its `stdout` output is returned as a [`String`] otherwise an error is
/// returned. If `ignore_exitcode` is specified as the first `key=value` argument, the
/// command's output will be returned without checking if the command succeeded.
///
/// # Examples
/// ```ignore
/// let args_list = ["--foo", "--bar", "value"];
/// cmd_output!("git", @args_list, "clone"; arg=("url.com"), env=("var", "value"));
/// ```
#[macro_export]
macro_rules! cmd_output {
    ($cmd:expr $(, $(@$cmdargs:expr,)* $cmdarg:expr)*; ignore_exitcode $(,$k:ident = $v:tt)*) => {{
        let cmd = &($cmd);
        let mut builder = std::process::Command::new(cmd);
        $(
            $(builder.args($cmdargs);)*
            builder.arg($cmdarg);
        )*
        $(builder. $k $v;)*

        use $crate::anyhow::Context;
        builder.output()
            .with_context(|| format!("Command '{:?}' failed to execute", &builder))
            .map(|result| {
                // TODO: add some way to quiet this output
                use std::io::Write;
                std::io::stdout().write_all(&result.stdout[..]).ok();
                std::io::stderr().write_all(&result.stderr[..]).ok();

                String::from_utf8_lossy(&result.stdout[..]).trim_end_matches(&['\n', '\r'][..]).to_string()
            })
    }};
    ($cmd:expr $(, $(@$cmdargs:expr,)* $cmdarg:expr)* $(; $($k:ident = $v:tt),*)?) => {{
        let cmd = &($cmd);
        let mut builder = std::process::Command::new(cmd);
        $(
            $(builder.args($cmdargs);)*
            builder.arg($cmdarg);
        )*
        $($(builder. $k $v;)*)?

        match builder.output() {
            Err(err) => {
                Err(
                    $crate::anyhow::Error::new(err)
                        .context(format!("Command '{:?}' failed to execute", &builder))
                )
            },
            Ok(result) => {
                if !result.status.success() {
                    // TODO: add some way to quiet this output
                    use std::io::Write;
                    std::io::stdout().write_all(&result.stdout[..]).ok();
                    std::io::stderr().write_all(&result.stderr[..]).ok();


                    let base_err = $crate::anyhow::Error::msg(String::from_utf8_lossy(&result.stderr[..]).trim_end().to_string());
                    Err(base_err.context(
                        anyhow::anyhow!("Command '{:?}' failed with exit code {:?}", &builder, result.status.code())
                    ))
                }
                else {
                    Ok(String::from_utf8_lossy(&result.stdout[..]).trim_end_matches(&['\n', '\r'][..]).to_string())
                }
            }
        }
    }};
}

pub trait PathExt: AsRef<Path> {
    /// Pop `times` segments from this path.
    fn pop_times(&self, times: usize) -> PathBuf {
        let mut path: PathBuf = self.as_ref().to_owned();
        for _ in 0..times {
            path.pop();
        }
        path
    }

    /// Make this path absolute relative to `relative_dir` if not already.
    ///
    /// Note: Does not check if the path exists and no normalization takes place.
    fn abspath_relative_to(&self, relative_dir: impl AsRef<Path>) -> PathBuf {
        if self.as_ref().is_absolute() {
            return self.as_ref().to_owned();
        }

        relative_dir.as_ref().join(self)
    }

    /// Make this path absolute relative to [`env::current_dir`] if not already.
    ///
    /// Note: Does not check if the path exists and no normalization takes place.
    fn abspath(&self) -> Result<PathBuf> {
        if self.as_ref().is_absolute() {
            return Ok(self.as_ref().to_owned());
        }

        Ok(env::current_dir()?.join(self))
    }
}

impl PathExt for Path {}
impl PathExt for PathBuf {}

pub trait OsStrExt: AsRef<OsStr> {
    /// Try to convert this [`OsStr`] into a string.
    fn try_to_str(&self) -> Result<&str> {
        match self.as_ref().to_str() {
            Some(s) => Ok(s),
            _ => bail!(
                "Failed to convert the OsString '{}' to string.",
                self.as_ref().to_string_lossy()
            ),
        }
    }
}

impl OsStrExt for OsStr {}
impl OsStrExt for std::ffi::OsString {}
impl OsStrExt for Path {}
impl OsStrExt for PathBuf {}

/// Download the contents of `url` to `writer`.
pub fn download_file_to(url: &str, writer: &mut impl std::io::Write) -> Result<()> {
    let req = ureq::get(url).call()?;
    if req.status() != 200 {
        bail!(
            "Server at url '{}' returned unexpected status {}: {}",
            url,
            req.status(),
            req.status_text()
        );
    }

    let mut reader = req.into_reader();
    std::io::copy(&mut reader, writer)?;
    Ok(())
}