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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
use regex::Regex;
use std::collections::{HashMap, HashSet};
use std::fmt;

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

#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct WaitStatus(i32, i32, i32);

impl WaitStatus {
    pub fn from_exited(pid: i32, status: i32) -> Self {
        WaitStatus(pid, 0, status)
    }

    pub fn from_signaled(pid: i32, sig: i32) -> Self {
        WaitStatus(pid, 1, sig)
    }

    pub fn from_stopped(pid: i32, sig: i32) -> Self {
        WaitStatus(pid, 2, sig)
    }

    pub fn from_continuted(pid: i32) -> Self {
        WaitStatus(pid, 3, 0)
    }

    pub fn from_others() -> Self {
        WaitStatus(0, 9, 9)
    }

    pub fn from_error(errno: i32) -> Self {
        WaitStatus(0, 255, errno)
    }

    pub fn empty() -> Self {
        WaitStatus(0, 0, 0)
    }

    pub fn is_error(&self) -> bool {
        self.1 == 255
    }

    pub fn is_others(&self) -> bool {
        self.1 == 9
    }

    pub fn is_signaled(&self) -> bool {
        self.1 == 1
    }

    pub fn get_errno(&self) -> nix::Error {
        nix::Error::from_i32(self.2)
    }

    pub fn is_exited(&self) -> bool {
        self.0 != 0 && self.1 == 0
    }

    pub fn is_stopped(&self) -> bool {
        self.1 == 2
    }

    pub fn is_continued(&self) -> bool {
        self.1 == 3
    }

    pub fn get_pid(&self) -> i32 {
        self.0
    }

    fn _get_signaled_status(&self) -> i32 {
        self.2 + 128
    }

    pub fn get_signal(&self) -> i32 {
        self.2
    }

    pub fn get_name(&self) -> String {
        if self.is_exited() {
            "Exited".to_string()
        } else if self.is_stopped() {
            "Stopped".to_string()
        } else if self.is_continued() {
            "Continued".to_string()
        } else if self.is_signaled() {
            "Signaled".to_string()
        } else if self.is_others() {
            "Others".to_string()
        } else if self.is_error() {
            "Error".to_string()
        } else {
            format!("unknown: {}", self.2)
        }
    }

    pub fn get_status(&self) -> i32 {
        if self.is_exited() {
            self.2
        } else {
            self._get_signaled_status()
        }
    }
}

impl fmt::Debug for WaitStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut formatter = f.debug_struct("WaitStatus");
        formatter.field("pid", &self.0);
        let name = self.get_name();
        formatter.field("name", &name);
        formatter.field("ext", &self.2);
        formatter.finish()
    }
}

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 pids_stopped: HashSet<i32>,
    pub status: String,
    pub is_bg: bool,
}

impl Job {
    pub fn all_members_stopped(&self) -> bool {
        for pid in &self.pids {
            if !self.pids_stopped.contains(&pid) {
                return false;
            }
        }
        return true;
    }

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

#[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()
    }
}