aboutsummaryrefslogtreecommitdiff
path: root/xtask/src/not_bash.rs
blob: 038898993ac046cea756fefa0851b02d379d19ab (plain)
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
//! A bad shell -- small cross platform module for writing glue code

use std::{
    cell::RefCell,
    env,
    ffi::OsString,
    io::{self, Write},
    path::{Path, PathBuf},
    process::{Command, Stdio},
};

use anyhow::{bail, Context, Result};

pub use fs_err as fs2;

#[macro_export]
macro_rules! run {
    ($($expr:expr),*) => {
        run!($($expr),*; echo = true)
    };
    ($($expr:expr),* ; echo = $echo:expr) => {
        $crate::not_bash::run_process(format!($($expr),*), $echo, None)
    };
    ($($expr:expr),* ;  <$stdin:expr) => {
        $crate::not_bash::run_process(format!($($expr),*), false, Some($stdin))
    };
}
pub use crate::run;

pub struct Pushd {
    _p: (),
}

pub fn pushd(path: impl Into<PathBuf>) -> Pushd {
    Env::with(|env| env.pushd(path.into()));
    Pushd { _p: () }
}

impl Drop for Pushd {
    fn drop(&mut self) {
        Env::with(|env| env.popd())
    }
}

pub struct Pushenv {
    _p: (),
}

pub fn pushenv(var: &str, value: &str) -> Pushenv {
    Env::with(|env| env.pushenv(var.into(), value.into()));
    Pushenv { _p: () }
}

impl Drop for Pushenv {
    fn drop(&mut self) {
        Env::with(|env| env.popenv())
    }
}

pub fn rm_rf(path: impl AsRef<Path>) -> io::Result<()> {
    let path = path.as_ref();
    if !path.exists() {
        return Ok(());
    }
    if path.is_file() {
        fs2::remove_file(path)
    } else {
        fs2::remove_dir_all(path)
    }
}

#[doc(hidden)]
pub fn run_process(cmd: String, echo: bool, stdin: Option<&[u8]>) -> Result<String> {
    run_process_inner(&cmd, echo, stdin).with_context(|| format!("process `{}` failed", cmd))
}

pub fn date_iso() -> Result<String> {
    run!("date --iso --utc")
}

fn run_process_inner(cmd: &str, echo: bool, stdin: Option<&[u8]>) -> Result<String> {
    let mut args = shelx(cmd);
    let binary = args.remove(0);
    let current_dir = Env::with(|it| it.cwd().to_path_buf());

    if echo {
        println!("> {}", cmd)
    }

    let mut command = Command::new(binary);
    command.args(args).current_dir(current_dir).stderr(Stdio::inherit());
    let output = match stdin {
        None => command.stdin(Stdio::null()).output(),
        Some(stdin) => {
            command.stdin(Stdio::piped()).stdout(Stdio::piped());
            let mut process = command.spawn()?;
            process.stdin.take().unwrap().write_all(stdin)?;
            process.wait_with_output()
        }
    }?;
    let stdout = String::from_utf8(output.stdout)?;

    if echo {
        print!("{}", stdout)
    }

    if !output.status.success() {
        bail!("{}", output.status)
    }

    Ok(stdout.trim().to_string())
}

// FIXME: some real shell lexing here
fn shelx(cmd: &str) -> Vec<String> {
    let mut res = Vec::new();
    for (string_piece, in_quotes) in cmd.split('\'').zip([false, true].iter().copied().cycle()) {
        if in_quotes {
            res.push(string_piece.to_string())
        } else {
            if !string_piece.is_empty() {
                res.extend(string_piece.split_ascii_whitespace().map(|it| it.to_string()))
            }
        }
    }
    res
}

struct Env {
    pushd_stack: Vec<PathBuf>,
    pushenv_stack: Vec<(OsString, Option<OsString>)>,
}

impl Env {
    fn with<F: FnOnce(&mut Env) -> T, T>(f: F) -> T {
        thread_local! {
            static ENV: RefCell<Env> = RefCell::new(Env {
                pushd_stack: vec![env::current_dir().unwrap()],
                pushenv_stack: vec![],
            });
        }
        ENV.with(|it| f(&mut *it.borrow_mut()))
    }

    fn pushd(&mut self, dir: PathBuf) {
        let dir = self.cwd().join(dir);
        self.pushd_stack.push(dir);
        env::set_current_dir(self.cwd())
            .unwrap_or_else(|err| panic!("Failed to set cwd to {}: {}", self.cwd().display(), err));
    }
    fn popd(&mut self) {
        self.pushd_stack.pop().unwrap();
        env::set_current_dir(self.cwd()).unwrap();
    }
    fn pushenv(&mut self, var: OsString, value: OsString) {
        self.pushenv_stack.push((var.clone(), env::var_os(&var)));
        env::set_var(var, value)
    }
    fn popenv(&mut self) {
        let (var, value) = self.pushenv_stack.pop().unwrap();
        match value {
            None => env::remove_var(var),
            Some(value) => env::set_var(var, value),
        }
    }
    fn cwd(&self) -> &Path {
        self.pushd_stack.last().unwrap()
    }
}