oxedyne/fe2o3/fe2o3_text/src/shell.rs
7.1 KiB, 1 run
created by r1870400018:76845, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | //! A POSIX shell command line read into words and simple commands, without running anything. |
| 2 | //! |
| 3 | //! Only the quoting and the operators are read: a parameter, a command substitution, a glob or a |
| 4 | //! leading `~` is left as written and the word is marked as not literal, since the shell would |
| 5 | //! hand the program something else. A caller that needs the word as the program would see it |
| 6 | //! treats a non-literal word as unknown. |
| 7 | |
| 8 | use oxedyne_fe2o3_core::prelude::*; |
| 9 | |
| 10 | |
| 11 | /// A word of a command line, its quoting removed. |
| 12 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 13 | pub struct Word { |
| 14 | pub text: String, |
| 15 | pub literal: bool, // no `$`, backquote, glob or leading `~` the shell would expand |
| 16 | } |
| 17 | |
| 18 | impl Word { |
| 19 | |
| 20 | /// A word the shell hands over as written, such as an element of an argv. |
| 21 | pub fn literal(text: &str) -> Self { |
| 22 | Self { text: text.to_string(), literal: true } |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 27 | pub enum Token { |
| 28 | Word(Word), |
| 29 | Sep, // ends a simple command: `;`, `&`, `|`, a newline, a bracket or a comment |
| 30 | ReadFrom, // `<`: the next word is a file the command reads |
| 31 | Redirect, // any other redirection: the next word is not an operand |
| 32 | } |
| 33 | |
| 34 | /// The tokens of a command line, quoted the way a POSIX shell quotes. |
| 35 | pub fn tokens(line: &str) -> Vec<Token> { |
| 36 | let mut toks = Vec::new(); |
| 37 | let mut cur = String::new(); |
| 38 | let mut lit = true; |
| 39 | let mut quoted = false; |
| 40 | let mut cs = line.chars().peekable(); |
| 41 | let flush = |toks: &mut Vec<Token>, cur: &mut String, lit: &mut bool, quoted: &mut bool| { |
| 42 | if *quoted || !cur.is_empty() { |
| 43 | toks.push(Token::Word(Word { text: std::mem::take(cur), literal: *lit })); |
| 44 | } |
| 45 | *lit = true; |
| 46 | *quoted = false; |
| 47 | }; |
| 48 | while let Some(c) = cs.next() { |
| 49 | match c { |
| 50 | ' ' | '\t' => flush(&mut toks, &mut cur, &mut lit, &mut quoted), |
| 51 | '\n' | ';' | '|' | '(' | ')' => { |
| 52 | flush(&mut toks, &mut cur, &mut lit, &mut quoted); |
| 53 | toks.push(Token::Sep); |
| 54 | } |
| 55 | '&' if cs.peek() == Some(&'>') => { |
| 56 | flush(&mut toks, &mut cur, &mut lit, &mut quoted); |
| 57 | cs.next(); |
| 58 | if cs.peek() == Some(&'>') { cs.next(); } |
| 59 | toks.push(Token::Redirect); |
| 60 | } |
| 61 | '&' => { |
| 62 | flush(&mut toks, &mut cur, &mut lit, &mut quoted); |
| 63 | toks.push(Token::Sep); |
| 64 | } |
| 65 | '<' | '>' => { |
| 66 | // A file descriptor number before the operator belongs to it. |
| 67 | if !quoted && !cur.is_empty() && cur.chars().all(|d| d.is_ascii_digit()) { |
| 68 | cur.clear(); |
| 69 | } |
| 70 | flush(&mut toks, &mut cur, &mut lit, &mut quoted); |
| 71 | let mut plain = true; |
| 72 | while let Some(&n) = cs.peek() { |
| 73 | if n == c || n == '&' || (c == '>' && n == '|') { |
| 74 | plain = false; |
| 75 | cs.next(); |
| 76 | } else { |
| 77 | break; |
| 78 | } |
| 79 | } |
| 80 | // `<<`, `<<<` and `<&` take a delimiter, a string or a descriptor, not a file. |
| 81 | toks.push(if c == '<' && plain { Token::ReadFrom } else { Token::Redirect }); |
| 82 | } |
| 83 | '\'' => { |
| 84 | quoted = true; |
| 85 | for n in cs.by_ref() { |
| 86 | if n == '\'' { break; } |
| 87 | cur.push(n); |
| 88 | } |
| 89 | } |
| 90 | '"' => { |
| 91 | quoted = true; |
| 92 | while let Some(n) = cs.next() { |
| 93 | match n { |
| 94 | '"' => break, |
| 95 | '\\' => match cs.peek() { |
| 96 | Some(&e) if matches!(e, '$' | '`' | '"' | '\\' | '\n') => { |
| 97 | cs.next(); |
| 98 | cur.push(e); |
| 99 | } |
| 100 | _ => cur.push('\\'), |
| 101 | }, |
| 102 | '$' | '`' => { lit = false; cur.push(n); } |
| 103 | _ => cur.push(n), |
| 104 | } |
| 105 | } |
| 106 | } |
| 107 | '\\' => { |
| 108 | quoted = true; |
| 109 | if let Some(n) = cs.next() { |
| 110 | if n != '\n' { cur.push(n); } |
| 111 | } |
| 112 | } |
| 113 | '#' if cur.is_empty() && !quoted => { |
| 114 | for n in cs.by_ref() { |
| 115 | if n == '\n' { break; } |
| 116 | } |
| 117 | toks.push(Token::Sep); |
| 118 | } |
| 119 | '~' if cur.is_empty() && !quoted => { lit = false; cur.push(c); } |
| 120 | '$' | '`' | '*' | '?' | '[' => { lit = false; cur.push(c); } |
| 121 | _ => cur.push(c), |
| 122 | } |
| 123 | } |
| 124 | flush(&mut toks, &mut cur, &mut lit, &mut quoted); |
| 125 | toks |
| 126 | } |
| 127 | |
| 128 | /// A simple command: its words, and the files its `<` redirections read. Other redirections |
| 129 | /// and their targets are dropped, as they are not operands. |
| 130 | #[derive(Clone, Debug, Default, PartialEq, Eq)] |
| 131 | pub struct Command { |
| 132 | pub words: Vec<Word>, |
| 133 | pub read_from: Vec<Word>, |
| 134 | } |
| 135 | |
| 136 | /// The simple commands of a command line, in order. |
| 137 | pub fn commands(line: &str) -> Vec<Command> { |
| 138 | let mut cmds = Vec::new(); |
| 139 | let mut cmd = Command::default(); |
| 140 | let mut toks = tokens(line).into_iter(); |
| 141 | while let Some(t) = toks.next() { |
| 142 | match t { |
| 143 | Token::Word(w) => cmd.words.push(w), |
| 144 | Token::ReadFrom => if let Some(Token::Word(w)) = toks.next() { cmd.read_from.push(w) }, |
| 145 | Token::Redirect => { toks.next(); } |
| 146 | Token::Sep => if !cmd.words.is_empty() || !cmd.read_from.is_empty() { |
| 147 | cmds.push(std::mem::take(&mut cmd)); |
| 148 | }, |
| 149 | } |
| 150 | } |
| 151 | if !cmd.words.is_empty() || !cmd.read_from.is_empty() { |
| 152 | cmds.push(cmd); |
| 153 | } |
| 154 | cmds |
| 155 | } |
| 156 | |
| 157 | impl Command { |
| 158 | |
| 159 | pub fn of_argv(argv: &[String]) -> Self { |
| 160 | Self { words: argv.iter().map(|a| Word::literal(a)).collect(), read_from: Vec::new() } |
| 161 | } |
| 162 | |
| 163 | /// The program and its arguments, past any leading `NAME=value` assignments. |
| 164 | pub fn args(&self) -> &[Word] { |
| 165 | let n = self.words.iter() |
| 166 | .take_while(|w| w.literal && w.text.split_once('=').map_or(false, |(k, _)| |
| 167 | !k.is_empty() && k.chars().all(|c| c == '_' || c.is_ascii_alphanumeric()))) |
| 168 | .count(); |
| 169 | &self.words[n..] |
| 170 | } |
| 171 | |
| 172 | /// The program's name without its folder, when the shell would run it as written. |
| 173 | pub fn program(&self) -> Option<&str> { |
| 174 | match self.args().first() { |
| 175 | Some(w) if w.literal => w.text.rsplit('/').next(), |
| 176 | _ => None, |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | /// Is the program a POSIX shell? |
| 181 | pub fn is_shell(&self) -> bool { |
| 182 | matches!(self.program(), Some("sh" | "bash" | "dash" | "zsh" | "ksh")) |
| 183 | } |
| 184 | |
| 185 | /// The script a shell is given with `-c`, the first operand after its options. |
| 186 | pub fn script(&self) -> Option<&Word> { |
| 187 | if !self.is_shell() { |
| 188 | return None; |
| 189 | } |
| 190 | let args = match self.args().split_first() { |
| 191 | Some((_, rest)) => rest, |
| 192 | None => return None, |
| 193 | }; |
| 194 | let c = args.iter().take_while(|w| w.text.starts_with('-')) |
| 195 | .any(|w| !w.text.starts_with("--") && w.text.contains('c')); |
| 196 | match c { |
| 197 | true => args.iter().find(|w| !w.text.starts_with('-')), |
| 198 | false => None, |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | /// Is this a `cd`? If so, `dir` moves to the folder it leaves the shell in, by [`join`], |
| 203 | /// and to `None` when that cannot be known from the line. |
| 204 | pub fn cd(&self, dir: &mut Option<String>) -> bool { |
| 205 | if self.program() != Some("cd") { |
| 206 | return false; |
| 207 | } |
| 208 | *dir = match self.args().get(1) { |
| 209 | Some(w) if w.literal && w.text != "-" => join(dir, &w.text), |
| 210 | _ => None, |
| 211 | }; |
| 212 | true |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | /// Where `path` lands from the folder `dir`: an absolute path stands, `Some("")` is the folder |
| 217 | /// the line started in so a relative path stands as written, and `None` is a folder no longer |
| 218 | /// known, from which nothing relative can be placed. |
| 219 | pub fn join(dir: &Option<String>, path: &str) -> Option<String> { |
| 220 | if path.starts_with('/') { |
| 221 | return Some(path.to_string()); |
| 222 | } |
| 223 | match dir { |
| 224 | Some(d) if d.is_empty() => Some(path.to_string()), |
| 225 | Some(d) => Some(fmt!("{}/{}", d.trim_end_matches('/'), path)), |
| 226 | None => None, |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | /// A word a POSIX shell reads back as exactly `s`. |
| 231 | pub fn quote(s: &str) -> String { |
| 232 | if !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || "_./,:@%+=-".contains(c)) { |
| 233 | return s.to_string(); |
| 234 | } |
| 235 | fmt!("'{}'", s.replace('\'', "'\\''")) |
| 236 | } |