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
use regex::Regex;
use std::collections::HashMap;

use crate::parsers;
use crate::parsers::parser_line::tokens_to_redirections;
use crate::shell;
use crate::libs;
use crate::tools;

pub const STOPPED: i32 = 148;

pub type Token = (String, String);
pub type Tokens = Vec<Token>;
pub type Redirection = (String, String, String);

///
/// command line: `ls 'foo bar' 2>&1 > /dev/null < one-file` would be:
/// Command {
///     tokens: [("", "ls"), ("", "-G"), ("\'", "foo bar")],
///     redirects_to: [
///         ("2", ">", "&1"),
///         ("1", ">", "/dev/null"),
///     ],
///     redirect_from: Some(("<", "one-file")),
/// }
///
#[derive(Debug)]
pub struct Command {
    pub tokens: Tokens,
    pub redirects_to: Vec<Redirection>,
    pub redirect_from: Option<Token>,
}

#[derive(Debug)]
pub struct CommandLine {
    pub line: String,
    pub commands: Vec<Command>,
    pub envs: HashMap<String, String>,
    pub background: bool,
}

impl Command {
    pub fn from_tokens(tokens: Tokens) -> Result<Command, String> {
        let mut tokens_new = tokens.clone();
        let mut redirects_from_type = String::new();
        let mut redirects_from_value = String::new();
        let mut has_redirect_from = tokens_new.iter().any(|x| x.1 == "<" || x.1 == "<<<");

        let mut len = tokens_new.len();
        while has_redirect_from {
            if let Some(idx) = tokens_new.iter().position(|x| x.1 == "<") {
                redirects_from_type = "<".to_string();
                tokens_new.remove(idx);
                len -= 1;
                if len > idx {
                    redirects_from_value = tokens_new.remove(idx).1;
                    len -= 1;
                }
            }
            if let Some(idx) = tokens_new.iter().position(|x| x.1 == "<<<") {
                redirects_from_type = "<<<".to_string();
                tokens_new.remove(idx);
                len -= 1;
                if len > idx {
                    redirects_from_value = tokens_new.remove(idx).1;
                    len -= 1;
                }
            }

            has_redirect_from = tokens_new.iter().any(|x| x.1 == "<" || x.1 == "<<<");
        }

        let tokens_final;
        let redirects_to;
        match tokens_to_redirections(&tokens_new) {
            Ok((_tokens, _redirects_to)) => {
                tokens_final = _tokens;
                redirects_to = _redirects_to;
            }
            Err(e) => {
                return Err(e);
            }
        }

        let redirect_from = if redirects_from_type.is_empty() {
            None
        } else {
            Some((redirects_from_type, redirects_from_value))
        };

        Ok(Command{
            tokens: tokens_final,
            redirects_to: redirects_to,
            redirect_from: redirect_from,
        })
    }

    pub fn has_redirect_from(&self) -> bool {
        self.redirect_from.is_some() &&
        self.redirect_from.clone().unwrap().0 == "<"
    }

    pub fn has_here_string(&self) -> bool {
        self.redirect_from.is_some() &&
        self.redirect_from.clone().unwrap().0 == "<<<"
    }

    pub fn is_builtin(&self) -> bool {
        tools::is_builtin(&self.tokens[0].1)
    }
}

#[derive(Debug, Clone, Default)]
pub struct Job {
    pub cmd: String,
    pub id: i32,
    pub gid: i32,
    pub pids: Vec<i32>,
    pub status: String,
    pub report: bool,
}

#[derive(Clone, Debug, Default)]
pub struct CommandResult {
    pub gid: i32,
    pub status: i32,
    pub stdout: String,
    pub stderr: String,
}

impl CommandResult {
    pub fn new() -> CommandResult {
        CommandResult {
            gid: 0,
            status: 0,
            stdout: String::new(),
            stderr: String::new(),
        }
    }

    pub fn from_status(gid: i32, status: i32) -> CommandResult {
        CommandResult {
            gid: gid,
            status: status,
            stdout: String::new(),
            stderr: String::new(),
        }
    }

    pub fn error() -> CommandResult {
        CommandResult {
            gid: 0,
            status: 1,
            stdout: String::new(),
            stderr: String::new(),
        }
    }
}

#[derive(Clone, Debug, Default)]
pub struct CommandOptions {
    pub background: bool,
    pub isatty: bool,
    pub capture_output: bool,
    pub envs: HashMap<String, String>,
}

fn split_tokens_by_pipes(tokens: &[Token]) -> Vec<Tokens> {
    let mut cmd = Vec::new();
    let mut cmds = Vec::new();
    for token in tokens {
        let sep = &token.0;
        let value = &token.1;
        if sep.is_empty() && value == "|" {
            if cmd.is_empty() {
                return Vec::new();
            }
            cmds.push(cmd.clone());
            cmd = Vec::new();
        } else {
            cmd.push(token.clone());
        }
    }
    if cmd.is_empty() {
        return Vec::new();
    }
    cmds.push(cmd.clone());
    cmds
}

fn drain_env_tokens(tokens: &mut Tokens) -> HashMap<String, String> {
    let mut envs: HashMap<String, String> = HashMap::new();
    let mut n = 0;
    let re = Regex::new(r"^([a-zA-Z0-9_]+)=(.*)$").unwrap();
    for (sep, text) in tokens.iter() {
        if !sep.is_empty() || !libs::re::re_contains(text, r"^([a-zA-Z0-9_]+)=(.*)$") {
            break;
        }

        for cap in re.captures_iter(text) {
            let name = cap[1].to_string();
            let value = parsers::parser_line::unquote(&cap[2]);
            envs.insert(name, value);
        }

        n += 1;
    }
    if n > 0 {
        tokens.drain(0..n);
    }
    envs
}

impl CommandLine {
    pub fn from_line(line: &str, sh: &mut shell::Shell) -> Result<CommandLine, String> {
        let mut tokens = parsers::parser_line::cmd_to_tokens(line);
        shell::do_expansion(sh, &mut tokens);
        let envs = drain_env_tokens(&mut tokens);

        let mut background = false;
        let len = tokens.len();
        if len > 1 && tokens[len - 1].1 == "&" {
            background = true;
            tokens.pop();
        }

        let mut commands = Vec::new();
        for sub_tokens in split_tokens_by_pipes(&tokens) {
            match Command::from_tokens(sub_tokens) {
                Ok(c) => {
                    commands.push(c);
                }
                Err(e) => {
                    return Err(e);
                }
            }
        }

        Ok(CommandLine{
            line: line.to_string(),
            commands: commands,
            envs: envs,
            background: background,
        })
    }

    pub fn is_empty(&self) -> bool {
        self.commands.is_empty()
    }

    pub fn with_pipeline(&self) -> bool {
        self.commands.len() > 1
    }

    pub fn is_single_and_builtin(&self) -> bool {
        self.commands.len() == 1 && self.commands[0].is_builtin()
    }
}