From 1b81f39fc61319f7d5d861eabb5310a3d2cc2250 Mon Sep 17 00:00:00 2001 From: Thomas Kinnen <thomas.kinnen@gmail.com> Date: Thu, 14 Dec 2017 13:59:34 +0100 Subject: [PATCH] Reformat the code. According to the README all code must be formated using the nightly formatter. Reran the format on the entire code-base as this came up when preparing the previous PR. --- src/builtins/exists.rs | 4 +- src/builtins/job_control.rs | 22 ++- src/builtins/man_pages.rs | 1 - src/builtins/mod.rs | 16 +- src/builtins/set.rs | 6 +- src/builtins/test.rs | 13 +- src/builtins/variables.rs | 6 +- src/parser/arguments.rs | 9 +- src/parser/assignments/actions.rs | 15 +- src/parser/assignments/keys.rs | 5 +- src/parser/assignments/splitter.rs | 4 +- src/parser/loops/for_grammar.rs | 4 +- src/parser/pipelines/collector.rs | 91 +++++---- src/parser/pipelines/mod.rs | 13 +- src/parser/quotes.rs | 33 ++-- src/parser/shell_expand/mod.rs | 20 +- src/parser/shell_expand/ranges.rs | 7 +- .../shell_expand/words/methods/arrays.rs | 108 +++++----- src/parser/shell_expand/words/methods/mod.rs | 10 +- .../shell_expand/words/methods/strings.rs | 186 +++++++++--------- src/parser/shell_expand/words/mod.rs | 6 +- src/parser/shell_expand/words/select.rs | 1 - src/parser/shell_expand/words/tests.rs | 31 ++- src/parser/statement/parse.rs | 65 +++--- src/parser/statement/splitter.rs | 32 ++- src/shell/assignments.rs | 4 +- src/shell/binary/designators.rs | 14 +- src/shell/binary/mod.rs | 15 +- src/shell/binary/terminate.rs | 8 +- src/shell/colors.rs | 10 +- src/shell/completer.rs | 8 +- src/shell/directory_stack.rs | 10 +- src/shell/flags.rs | 2 +- src/shell/flow.rs | 19 +- src/shell/flow_control.rs | 44 ++--- src/shell/fork.rs | 8 +- src/shell/history.rs | 2 +- src/shell/job.rs | 16 +- src/shell/mod.rs | 83 ++++---- src/shell/pipe_exec/foreground.rs | 16 +- src/shell/pipe_exec/fork.rs | 6 +- src/shell/pipe_exec/job_control.rs | 18 +- src/shell/pipe_exec/mod.rs | 34 ++-- src/shell/plugins/library_iter/redox.rs | 8 +- src/shell/plugins/library_iter/unix.rs | 4 +- src/shell/plugins/methods/redox.rs | 8 +- src/shell/plugins/methods/unix.rs | 18 +- src/shell/plugins/namespaces/redox.rs | 4 +- src/shell/signals.rs | 12 +- src/shell/status.rs | 4 +- src/shell/variables/mod.rs | 69 +++---- src/sys/redox.rs | 29 +-- src/sys/unix/mod.rs | 28 +-- 53 files changed, 529 insertions(+), 680 deletions(-) diff --git a/src/builtins/exists.rs b/src/builtins/exists.rs index eab328d5..d7d6c06f 100644 --- a/src/builtins/exists.rs +++ b/src/builtins/exists.rs @@ -118,9 +118,7 @@ fn file_has_execute_permission(filepath: &str) -> bool { } /// Returns true if the string is not empty -fn string_is_nonzero(string: &str) -> bool { - !string.is_empty() -} +fn string_is_nonzero(string: &str) -> bool { !string.is_empty() } /// Returns true if the variable is an array and the array is not empty fn array_var_is_not_empty(arrayvar: &str, shell: &Shell) -> bool { diff --git a/src/builtins/job_control.rs b/src/builtins/job_control.rs index 9b470d9f..9d409e34 100644 --- a/src/builtins/job_control.rs +++ b/src/builtins/job_control.rs @@ -26,9 +26,10 @@ pub(crate) fn disown(shell: &mut Shell, args: &[&str]) -> Result<(), String> { "-h" => flags |= NO_SIGHUP, "-r" => flags |= RUN_JOBS, _ => { - let jobspec = arg.parse::<u32>().map_err(|_| format!("invalid jobspec: '{}'", arg))?; + let jobspec = arg.parse::<u32>() + .map_err(|_| format!("invalid jobspec: '{}'", arg))?; collected_jobs.push(jobspec); - }, + } } } @@ -42,9 +43,13 @@ pub(crate) fn disown(shell: &mut Shell, args: &[&str]) -> Result<(), String> { let mut process_table = shell.background.lock().unwrap(); if collected_jobs.is_empty() && flags & ALL_JOBS != 0 { if flags & NO_SIGHUP != 0 { - process_table.iter_mut().for_each(|process| process.ignore_sighup = true); + process_table + .iter_mut() + .for_each(|process| process.ignore_sighup = true); } else { - process_table.iter_mut().for_each(|process| process.state = ProcessState::Empty); + process_table + .iter_mut() + .for_each(|process| process.state = ProcessState::Empty); } } else { collected_jobs.sort(); @@ -80,7 +85,10 @@ pub(crate) fn disown(shell: &mut Shell, args: &[&str]) -> Result<(), String> { pub(crate) fn jobs(shell: &mut Shell) { for (id, process) in shell.background.lock().unwrap().iter().enumerate() { if process.state != ProcessState::Empty { - eprintln!("[{}] {} {}\t{}", id, process.pid, process.state, process.name); + eprintln!( + "[{}] {} {}\t{}", + id, process.pid, process.state, process.name + ); } } } @@ -90,7 +98,9 @@ pub(crate) fn jobs(shell: &mut Shell) { /// If multiple jobs are given, then only the last job's exit status will be returned. pub(crate) fn fg(shell: &mut Shell, args: &[&str]) -> i32 { fn fg_job(shell: &mut Shell, njob: u32) -> i32 { - let job = if let Some(borrowed_job) = shell.background.lock().unwrap().iter().nth(njob as usize) { + let job = if let Some(borrowed_job) = + shell.background.lock().unwrap().iter().nth(njob as usize) + { borrowed_job.clone() } else { eprintln!("ion: fg: job {} does not exist", njob); diff --git a/src/builtins/man_pages.rs b/src/builtins/man_pages.rs index 7aa87409..135d598f 100644 --- a/src/builtins/man_pages.rs +++ b/src/builtins/man_pages.rs @@ -212,7 +212,6 @@ OPTIONS -c Execute command with an empty environment. "#; - pub(crate) const MAN_HISTORY: &'static str = r#"NAME history - print command history diff --git a/src/builtins/mod.rs b/src/builtins/mod.rs index 4cffe500..f6f2f82a 100644 --- a/src/builtins/mod.rs +++ b/src/builtins/mod.rs @@ -123,8 +123,8 @@ pub struct Builtin { } pub struct BuiltinMap { - pub(crate) name: &'static [&'static str], - pub(crate) help: &'static [&'static str], + pub(crate) name: &'static [&'static str], + pub(crate) help: &'static [&'static str], pub(crate) functions: &'static [BuiltinFunction], } @@ -139,13 +139,9 @@ impl BuiltinMap { }) } - pub fn keys(&self) -> &'static [&'static str] { - self.name - } + pub fn keys(&self) -> &'static [&'static str] { self.name } - pub fn contains_key(&self, func: &str) -> bool { - self.name.iter().any(|&name| name == func) - } + pub fn contains_key(&self, func: &str) -> bool { self.name.iter().any(|&name| name == func) } } // Definitions of simple builtins go here @@ -267,9 +263,7 @@ fn builtin_unalias(args: &[&str], shell: &mut Shell) -> i32 { // TODO There is a man page for fn however the -h and --help flags are not // checked for. -fn builtin_fn(_: &[&str], shell: &mut Shell) -> i32 { - fn_(&mut shell.functions) -} +fn builtin_fn(_: &[&str], shell: &mut Shell) -> i32 { fn_(&mut shell.functions) } fn builtin_read(args: &[&str], shell: &mut Shell) -> i32 { if check_help(args, MAN_READ) { diff --git a/src/builtins/set.rs b/src/builtins/set.rs index e97fe16f..e0405f3e 100644 --- a/src/builtins/set.rs +++ b/src/builtins/set.rs @@ -32,10 +32,10 @@ pub(crate) fn set(args: &[&str], shell: &mut Shell) -> i32 { b'o' => match args_iter.next() { Some(&"vi") => if let Some(context) = shell.context.as_mut() { context.key_bindings = KeyBindings::Vi; - } + }, Some(&"emacs") => if let Some(context) = shell.context.as_mut() { context.key_bindings = KeyBindings::Emacs; - } + }, Some(&"huponexit") => shell.flags |= HUPONEXIT, Some(_) => { eprintln!("ion: set: invalid option"); @@ -65,7 +65,7 @@ pub(crate) fn set(args: &[&str], shell: &mut Shell) -> i32 { eprintln!("ion: set: no option given"); return 0; } - } + }, _ => return 0, } } diff --git a/src/builtins/test.rs b/src/builtins/test.rs index 101a7980..0c0a37d5 100644 --- a/src/builtins/test.rs +++ b/src/builtins/test.rs @@ -221,9 +221,7 @@ fn file_is_character_device(filepath: &str) -> bool { } /// Exits SUCCESS if the file exists -fn file_exists(filepath: &str) -> bool { - Path::new(filepath).exists() -} +fn file_exists(filepath: &str) -> bool { Path::new(filepath).exists() } /// Exits SUCCESS if the file is a regular file fn file_is_regular(filepath: &str) -> bool { @@ -247,14 +245,10 @@ fn file_is_symlink(filepath: &str) -> bool { } /// Exits SUCCESS if the string is not empty -fn string_is_nonzero(string: &str) -> bool { - !string.is_empty() -} +fn string_is_nonzero(string: &str) -> bool { !string.is_empty() } /// Exits SUCCESS if the string is empty -fn string_is_zero(string: &str) -> bool { - string.is_empty() -} +fn string_is_zero(string: &str) -> bool { string.is_empty() } #[test] fn test_strings() { @@ -271,7 +265,6 @@ fn test_empty_str() { assert_eq!(eval(vec!["c", "=", ""]), Ok(false)); } - #[test] fn test_integers_arguments() { // Equal To diff --git a/src/builtins/variables.rs b/src/builtins/variables.rs index e58970f0..2f223df1 100644 --- a/src/builtins/variables.rs +++ b/src/builtins/variables.rs @@ -134,7 +134,6 @@ pub(crate) fn alias(vars: &mut Variables, args: &str) -> i32 { SUCCESS } - /// Dropping an alias will erase it from the shell. pub(crate) fn drop_alias<I: IntoIterator>(vars: &mut Variables, args: I) -> i32 where @@ -200,7 +199,6 @@ where SUCCESS } - #[cfg(test)] mod test { use super::*; @@ -210,9 +208,7 @@ mod test { struct VariableExpander(pub Variables); impl Expander for VariableExpander { - fn variable(&self, var: &str, _: bool) -> Option<Value> { - self.0.get_var(var) - } + fn variable(&self, var: &str, _: bool) -> Option<Value> { self.0.get_var(var) } } // TODO: Rewrite tests now that let is part of the grammar. diff --git a/src/parser/arguments.rs b/src/parser/arguments.rs index dedee06a..defce4de 100644 --- a/src/parser/arguments.rs +++ b/src/parser/arguments.rs @@ -7,16 +7,16 @@ const METHOD: u8 = 32; /// An efficient `Iterator` structure for splitting arguments pub struct ArgumentSplitter<'a> { - data: &'a str, - read: usize, + data: &'a str, + read: usize, flags: u8, } impl<'a> ArgumentSplitter<'a> { pub fn new(data: &'a str) -> ArgumentSplitter<'a> { ArgumentSplitter { - data: data, - read: 0, + data: data, + read: 0, flags: 0, } } @@ -135,7 +135,6 @@ mod tests { compare(input, expected); } - #[test] fn arrays() { let input = "echo [ one two @[echo three four] five ] [ six seven ]"; diff --git a/src/parser/assignments/actions.rs b/src/parser/assignments/actions.rs index c1bc9175..b2f75503 100644 --- a/src/parser/assignments/actions.rs +++ b/src/parser/assignments/actions.rs @@ -28,11 +28,11 @@ impl<'a> Display for AssignmentError<'a> { /// Each request will tell the shell whether the assignment is asking to update an array or a /// string, and will contain the key/value pair to assign. pub(crate) struct AssignmentActions<'a> { - keys: KeyIterator<'a>, + keys: KeyIterator<'a>, operator: Operator, - values: ArgumentSplitter<'a>, - prevkey: &'a str, - prevval: &'a str, + values: ArgumentSplitter<'a>, + prevkey: &'a str, + prevval: &'a str, } impl<'a> AssignmentActions<'a> { @@ -65,10 +65,9 @@ impl<'a> Iterator for AssignmentActions<'a> { } else { if let Some(_) = self.values.next() { eprintln!( - "ion: extra values were supplied, and thus ignored. Previous \ - assignment: '{}' = '{}'", - self.prevkey, - self.prevval + "ion: extra values were supplied, and thus ignored. Previous assignment: '{}' \ + = '{}'", + self.prevkey, self.prevval ); } None diff --git a/src/parser/assignments/keys.rs b/src/parser/assignments/keys.rs index b12502d7..20116dfc 100644 --- a/src/parser/assignments/keys.rs +++ b/src/parser/assignments/keys.rs @@ -16,7 +16,6 @@ pub(crate) struct KeyBuf { pub name: String, } - #[derive(Debug, PartialEq)] pub(crate) enum TypeError<'a> { Invalid(&'a str), @@ -107,9 +106,7 @@ pub(crate) struct KeyIterator<'a> { } impl<'a> KeyIterator<'a> { - pub(crate) fn new(data: &'a str) -> KeyIterator<'a> { - KeyIterator { data, read: 0 } - } + pub(crate) fn new(data: &'a str) -> KeyIterator<'a> { KeyIterator { data, read: 0 } } // Parameters are values that follow the semicolon (':'). fn parse_parameter(&mut self, name: &'a str) -> Result<Key<'a>, TypeError<'a>> { diff --git a/src/parser/assignments/splitter.rs b/src/parser/assignments/splitter.rs index 5de8aadd..711741ab 100644 --- a/src/parser/assignments/splitter.rs +++ b/src/parser/assignments/splitter.rs @@ -49,9 +49,7 @@ pub(crate) fn split_assignment<'a>( (Some(keys), Some(operator), Some(values.trim())) } -fn is_operator(byte: u8) -> bool { - byte == b'+' || byte == b'-' || byte == b'*' || byte == b'/' -} +fn is_operator(byte: u8) -> bool { byte == b'+' || byte == b'-' || byte == b'*' || byte == b'/' } #[cfg(test)] mod tests { diff --git a/src/parser/loops/for_grammar.rs b/src/parser/loops/for_grammar.rs index e6b639b5..58a3c8bf 100644 --- a/src/parser/loops/for_grammar.rs +++ b/src/parser/loops/for_grammar.rs @@ -70,9 +70,7 @@ mod tests { struct VariableExpander(pub Variables); impl Expander for VariableExpander { - fn variable(&self, var: &str, _: bool) -> Option<Value> { - self.0.get_var(var) - } + fn variable(&self, var: &str, _: bool) -> Option<Value> { self.0.get_var(var) } } #[test] diff --git a/src/parser/pipelines/collector.rs b/src/parser/pipelines/collector.rs index 47633316..0f3631f7 100644 --- a/src/parser/pipelines/collector.rs +++ b/src/parser/pipelines/collector.rs @@ -17,9 +17,7 @@ lazy_static! { } impl<'a> Collector<'a> { - pub(crate) fn new(data: &'a str) -> Self { - Collector { data } - } + pub(crate) fn new(data: &'a str) -> Self { Collector { data } } pub(crate) fn run(data: &'a str) -> Result<Pipeline, &'static str> { Collector::new(data).parse() @@ -356,7 +354,8 @@ impl<'a> Collector<'a> { }; let heredoc = heredoc.lines().skip(1).collect::<Vec<&str>>(); if heredoc.len() > 1 { - let herestring = Input::HereString(heredoc[..heredoc.len()-1].join("\n")); + let herestring = + Input::HereString(heredoc[..heredoc.len() - 1].join("\n")); inputs.as_mut().map(|x| x.push(herestring.clone())); } } @@ -403,8 +402,8 @@ mod tests { let expected = vec![ Redirection { - from: RedirectFrom::Stderr, - file: "/dev/null".to_owned(), + from: RedirectFrom::Stderr, + file: "/dev/null".to_owned(), append: false, }, ]; @@ -778,30 +777,30 @@ mod tests { let expected = Pipeline { items: vec![ PipeItem { - job: Job::new(array!["cat"], JobKind::Pipe(RedirectFrom::Stdout)), - inputs: vec![ + job: Job::new(array!["cat"], JobKind::Pipe(RedirectFrom::Stdout)), + inputs: vec![ Input::File("file1".into()), Input::HereString("\"herestring\"".into()), ], outputs: Vec::new(), }, PipeItem { - job: Job::new(array!["tr", "'x'", "'y'"], JobKind::Last), - inputs: Vec::new(), + job: Job::new(array!["tr", "'x'", "'y'"], JobKind::Last), + inputs: Vec::new(), outputs: vec![ Redirection { - from: RedirectFrom::Stderr, - file: "err".into(), + from: RedirectFrom::Stderr, + file: "err".into(), append: true, }, Redirection { - from: RedirectFrom::Both, - file: "both".into(), + from: RedirectFrom::Both, + file: "both".into(), append: false, }, Redirection { - from: RedirectFrom::Stdout, - file: "out".into(), + from: RedirectFrom::Stdout, + file: "out".into(), append: false, }, ], @@ -819,22 +818,22 @@ mod tests { let expected = Pipeline { items: vec![ PipeItem { - job: Job::new(array!["cat"], JobKind::Pipe(RedirectFrom::Stdout)), - inputs: Vec::new(), + job: Job::new(array!["cat"], JobKind::Pipe(RedirectFrom::Stdout)), + inputs: Vec::new(), outputs: Vec::new(), }, PipeItem { - job: Job::new(array!["echo", "hello"], JobKind::Pipe(RedirectFrom::Stdout)), - inputs: Vec::new(), + job: Job::new(array!["echo", "hello"], JobKind::Pipe(RedirectFrom::Stdout)), + inputs: Vec::new(), outputs: Vec::new(), }, PipeItem { - job: Job::new(array!["cat"], JobKind::Last), - inputs: vec![Input::File("stuff".into())], + job: Job::new(array!["cat"], JobKind::Last), + inputs: vec![Input::File("stuff".into())], outputs: vec![ Redirection { - from: RedirectFrom::Stderr, - file: "other".into(), + from: RedirectFrom::Stderr, + file: "other".into(), append: true, }, ], @@ -852,22 +851,22 @@ mod tests { let expected = Pipeline { items: vec![ PipeItem { - job: Job::new(array!["cat"], JobKind::Pipe(RedirectFrom::Stdout)), - inputs: Vec::new(), + job: Job::new(array!["cat"], JobKind::Pipe(RedirectFrom::Stdout)), + inputs: Vec::new(), outputs: Vec::new(), }, PipeItem { - job: Job::new(array!["echo", "hello"], JobKind::Pipe(RedirectFrom::Stdout)), - inputs: Vec::new(), + job: Job::new(array!["echo", "hello"], JobKind::Pipe(RedirectFrom::Stdout)), + inputs: Vec::new(), outputs: Vec::new(), }, PipeItem { - job: Job::new(array!["cat"], JobKind::Last), - inputs: vec![Input::File("stuff".into())], + job: Job::new(array!["cat"], JobKind::Last), + inputs: vec![Input::File("stuff".into())], outputs: vec![ Redirection { - from: RedirectFrom::Both, - file: "other".into(), + from: RedirectFrom::Both, + file: "other".into(), append: true, }, ], @@ -918,8 +917,8 @@ mod tests { let expected = Pipeline { items: vec![ PipeItem { - job: Job::new(array!["calc"], JobKind::Last), - inputs: vec![Input::HereString("$(cat math.txt)".into())], + job: Job::new(array!["calc"], JobKind::Last), + inputs: vec![Input::HereString("$(cat math.txt)".into())], outputs: vec![], }, ], @@ -933,8 +932,8 @@ mod tests { let expected = Pipeline { items: vec![ PipeItem { - job: Job::new(array!["calc"], JobKind::Last), - inputs: vec![Input::HereString("1 + 2\n3 + 4".into())], + job: Job::new(array!["calc"], JobKind::Last), + inputs: vec![Input::HereString("1 + 2\n3 + 4".into())], outputs: vec![], }, ], @@ -950,17 +949,17 @@ mod tests { let expected = Pipeline { items: vec![ PipeItem { - job: Job::new(array!["cat"], JobKind::Pipe(RedirectFrom::Stdout)), - inputs: Vec::new(), + job: Job::new(array!["cat"], JobKind::Pipe(RedirectFrom::Stdout)), + inputs: Vec::new(), outputs: Vec::new(), }, PipeItem { - job: Job::new(array!["tr", "'o'", "'x'"], JobKind::Last), - inputs: vec![Input::HereString("$VAR".into())], + job: Job::new(array!["tr", "'o'", "'x'"], JobKind::Last), + inputs: vec![Input::HereString("$VAR".into())], outputs: vec![ Redirection { - from: RedirectFrom::Stdout, - file: "out.log".into(), + from: RedirectFrom::Stdout, + file: "out.log".into(), append: false, }, ], @@ -993,12 +992,12 @@ mod tests { let expected = Pipeline { items: vec![ PipeItem { - job: Job::new(array!["echo", "zardoz"], JobKind::Last), - inputs: Vec::new(), + job: Job::new(array!["echo", "zardoz"], JobKind::Last), + inputs: Vec::new(), outputs: vec![ Redirection { - from: RedirectFrom::Stdout, - file: "foo\\'bar".into(), + from: RedirectFrom::Stdout, + file: "foo\\'bar".into(), append: true, }, ], diff --git a/src/parser/pipelines/mod.rs b/src/parser/pipelines/mod.rs index da00bbb2..301281e8 100644 --- a/src/parser/pipelines/mod.rs +++ b/src/parser/pipelines/mod.rs @@ -15,12 +15,11 @@ pub(crate) enum RedirectFrom { #[derive(Debug, PartialEq, Clone)] pub(crate) struct Redirection { - pub from: RedirectFrom, - pub file: String, + pub from: RedirectFrom, + pub file: String, pub append: bool, } - /// Represents input that a process could initially receive from `stdin` #[derive(Debug, PartialEq, Clone)] pub(crate) enum Input { @@ -39,9 +38,9 @@ pub(crate) struct Pipeline { #[derive(Debug, PartialEq, Clone)] pub(crate) struct PipeItem { - pub job: Job, + pub job: Job, pub outputs: Vec<Redirection>, - pub inputs: Vec<Input>, + pub inputs: Vec<Input>, } impl PipeItem { @@ -72,9 +71,7 @@ impl PipeItem { } impl Pipeline { - pub(crate) fn new() -> Self { - Pipeline { items: Vec::new() } - } + pub(crate) fn new() -> Self { Pipeline { items: Vec::new() } } pub(crate) fn expand(&mut self, shell: &Shell) { self.items.iter_mut().for_each(|i| i.expand(shell)); diff --git a/src/parser/quotes.rs b/src/parser/quotes.rs index fcf604f8..fe914953 100644 --- a/src/parser/quotes.rs +++ b/src/parser/quotes.rs @@ -18,35 +18,31 @@ bitflags! { /// This example comes from the shell's REPL, which ensures that the user's input /// will only be submitted for execution once a terminated command is supplied. pub struct Terminator { - buffer: String, - eof: Option<String>, + buffer: String, + eof: Option<String>, eof_buffer: String, - array: usize, - read: usize, - flags: Flags, + array: usize, + read: usize, + flags: Flags, } impl<'a> From<&'a str> for Terminator { - fn from(string: &'a str) -> Terminator { - Terminator::new(string.to_owned()) - } + fn from(string: &'a str) -> Terminator { Terminator::new(string.to_owned()) } } impl From<String> for Terminator { - fn from(string: String) -> Terminator { - Terminator::new(string) - } + fn from(string: String) -> Terminator { Terminator::new(string) } } impl Terminator { pub fn new(input: String) -> Terminator { Terminator { - buffer: input, - eof: None, + buffer: input, + eof: None, eof_buffer: String::new(), - array: 0, - read: 0, - flags: Flags::empty(), + array: 0, + read: 0, + flags: Flags::empty(), } } @@ -63,7 +59,6 @@ impl Terminator { } } - pub fn is_terminated(&mut self) -> bool { let mut eof_line = None; let eof = self.eof.clone(); @@ -187,7 +182,5 @@ impl Terminator { } /// Consumes the `Terminator`, and returns the underlying `String`. - pub fn consume(self) -> String { - self.buffer - } + pub fn consume(self) -> String { self.buffer } } diff --git a/src/parser/shell_expand/mod.rs b/src/parser/shell_expand/mod.rs index c97a1c14..71e3880b 100644 --- a/src/parser/shell_expand/mod.rs +++ b/src/parser/shell_expand/mod.rs @@ -26,21 +26,13 @@ pub(crate) fn is_expression(s: &str) -> bool { /// Trait representing different elements of string expansion pub(crate) trait Expander { /// Expand a tilde form to the correct directory - fn tilde(&self, &str) -> Option<String> { - None - } + fn tilde(&self, &str) -> Option<String> { None } /// Expand an array variable with some selection - fn array(&self, &str, Select) -> Option<Array> { - None - } + fn array(&self, &str, Select) -> Option<Array> { None } /// Expand a string variable given if its quoted / unquoted - fn variable(&self, &str, bool) -> Option<Value> { - None - } + fn variable(&self, &str, bool) -> Option<Value> { None } /// Expand a subshell expression - fn command(&self, &str) -> Option<Value> { - None - } + fn command(&self, &str) -> Option<Value> { None } } fn expand_process<E: Expander>( @@ -647,9 +639,7 @@ mod test { struct CommandExpander; impl Expander for CommandExpander { - fn command(&self, cmd: &str) -> Option<Value> { - Some(cmd.to_owned()) - } + fn command(&self, cmd: &str) -> Option<Value> { Some(cmd.to_owned()) } } #[test] diff --git a/src/parser/shell_expand/ranges.rs b/src/parser/shell_expand/ranges.rs index 5751d136..114bc93a 100644 --- a/src/parser/shell_expand/ranges.rs +++ b/src/parser/shell_expand/ranges.rs @@ -67,9 +67,7 @@ fn numeric_range( } #[inline] -fn byte_is_valid_range(b: u8) -> bool { - (b >= b'a' && b <= b'z') || (b >= b'A' && b <= b'Z') -} +fn byte_is_valid_range(b: u8) -> bool { (b >= b'a' && b <= b'z') || (b >= b'A' && b <= b'Z') } use std::u8; fn char_range(start: u8, mut end: u8, step: isize, inclusive: bool) -> Option<Vec<String>> { @@ -112,7 +110,6 @@ fn strings_to_isizes(a: &str, b: &str) -> Option<(isize, isize)> { } } - // In a range we allow the following syntax: // Exclusive nonstepped: {start..end} // Inclusive nonstepped: {start...end} @@ -284,7 +281,6 @@ pub(crate) fn parse_index_range(input: &str) -> Option<Range> { None } - #[test] fn index_ranges() { let valid_cases = vec![ @@ -381,7 +377,6 @@ fn range_expand() { let expected = Some(vec!["c".to_owned(), "b".to_owned()]); assert_eq!(actual, expected); - let actual = parse_range("-3..4"); let expected = Some(vec![ "-3".to_owned(), diff --git a/src/parser/shell_expand/words/methods/arrays.rs b/src/parser/shell_expand/words/methods/arrays.rs index 7df75fc8..660ac1fd 100644 --- a/src/parser/shell_expand/words/methods/arrays.rs +++ b/src/parser/shell_expand/words/methods/arrays.rs @@ -9,9 +9,9 @@ use unicode_segmentation::UnicodeSegmentation; #[derive(Debug, PartialEq, Clone)] pub(crate) struct ArrayMethod<'a> { - pub(crate) method: &'a str, - pub(crate) variable: &'a str, - pub(crate) pattern: Pattern<'a>, + pub(crate) method: &'a str, + pub(crate) variable: &'a str, + pub(crate) pattern: Pattern<'a>, pub(crate) selection: Select, } @@ -199,9 +199,9 @@ mod test { fn test_split_string_all() { let mut output = String::new(); let method = ArrayMethod { - method: "split", - variable: "$FOO", - pattern: Pattern::StringPattern("OB"), + method: "split", + variable: "$FOO", + pattern: Pattern::StringPattern("OB"), selection: Select::All, }; method.handle(&mut output, &VariableExpander); @@ -212,9 +212,9 @@ mod test { fn test_split_whitespace_all() { let mut output = String::new(); let method = ArrayMethod { - method: "split", - variable: "$SPACEDFOO", - pattern: Pattern::Whitespace, + method: "split", + variable: "$SPACEDFOO", + pattern: Pattern::Whitespace, selection: Select::All, }; method.handle(&mut output, &VariableExpander); @@ -225,9 +225,9 @@ mod test { fn test_split_string_index_forward() { let mut output = String::new(); let method = ArrayMethod { - method: "split", - variable: "$FOO", - pattern: Pattern::StringPattern("OB"), + method: "split", + variable: "$FOO", + pattern: Pattern::StringPattern("OB"), selection: Select::Index(Index::Forward(1)), }; method.handle(&mut output, &VariableExpander); @@ -238,9 +238,9 @@ mod test { fn test_split_whitespace_index_forward() { let mut output = String::new(); let method = ArrayMethod { - method: "split", - variable: "$SPACEDFOO", - pattern: Pattern::Whitespace, + method: "split", + variable: "$SPACEDFOO", + pattern: Pattern::Whitespace, selection: Select::Index(Index::Forward(1)), }; method.handle(&mut output, &VariableExpander); @@ -251,9 +251,9 @@ mod test { fn test_split_string_index_backward() { let mut output = String::new(); let method = ArrayMethod { - method: "split", - variable: "$FOO", - pattern: Pattern::StringPattern("OB"), + method: "split", + variable: "$FOO", + pattern: Pattern::StringPattern("OB"), selection: Select::Index(Index::Backward(1)), }; method.handle(&mut output, &VariableExpander); @@ -264,9 +264,9 @@ mod test { fn test_split_whitespace_index_backward() { let mut output = String::new(); let method = ArrayMethod { - method: "split", - variable: "$SPACEDFOO", - pattern: Pattern::Whitespace, + method: "split", + variable: "$SPACEDFOO", + pattern: Pattern::Whitespace, selection: Select::Index(Index::Backward(1)), }; method.handle(&mut output, &VariableExpander); @@ -277,9 +277,9 @@ mod test { fn test_split_string_range() { let mut output = String::new(); let method = ArrayMethod { - method: "split", - variable: "$FOO", - pattern: Pattern::StringPattern("OB"), + method: "split", + variable: "$FOO", + pattern: Pattern::StringPattern("OB"), selection: Select::Range(Range::from(Index::Forward(0))), }; method.handle(&mut output, &VariableExpander); @@ -290,9 +290,9 @@ mod test { fn test_split_whitespace_range() { let mut output = String::new(); let method = ArrayMethod { - method: "split", - variable: "$SPACEDFOO", - pattern: Pattern::Whitespace, + method: "split", + variable: "$SPACEDFOO", + pattern: Pattern::Whitespace, selection: Select::Range(Range::from(Index::Forward(0))), }; method.handle(&mut output, &VariableExpander); @@ -303,9 +303,9 @@ mod test { fn test_split_none() { let mut output = String::new(); let method = ArrayMethod { - method: "split", - variable: "$SPACEDFOO", - pattern: Pattern::Whitespace, + method: "split", + variable: "$SPACEDFOO", + pattern: Pattern::Whitespace, selection: Select::None, }; method.handle(&mut output, &VariableExpander); @@ -316,9 +316,9 @@ mod test { fn test_split_key() { let mut output = String::new(); let method = ArrayMethod { - method: "split", - variable: "$SPACEDFOO", - pattern: Pattern::Whitespace, + method: "split", + variable: "$SPACEDFOO", + pattern: Pattern::Whitespace, selection: Select::Key(Key::new("1")), }; method.handle(&mut output, &VariableExpander); @@ -328,9 +328,9 @@ mod test { #[test] fn test_split_at_failing_whitespace() { let method = ArrayMethod { - method: "split_at", - variable: "$SPACEDFOO", - pattern: Pattern::Whitespace, + method: "split_at", + variable: "$SPACEDFOO", + pattern: Pattern::Whitespace, selection: Select::All, }; assert_eq!(method.handle_as_array(&VariableExpander), array![]); @@ -339,9 +339,9 @@ mod test { #[test] fn test_split_at_failing_no_number() { let method = ArrayMethod { - method: "split_at", - variable: "$SPACEDFOO", - pattern: Pattern::StringPattern("a"), + method: "split_at", + variable: "$SPACEDFOO", + pattern: Pattern::StringPattern("a"), selection: Select::All, }; assert_eq!(method.handle_as_array(&VariableExpander), array![]); @@ -350,9 +350,9 @@ mod test { #[test] fn test_split_at_failing_out_of_bound() { let method = ArrayMethod { - method: "split_at", - variable: "$SPACEDFOO", - pattern: Pattern::StringPattern("100"), + method: "split_at", + variable: "$SPACEDFOO", + pattern: Pattern::StringPattern("100"), selection: Select::All, }; assert_eq!(method.handle_as_array(&VariableExpander), array![]); @@ -361,9 +361,9 @@ mod test { #[test] fn test_split_at_succeeding() { let method = ArrayMethod { - method: "split_at", - variable: "$FOO", - pattern: Pattern::StringPattern("3"), + method: "split_at", + variable: "$FOO", + pattern: Pattern::StringPattern("3"), selection: Select::All, }; assert_eq!( @@ -375,9 +375,9 @@ mod test { #[test] fn test_graphemes() { let method = ArrayMethod { - method: "graphemes", - variable: "$FOO", - pattern: Pattern::StringPattern("3"), + method: "graphemes", + variable: "$FOO", + pattern: Pattern::StringPattern("3"), selection: Select::All, }; assert_eq!( @@ -389,9 +389,9 @@ mod test { #[test] fn test_bytes() { let method = ArrayMethod { - method: "bytes", - variable: "$FOO", - pattern: Pattern::StringPattern("3"), + method: "bytes", + variable: "$FOO", + pattern: Pattern::StringPattern("3"), selection: Select::All, }; assert_eq!( @@ -403,9 +403,9 @@ mod test { #[test] fn test_chars() { let method = ArrayMethod { - method: "chars", - variable: "$FOO", - pattern: Pattern::StringPattern("3"), + method: "chars", + variable: "$FOO", + pattern: Pattern::StringPattern("3"), selection: Select::All, }; assert_eq!( diff --git a/src/parser/shell_expand/words/methods/mod.rs b/src/parser/shell_expand/words/methods/mod.rs index 90ed166e..34d85533 100644 --- a/src/parser/shell_expand/words/methods/mod.rs +++ b/src/parser/shell_expand/words/methods/mod.rs @@ -21,16 +21,12 @@ pub(crate) struct Key { impl Key { #[cfg(test)] - pub(crate) fn new<K: Into<::types::Key>>(key: K) -> Key { - Key { key: key.into() } - } - pub(crate) fn get(&self) -> &::types::Key { - return &self.key; - } + pub(crate) fn new<K: Into<::types::Key>>(key: K) -> Key { Key { key: key.into() } } + pub(crate) fn get(&self) -> &::types::Key { return &self.key; } } pub(crate) struct MethodArgs<'a, 'b, E: 'b + Expander> { - args: &'a str, + args: &'a str, expand: &'b E, } diff --git a/src/parser/shell_expand/words/methods/strings.rs b/src/parser/shell_expand/words/methods/strings.rs index c20f0124..1da1f928 100644 --- a/src/parser/shell_expand/words/methods/strings.rs +++ b/src/parser/shell_expand/words/methods/strings.rs @@ -344,9 +344,9 @@ mod test { fn test_ends_with_succeeding() { let mut output = String::new(); let method = StringMethod { - method: "ends_with", - variable: "$FOO", - pattern: "\"BAR\"", + method: "ends_with", + variable: "$FOO", + pattern: "\"BAR\"", selection: Select::All, }; method.handle(&mut output, &VariableExpander); @@ -357,9 +357,9 @@ mod test { fn test_ends_with_failing() { let mut output = String::new(); let method = StringMethod { - method: "ends_with", - variable: "$FOO", - pattern: "\"BA\"", + method: "ends_with", + variable: "$FOO", + pattern: "\"BA\"", selection: Select::All, }; method.handle(&mut output, &VariableExpander); @@ -370,9 +370,9 @@ mod test { fn test_contains_succeeding() { let mut output = String::new(); let method = StringMethod { - method: "contains", - variable: "$FOO", - pattern: "\"OBA\"", + method: "contains", + variable: "$FOO", + pattern: "\"OBA\"", selection: Select::All, }; method.handle(&mut output, &VariableExpander); @@ -383,9 +383,9 @@ mod test { fn test_contains_failing() { let mut output = String::new(); let method = StringMethod { - method: "contains", - variable: "$FOO", - pattern: "\"OBI\"", + method: "contains", + variable: "$FOO", + pattern: "\"OBI\"", selection: Select::All, }; method.handle(&mut output, &VariableExpander); @@ -396,9 +396,9 @@ mod test { fn test_starts_with_succeeding() { let mut output = String::new(); let method = StringMethod { - method: "starts_with", - variable: "$FOO", - pattern: "\"FOO\"", + method: "starts_with", + variable: "$FOO", + pattern: "\"FOO\"", selection: Select::All, }; method.handle(&mut output, &VariableExpander); @@ -409,9 +409,9 @@ mod test { fn test_starts_with_failing() { let mut output = String::new(); let method = StringMethod { - method: "starts_with", - variable: "$FOO", - pattern: "\"OO\"", + method: "starts_with", + variable: "$FOO", + pattern: "\"OO\"", selection: Select::All, }; method.handle(&mut output, &VariableExpander); @@ -422,9 +422,9 @@ mod test { fn test_basename() { let mut output = String::new(); let method = StringMethod { - method: "basename", - variable: "\"/home/redox/file.txt\"", - pattern: "", + method: "basename", + variable: "\"/home/redox/file.txt\"", + pattern: "", selection: Select::All, }; method.handle(&mut output, &VariableExpander); @@ -435,9 +435,9 @@ mod test { fn test_extension() { let mut output = String::new(); let method = StringMethod { - method: "extension", - variable: "\"/home/redox/file.txt\"", - pattern: "", + method: "extension", + variable: "\"/home/redox/file.txt\"", + pattern: "", selection: Select::All, }; method.handle(&mut output, &VariableExpander); @@ -448,9 +448,9 @@ mod test { fn test_filename() { let mut output = String::new(); let method = StringMethod { - method: "filename", - variable: "\"/home/redox/file.txt\"", - pattern: "", + method: "filename", + variable: "\"/home/redox/file.txt\"", + pattern: "", selection: Select::All, }; method.handle(&mut output, &VariableExpander); @@ -461,9 +461,9 @@ mod test { fn test_parent() { let mut output = String::new(); let method = StringMethod { - method: "parent", - variable: "\"/home/redox/file.txt\"", - pattern: "", + method: "parent", + variable: "\"/home/redox/file.txt\"", + pattern: "", selection: Select::All, }; method.handle(&mut output, &VariableExpander); @@ -474,9 +474,9 @@ mod test { fn test_to_lowercase() { let mut output = String::new(); let method = StringMethod { - method: "to_lowercase", - variable: "\"Ford Prefect\"", - pattern: "", + method: "to_lowercase", + variable: "\"Ford Prefect\"", + pattern: "", selection: Select::All, }; method.handle(&mut output, &VariableExpander); @@ -487,9 +487,9 @@ mod test { fn test_to_uppercase() { let mut output = String::new(); let method = StringMethod { - method: "to_uppercase", - variable: "\"Ford Prefect\"", - pattern: "", + method: "to_uppercase", + variable: "\"Ford Prefect\"", + pattern: "", selection: Select::All, }; method.handle(&mut output, &VariableExpander); @@ -500,9 +500,9 @@ mod test { fn test_repeat_succeeding() { let mut output = String::new(); let method = StringMethod { - method: "repeat", - variable: "$FOO", - pattern: "2", + method: "repeat", + variable: "$FOO", + pattern: "2", selection: Select::All, }; method.handle(&mut output, &VariableExpander); @@ -513,9 +513,9 @@ mod test { fn test_repeat_failing() { let mut output = String::new(); let method = StringMethod { - method: "repeat", - variable: "$FOO", - pattern: "-2", + method: "repeat", + variable: "$FOO", + pattern: "-2", selection: Select::All, }; method.handle(&mut output, &VariableExpander); @@ -526,9 +526,9 @@ mod test { fn test_replace_succeeding() { let mut output = String::new(); let method = StringMethod { - method: "replace", - variable: "$FOO", - pattern: "[\"FOO\" \"BAR\"]", + method: "replace", + variable: "$FOO", + pattern: "[\"FOO\" \"BAR\"]", selection: Select::All, }; method.handle(&mut output, &VariableExpander); @@ -539,9 +539,9 @@ mod test { fn test_replace_failing() { let mut output = String::new(); let method = StringMethod { - method: "replace", - variable: "$FOO", - pattern: "[]", + method: "replace", + variable: "$FOO", + pattern: "[]", selection: Select::All, }; method.handle(&mut output, &VariableExpander); @@ -552,9 +552,9 @@ mod test { fn test_replacen_succeeding() { let mut output = String::new(); let method = StringMethod { - method: "replacen", - variable: "\"FOO$FOO\"", - pattern: "[\"FOO\" \"BAR\" 1]", + method: "replacen", + variable: "\"FOO$FOO\"", + pattern: "[\"FOO\" \"BAR\" 1]", selection: Select::All, }; method.handle(&mut output, &VariableExpander); @@ -565,9 +565,9 @@ mod test { fn test_replacen_failing() { let mut output = String::new(); let method = StringMethod { - method: "replacen", - variable: "$FOO", - pattern: "[]", + method: "replacen", + variable: "$FOO", + pattern: "[]", selection: Select::All, }; method.handle(&mut output, &VariableExpander); @@ -578,9 +578,9 @@ mod test { fn test_regex_replace_succeeding() { let mut output = String::new(); let method = StringMethod { - method: "regex_replace", - variable: "$FOO", - pattern: "[\"^F\" \"f\"]", + method: "regex_replace", + variable: "$FOO", + pattern: "[\"^F\" \"f\"]", selection: Select::All, }; method.handle(&mut output, &VariableExpander); @@ -591,9 +591,9 @@ mod test { fn test_regex_replace_failing() { let mut output = String::new(); let method = StringMethod { - method: "regex_replace", - variable: "$FOO", - pattern: "[\"^f\" \"F\"]", + method: "regex_replace", + variable: "$FOO", + pattern: "[\"^f\" \"F\"]", selection: Select::All, }; method.handle(&mut output, &VariableExpander); @@ -604,9 +604,9 @@ mod test { fn test_join_with_string() { let mut output = String::new(); let method = StringMethod { - method: "join", - variable: "[\"FOO\" \"BAR\"]", - pattern: "\" \"", + method: "join", + variable: "[\"FOO\" \"BAR\"]", + pattern: "\" \"", selection: Select::All, }; method.handle(&mut output, &VariableExpander); @@ -617,9 +617,9 @@ mod test { fn test_join_with_array() { let mut output = String::new(); let method = StringMethod { - method: "join", - variable: "[\"FOO\" \"BAR\"]", - pattern: "[\"-\" \"-\"]", + method: "join", + variable: "[\"FOO\" \"BAR\"]", + pattern: "[\"-\" \"-\"]", selection: Select::All, }; method.handle(&mut output, &VariableExpander); @@ -630,9 +630,9 @@ mod test { fn test_len_with_array() { let mut output = String::new(); let method = StringMethod { - method: "len", - variable: "[\"1\"]", - pattern: "", + method: "len", + variable: "[\"1\"]", + pattern: "", selection: Select::All, }; method.handle(&mut output, &VariableExpander); @@ -643,9 +643,9 @@ mod test { fn test_len_with_string() { let mut output = String::new(); let method = StringMethod { - method: "len", - variable: "\"FOO\"", - pattern: "", + method: "len", + variable: "\"FOO\"", + pattern: "", selection: Select::All, }; method.handle(&mut output, &VariableExpander); @@ -656,9 +656,9 @@ mod test { fn test_len_with_variable() { let mut output = String::new(); let method = StringMethod { - method: "len", - variable: "$FOO", - pattern: "", + method: "len", + variable: "$FOO", + pattern: "", selection: Select::All, }; method.handle(&mut output, &VariableExpander); @@ -669,9 +669,9 @@ mod test { fn test_len_bytes_with_variable() { let mut output = String::new(); let method = StringMethod { - method: "len_bytes", - variable: "$FOO", - pattern: "", + method: "len_bytes", + variable: "$FOO", + pattern: "", selection: Select::All, }; method.handle(&mut output, &VariableExpander); @@ -682,9 +682,9 @@ mod test { fn test_len_bytes_with_string() { let mut output = String::new(); let method = StringMethod { - method: "len_bytes", - variable: "\"oh là là\"", - pattern: "", + method: "len_bytes", + variable: "\"oh là là\"", + pattern: "", selection: Select::All, }; method.handle(&mut output, &VariableExpander); @@ -695,9 +695,9 @@ mod test { fn test_reverse_with_variable() { let mut output = String::new(); let method = StringMethod { - method: "reverse", - variable: "$FOO", - pattern: "", + method: "reverse", + variable: "$FOO", + pattern: "", selection: Select::All, }; method.handle(&mut output, &VariableExpander); @@ -708,9 +708,9 @@ mod test { fn test_reverse_with_string() { let mut output = String::new(); let method = StringMethod { - method: "reverse", - variable: "\"FOOBAR\"", - pattern: "", + method: "reverse", + variable: "\"FOOBAR\"", + pattern: "", selection: Select::All, }; method.handle(&mut output, &VariableExpander); @@ -721,9 +721,9 @@ mod test { fn test_find_succeeding() { let mut output = String::new(); let method = StringMethod { - method: "find", - variable: "$FOO", - pattern: "\"O\"", + method: "find", + variable: "$FOO", + pattern: "\"O\"", selection: Select::All, }; method.handle(&mut output, &VariableExpander); @@ -734,9 +734,9 @@ mod test { fn test_find_failing() { let mut output = String::new(); let method = StringMethod { - method: "find", - variable: "$FOO", - pattern: "\"L\"", + method: "find", + variable: "$FOO", + pattern: "\"L\"", selection: Select::All, }; method.handle(&mut output, &VariableExpander); diff --git a/src/parser/shell_expand/words/mod.rs b/src/parser/shell_expand/words/mod.rs index 7cf7cec1..7b16eec6 100644 --- a/src/parser/shell_expand/words/mod.rs +++ b/src/parser/shell_expand/words/mod.rs @@ -48,9 +48,9 @@ pub(crate) enum WordToken<'a> { } pub(crate) struct WordIterator<'a, E: Expander + 'a> { - data: &'a str, - read: usize, - flags: Flags, + data: &'a str, + read: usize, + flags: Flags, expanders: &'a E, } diff --git a/src/parser/shell_expand/words/select.rs b/src/parser/shell_expand/words/select.rs index 7099df1f..0bc07bed 100644 --- a/src/parser/shell_expand/words/select.rs +++ b/src/parser/shell_expand/words/select.rs @@ -4,7 +4,6 @@ use super::super::ranges::parse_index_range; use std::iter::{empty, FromIterator}; use std::str::FromStr; - /// Represents a filter on a vector-like object #[derive(Debug, PartialEq, Clone)] pub(crate) enum Select { diff --git a/src/parser/shell_expand/words/tests.rs b/src/parser/shell_expand/words/tests.rs index 839d2f5b..f47e7aa5 100644 --- a/src/parser/shell_expand/words/tests.rs +++ b/src/parser/shell_expand/words/tests.rs @@ -24,22 +24,21 @@ fn ranges() { assert_eq!(None, range2.bounds(3)); } - #[test] fn string_method() { let input = "$join(array, 'pattern') $join(array, 'pattern')"; let expected = vec![ WordToken::StringMethod(StringMethod { - method: "join", - variable: "array", - pattern: "'pattern'", + method: "join", + variable: "array", + pattern: "'pattern'", selection: Select::All, }), WordToken::Whitespace(" "), WordToken::StringMethod(StringMethod { - method: "join", - variable: "array", - pattern: "'pattern'", + method: "join", + variable: "array", + pattern: "'pattern'", selection: Select::All, }), ]; @@ -265,25 +264,25 @@ impl Expander for WithVars { fn array_methods() { let expanders = WithVars; let method = ArrayMethod { - method: "graphemes", - variable: "pkmn1", - pattern: Pattern::Whitespace, + method: "graphemes", + variable: "pkmn1", + pattern: Pattern::Whitespace, selection: Select::Index(Index::Forward(3)), }; let expected = array!["é"]; assert_eq!(method.handle_as_array(&expanders), expected); let method = ArrayMethod { - method: "chars", - variable: "pkmn2", - pattern: Pattern::Whitespace, + method: "chars", + variable: "pkmn2", + pattern: Pattern::Whitespace, selection: Select::Index(Index::Forward(3)), }; let expected = array!["e"]; assert_eq!(method.handle_as_array(&expanders), expected); let method = ArrayMethod { - method: "bytes", - variable: "pkmn2", - pattern: Pattern::Whitespace, + method: "bytes", + variable: "pkmn2", + pattern: Pattern::Whitespace, selection: Select::Index(Index::Forward(1)), }; let expected = array!["111"]; diff --git a/src/parser/statement/parse.rs b/src/parser/statement/parse.rs index a6fbd930..a906895c 100644 --- a/src/parser/statement/parse.rs +++ b/src/parser/statement/parse.rs @@ -19,9 +19,7 @@ where } } -fn is_valid_name(name: &str) -> bool { - !name.chars().any(|c| !(c.is_alphanumeric() || c == '_')) -} +fn is_valid_name(name: &str) -> bool { !name.chars().any(|c| !(c.is_alphanumeric() || c == '_')) } pub(crate) fn parse(code: &str) -> Statement { let cmd = code.trim(); @@ -102,13 +100,11 @@ pub(crate) fn parse(code: &str) -> Statement { } } _ if cmd.starts_with("if ") => { - return collect(cmd[3..].trim_left(), |pipeline| { - Statement::If { - expression: pipeline, - success: Vec::new(), - else_if: Vec::new(), - failure: Vec::new(), - } + return collect(cmd[3..].trim_left(), |pipeline| Statement::If { + expression: pipeline, + success: Vec::new(), + else_if: Vec::new(), + failure: Vec::new(), }) } "else" => return Statement::Else, @@ -120,17 +116,15 @@ pub(crate) fn parse(code: &str) -> Statement { return collect(cmd[3..].trim_left(), |pipeline| { Statement::ElseIf(ElseIf { expression: pipeline, - success: Vec::new(), + success: Vec::new(), }) }); } } _ if cmd.starts_with("while ") => { - return collect(cmd[6..].trim_left(), |pipeline| { - Statement::While { - expression: pipeline, - statements: Vec::new(), - } + return collect(cmd[6..].trim_left(), |pipeline| Statement::While { + expression: pipeline, + statements: Vec::new(), }) } _ if cmd.starts_with("for ") => { @@ -152,8 +146,8 @@ pub(crate) fn parse(code: &str) -> Statement { } return Statement::For { - variable: variable.into(), - values: ArgumentSplitter::new(cmd[3..].trim_left()) + variable: variable.into(), + values: ArgumentSplitter::new(cmd[3..].trim_left()) .map(String::from) .collect(), statements: Vec::new(), @@ -189,7 +183,7 @@ pub(crate) fn parse(code: &str) -> Statement { _ if cmd.starts_with("match ") => { return Statement::Match { expression: cmd[6..].trim_left().into(), - cases: Vec::new(), + cases: Vec::new(), } } _ if cmd.starts_with("fn ") => { @@ -198,8 +192,8 @@ pub(crate) fn parse(code: &str) -> Statement { let name = &cmd[..pos]; if !is_valid_name(name) { eprintln!( - "ion: syntax error: '{}' is not a valid function name\n \ - Function names may only contain alphanumeric characters", + "ion: syntax error: '{}' is not a valid function name\n Function names \ + may only contain alphanumeric characters", name ); return Statement::Default; @@ -228,7 +222,6 @@ pub(crate) fn parse(code: &str) -> Statement { _ => (), } - if cmd.is_empty() || cmd.starts_with('#') { Statement::Default } else { @@ -252,7 +245,7 @@ mod tests { expression: Pipeline { items: vec![ PipeItem { - job: Job::new( + job: Job::new( vec![ "test".to_owned(), "1".to_owned(), @@ -263,13 +256,13 @@ mod tests { JobKind::Last, ), outputs: Vec::new(), - inputs: Vec::new(), + inputs: Vec::new(), }, ], }, - success: vec![], - else_if: vec![], - failure: vec![], + success: vec![], + else_if: vec![], + failure: vec![], }; assert_eq!(correct_parse, parsed_if); @@ -318,9 +311,9 @@ mod tests { let parsed_if = parse("fn bob"); let correct_parse = Statement::Function { description: None, - name: "bob".into(), - args: Default::default(), - statements: Default::default(), + name: "bob".into(), + args: Default::default(), + statements: Default::default(), }; assert_eq!(correct_parse, parsed_if); @@ -336,8 +329,8 @@ mod tests { let parsed_if = parse("fn bob a b"); let correct_parse = Statement::Function { description: None, - name: "bob".into(), - args: vec![ + name: "bob".into(), + args: vec![ KeyBuf { name: "a".into(), kind: Primitive::Any, @@ -347,7 +340,7 @@ mod tests { kind: Primitive::Any, }, ], - statements: Default::default(), + statements: Default::default(), }; assert_eq!(correct_parse, parsed_if); @@ -358,8 +351,8 @@ mod tests { let parsed_if = parse("fn bob a b --bob is a nice function"); let correct_parse = Statement::Function { description: Some("bob is a nice function".to_string()), - name: "bob".into(), - args: vec![ + name: "bob".into(), + args: vec![ KeyBuf { name: "a".into(), kind: Primitive::Any, @@ -369,7 +362,7 @@ mod tests { kind: Primitive::Any, }, ], - statements: vec![], + statements: vec![], }; assert_eq!(correct_parse, parsed_if); let parsed_if = parse("fn bob a b -- bob is a nice function"); diff --git a/src/parser/statement/splitter.rs b/src/parser/statement/splitter.rs index 61e229b8..8354a48e 100644 --- a/src/parser/statement/splitter.rs +++ b/src/parser/statement/splitter.rs @@ -20,7 +20,6 @@ bitflags! { } } - #[derive(Debug, PartialEq)] pub(crate) enum StatementError<'a> { IllegalCommandName(&'a str), @@ -42,8 +41,7 @@ impl<'a> Display for StatementError<'a> { StatementError::InvalidCharacter(character, position) => writeln!( f, "syntax error: '{}' at position {} is out of place", - character, - position + character, position ), StatementError::UnterminatedSubshell => { writeln!(f, "syntax error: unterminated subshell") @@ -70,26 +68,26 @@ fn is_invalid(byte: u8) -> bool { } pub(crate) struct StatementSplitter<'a> { - data: &'a str, - read: usize, - flags: Flags, - a_level: u8, - ap_level: u8, - p_level: u8, - brace_level: u8, + data: &'a str, + read: usize, + flags: Flags, + a_level: u8, + ap_level: u8, + p_level: u8, + brace_level: u8, math_paren_level: i8, } impl<'a> StatementSplitter<'a> { pub(crate) fn new(data: &'a str) -> StatementSplitter<'a> { StatementSplitter { - data: data, - read: 0, - flags: Flags::empty(), - a_level: 0, - ap_level: 0, - p_level: 0, - brace_level: 0, + data: data, + read: 0, + flags: Flags::empty(), + a_level: 0, + ap_level: 0, + p_level: 0, + brace_level: 0, math_paren_level: 0, } } diff --git a/src/shell/assignments.rs b/src/shell/assignments.rs index dfd51711..a021d78d 100644 --- a/src/shell/assignments.rs +++ b/src/shell/assignments.rs @@ -57,7 +57,6 @@ pub(crate) trait VariableStore { fn export(&mut self, ExportAction) -> i32; } - impl VariableStore for Shell { fn local(&mut self, action: LocalAction) -> i32 { let actions = match action { @@ -89,8 +88,7 @@ impl VariableStore for Shell { } Ok(Action::UpdateArray(..)) => { eprintln!( - "ion: arithmetic operators on array expressions aren't supported \ - yet." + "ion: arithmetic operators on array expressions aren't supported yet." ); return FAILURE; } diff --git a/src/shell/binary/designators.rs b/src/shell/binary/designators.rs index 6bfc468a..7ef640d6 100644 --- a/src/shell/binary/designators.rs +++ b/src/shell/binary/designators.rs @@ -18,7 +18,7 @@ enum Token<'a> { } struct DesignatorSearcher<'a> { - data: &'a [u8], + data: &'a [u8], flags: Flags, } @@ -104,9 +104,7 @@ pub(crate) fn expand_designators<'a>(shell: &Shell, cmd: &'a str) -> Cow<'a, str Cow::Borrowed(cmd) } -fn command<'a>(text: &'a str) -> &'a str { - ArgumentSplitter::new(text).next().unwrap_or(text) -} +fn command<'a>(text: &'a str) -> &'a str { ArgumentSplitter::new(text).next().unwrap_or(text) } fn args(text: &str) -> &str { let bytes = text.as_bytes(); @@ -123,10 +121,6 @@ fn args(text: &str) -> &str { .unwrap_or(text) } -fn first_arg<'a>(text: &'a str) -> &'a str { - ArgumentSplitter::new(text).nth(1).unwrap_or(text) -} +fn first_arg<'a>(text: &'a str) -> &'a str { ArgumentSplitter::new(text).nth(1).unwrap_or(text) } -fn last_arg<'a>(text: &'a str) -> &'a str { - ArgumentSplitter::new(text).last().unwrap_or(text) -} +fn last_arg<'a>(text: &'a str) -> &'a str { ArgumentSplitter::new(text).last().unwrap_or(text) } diff --git a/src/shell/binary/mod.rs b/src/shell/binary/mod.rs index d7c0a283..0789a0b5 100644 --- a/src/shell/binary/mod.rs +++ b/src/shell/binary/mod.rs @@ -49,17 +49,11 @@ pub(crate) trait Binary { } impl Binary for Shell { - fn prompt(&mut self) -> String { - prompt(self) - } + fn prompt(&mut self) -> String { prompt(self) } - fn prompt_fn(&mut self) -> Option<String> { - prompt_fn(self) - } + fn prompt_fn(&mut self) -> Option<String> { prompt_fn(self) } - fn readln(&mut self) -> Option<String> { - readln(self) - } + fn readln(&mut self) -> Option<String> { readln(self) } fn terminate_script_quotes<I: Iterator<Item = String>>(&mut self, lines: I) -> i32 { terminate_script_quotes(self, lines) @@ -115,8 +109,7 @@ impl Binary for Shell { let history_filename = self.get_var_or_empty("HISTFILE"); eprintln!( "ion: failed to find history file {}: {}", - history_filename, - err + history_filename, err ); } Err(err) => { diff --git a/src/shell/binary/terminate.rs b/src/shell/binary/terminate.rs index c288c206..3ef4658c 100644 --- a/src/shell/binary/terminate.rs +++ b/src/shell/binary/terminate.rs @@ -19,13 +19,11 @@ pub(crate) fn terminate_script_quotes<I: Iterator<Item = String>>( } match command[start..].find('#').map(|x| x + start) { - Some(pos) if command.as_bytes()[pos-1] != b' ' => { + Some(pos) if command.as_bytes()[pos - 1] != b' ' => { start = pos + 1; } - Some(pos) => { - break &command[..pos] - } - None => break &command + Some(pos) => break &command[..pos], + None => break &command, } }; buffer.append(cmd); diff --git a/src/shell/colors.rs b/src/shell/colors.rs index 665e50dd..91e790cf 100644 --- a/src/shell/colors.rs +++ b/src/shell/colors.rs @@ -1,13 +1,14 @@ struct StaticMap { - keys: &'static [&'static str], + keys: &'static [&'static str], values: &'static [&'static str], } impl StaticMap { fn get(&self, key: &str) -> Option<&'static str> { - self.keys.binary_search(&key).ok().map(|pos| unsafe { - *self.values.get_unchecked(pos) - }) + self.keys + .binary_search(&key) + .ok() + .map(|pos| unsafe { *self.values.get_unchecked(pos) }) } } @@ -131,7 +132,6 @@ impl Colors { } } - /// If no matches were made, then this will attempt to parse the variable as either a /// 24-bit true color color, or one of 256 colors. It supports both hexadecimal and /// decimals. diff --git a/src/shell/completer.rs b/src/shell/completer.rs index 8aa55d86..8df962e3 100644 --- a/src/shell/completer.rs +++ b/src/shell/completer.rs @@ -21,9 +21,9 @@ impl IonFileCompleter { vars: *const Variables, ) -> IonFileCompleter { IonFileCompleter { - inner: FilenameCompleter::new(path), + inner: FilenameCompleter::new(path), dir_stack: dir_stack, - vars: vars, + vars: vars, } } } @@ -151,9 +151,7 @@ where A: Completer, B: Completer, { - pub(crate) fn new(a: Vec<A>, b: B) -> MultiCompleter<A, B> { - MultiCompleter { a: a, b: b } - } + pub(crate) fn new(a: Vec<A>, b: B) -> MultiCompleter<A, B> { MultiCompleter { a: a, b: b } } } impl<A, B> Completer for MultiCompleter<A, B> diff --git a/src/shell/directory_stack.rs b/src/shell/directory_stack.rs index a20150a3..5eefe5c5 100644 --- a/src/shell/directory_stack.rs +++ b/src/shell/directory_stack.rs @@ -239,8 +239,7 @@ impl DirectoryStack { } (Err(err), _) => Err(Cow::Owned(format!( "ion: failed to set current dir to {}: {}\n", - dir, - err + dir, err ))), (..) => Err(Cow::Borrowed( "ion: change_and_push_dir(): error occurred that should never happen\n", @@ -329,9 +328,7 @@ impl DirectoryStack { SUCCESS } - pub(crate) fn dir_from_top(&self, num: usize) -> Option<&PathBuf> { - self.dirs.get(num) - } + pub(crate) fn dir_from_top(&self, num: usize) -> Option<&PathBuf> { self.dirs.get(num) } pub(crate) fn dir_from_bottom(&self, num: usize) -> Option<&PathBuf> { self.dirs.iter().rev().nth(num) @@ -353,8 +350,7 @@ impl DirectoryStack { let dir = self.dirs.iter().nth(index).ok_or_else(|| { Cow::Owned(format!( "ion: {}: {}: directory stack out of range\n", - caller, - index + caller, index )) })?; diff --git a/src/shell/flags.rs b/src/shell/flags.rs index 9dcb63b9..430ef982 100644 --- a/src/shell/flags.rs +++ b/src/shell/flags.rs @@ -1,4 +1,4 @@ pub const ERR_EXIT: u8 = 1; pub const PRINT_COMMS: u8 = 2; pub const NO_EXEC: u8 = 4; -pub const HUPONEXIT: u8 = 8; \ No newline at end of file +pub const HUPONEXIT: u8 = 8; diff --git a/src/shell/flow.rs b/src/shell/flow.rs index 881499fd..4930bef3 100644 --- a/src/shell/flow.rs +++ b/src/shell/flow.rs @@ -1,7 +1,6 @@ use super::Shell; use super::flags::*; -use super::flow_control::{collect_cases, collect_if, collect_loops, Case, ElseIf, Function, - Statement}; +use super::flow_control::{collect_cases, collect_if, collect_loops, Case, ElseIf, Function, Statement}; use super::job_control::JobControl; use super::status::*; use parser::{expand_string, parse_and_validate, ForExpression, StatementSplitter}; @@ -669,8 +668,8 @@ impl FlowLogic for Shell { } else { // Store the partial `Statement::For` to memory self.flow_control.current_statement = Statement::For { - variable: variable, - values: values, + variable: variable, + values: values, statements: statements, } } @@ -705,9 +704,9 @@ impl FlowLogic for Shell { self.flow_control.current_if_mode = mode; self.flow_control.current_statement = Statement::If { expression: expression, - success: success, - else_if: else_if, - failure: failure, + success: success, + else_if: else_if, + failure: failure, }; } } @@ -734,9 +733,9 @@ impl FlowLogic for Shell { // Store the partial function declaration in memory. self.flow_control.current_statement = Statement::Function { description: description, - name: name, - args: args, - statements: statements, + name: name, + args: args, + statements: statements, } } } diff --git a/src/shell/flow_control.rs b/src/shell/flow_control.rs index 663774d1..298cfbf1 100644 --- a/src/shell/flow_control.rs +++ b/src/shell/flow_control.rs @@ -10,7 +10,7 @@ use types::Identifier; #[derive(Debug, PartialEq, Clone)] pub(crate) struct ElseIf { pub expression: Pipeline, - pub success: Vec<Statement>, + pub success: Vec<Statement>, } /// Represents a single branch in a match statement. For example, in the expression @@ -35,10 +35,10 @@ pub(crate) struct ElseIf { /// ``` #[derive(Debug, PartialEq, Clone)] pub(crate) struct Case { - pub value: Option<String>, - pub binding: Option<String>, + pub value: Option<String>, + pub binding: Option<String>, pub conditional: Option<String>, - pub statements: Vec<Statement>, + pub statements: Vec<Statement>, } #[derive(Debug, PartialEq, Clone)] @@ -62,20 +62,20 @@ pub(crate) enum Statement { Export(ExportAction), If { expression: Pipeline, - success: Vec<Statement>, - else_if: Vec<ElseIf>, - failure: Vec<Statement>, + success: Vec<Statement>, + else_if: Vec<ElseIf>, + failure: Vec<Statement>, }, ElseIf(ElseIf), Function { - name: Identifier, + name: Identifier, description: Option<String>, - args: Vec<KeyBuf>, - statements: Vec<Statement>, + args: Vec<KeyBuf>, + statements: Vec<Statement>, }, For { - variable: Identifier, - values: Vec<String>, + variable: Identifier, + values: Vec<String>, statements: Vec<Statement>, }, While { @@ -84,7 +84,7 @@ pub(crate) enum Statement { }, Match { expression: String, - cases: Vec<Case>, + cases: Vec<Case>, }, Else, End, @@ -121,17 +121,17 @@ impl Statement { } pub(crate) struct FlowControl { - pub level: usize, + pub level: usize, pub current_statement: Statement, - pub current_if_mode: u8, // { 0 = SUCCESS; 1 = FAILURE } + pub current_if_mode: u8, // { 0 = SUCCESS; 1 = FAILURE } } impl Default for FlowControl { fn default() -> FlowControl { FlowControl { - level: 0, + level: 0, current_statement: Statement::Default, - current_if_mode: 0, + current_if_mode: 0, } } } @@ -139,9 +139,9 @@ impl Default for FlowControl { #[derive(Clone)] pub struct Function { description: Option<String>, - name: Identifier, - args: Vec<KeyBuf>, - statements: Vec<Statement>, + name: Identifier, + args: Vec<KeyBuf>, + statements: Vec<Statement>, } #[derive(Debug, PartialEq, Clone)] @@ -175,9 +175,7 @@ impl Function { } } - pub(crate) fn get_description<'a>(&'a self) -> Option<&'a String> { - self.description.as_ref() - } + pub(crate) fn get_description<'a>(&'a self) -> Option<&'a String> { self.description.as_ref() } pub(crate) fn execute(self, shell: &mut Shell, args: &[&str]) -> Result<(), FunctionError> { if args.len() - 1 != self.args.len() { diff --git a/src/shell/fork.rs b/src/shell/fork.rs index 86cac8a3..761eb8ed 100644 --- a/src/shell/fork.rs +++ b/src/shell/fork.rs @@ -24,7 +24,7 @@ pub enum Capture { /// /// Using this structure directly is equivalent to using `Shell`'s fork method. pub struct Fork<'a> { - shell: &'a Shell, + shell: &'a Shell, capture: Capture, } @@ -34,16 +34,14 @@ pub struct Fork<'a> { /// in the future, once there's a better means of obtaining the exit status without having to /// wait on the PID. pub struct IonResult { - pub pid: u32, + pub pid: u32, pub stdout: Option<File>, pub stderr: Option<File>, } impl<'a> Fork<'a> { /// Creates a new `Fork` state from an existing shell. - pub fn new(shell: &'a Shell, capture: Capture) -> Fork<'a> { - Fork { shell, capture } - } + pub fn new(shell: &'a Shell, capture: Capture) -> Fork<'a> { Fork { shell, capture } } /// Executes a closure within the child of the fork, and returning an `IonResult` in a /// non-blocking fashion. diff --git a/src/shell/history.rs b/src/shell/history.rs index bbdb0a10..2feb4501 100644 --- a/src/shell/history.rs +++ b/src/shell/history.rs @@ -28,7 +28,7 @@ pub(crate) struct IgnoreSetting { impl IgnoreSetting { pub(crate) fn default() -> IgnoreSetting { IgnoreSetting { - flags: IgnoreFlags::empty(), + flags: IgnoreFlags::empty(), regexes: None, } } diff --git a/src/shell/job.rs b/src/shell/job.rs index 3d2c7b91..d905ce76 100644 --- a/src/shell/job.rs +++ b/src/shell/job.rs @@ -22,8 +22,8 @@ pub(crate) enum JobKind { #[derive(Clone)] pub(crate) struct Job { pub command: Identifier, - pub args: Array, - pub kind: JobKind, + pub args: Array, + pub kind: JobKind, pub builtin: Option<BuiltinFunction>, } @@ -60,9 +60,7 @@ impl fmt::Debug for Job { write!( f, "Job {{ command: {}, args: {:?}, kind: {:?} }}", - self.command, - self.args, - self.kind + self.command, self.args, self.kind ) } } @@ -111,8 +109,8 @@ pub(crate) enum RefinedJob { /// Represents redirection into stdin from more than one source Cat { sources: Vec<File>, - stdin: Option<File>, - stdout: Option<File>, + stdin: Option<File>, + stdout: Option<File>, }, Tee { /// 0 for stdout, 1 for stderr @@ -234,8 +232,8 @@ impl RefinedJob { pub(crate) fn tee(tee_out: Option<TeeItem>, tee_err: Option<TeeItem>) -> Self { RefinedJob::Tee { - items: (tee_out, tee_err), - stdin: None, + items: (tee_out, tee_err), + stdin: None, stdout: None, stderr: None, } diff --git a/src/shell/mod.rs b/src/shell/mod.rs index c3755e5a..9da6cc93 100644 --- a/src/shell/mod.rs +++ b/src/shell/mod.rs @@ -33,9 +33,9 @@ use self::variables::Variables; use builtins::{BuiltinMap, BUILTINS}; use fnv::FnvHashMap; use liner::Context; +use parser::{ArgumentSplitter, Expander, Select}; use parser::Terminator; use parser::pipelines::Pipeline; -use parser::{ArgumentSplitter, Expander, Select}; use smallvec::SmallVec; use std::env; use std::fs::File; @@ -44,8 +44,8 @@ use std::iter::FromIterator; use std::ops::Deref; use std::path::Path; use std::process; -use std::sync::atomic::Ordering; use std::sync::{Arc, Mutex}; +use std::sync::atomic::Ordering; use std::time::SystemTime; use sys; use types::*; @@ -112,22 +112,22 @@ impl<'a> Shell { /// Panics if DirectoryStack construction fails pub(crate) fn new_bin() -> Shell { Shell { - builtins: BUILTINS, - context: None, - variables: Variables::default(), - flow_control: FlowControl::default(), - directory_stack: DirectoryStack::new(), - functions: FnvHashMap::default(), - previous_job: !0, - previous_status: 0, - flags: 0, - foreground: Vec::new(), - background: Arc::new(Mutex::new(Vec::new())), + builtins: BUILTINS, + context: None, + variables: Variables::default(), + flow_control: FlowControl::default(), + directory_stack: DirectoryStack::new(), + functions: FnvHashMap::default(), + previous_job: !0, + previous_status: 0, + flags: 0, + foreground: Vec::new(), + background: Arc::new(Mutex::new(Vec::new())), is_background_shell: false, - is_library: false, - break_flow: false, - foreground_signals: Arc::new(ForegroundSignals::new()), - ignore_setting: IgnoreSetting::default(), + is_library: false, + break_flow: false, + foreground_signals: Arc::new(ForegroundSignals::new()), + ignore_setting: IgnoreSetting::default(), } } @@ -135,22 +135,22 @@ impl<'a> Shell { /// Creates a new shell within memory. pub fn new() -> Shell { Shell { - builtins: BUILTINS, - context: None, - variables: Variables::default(), - flow_control: FlowControl::default(), - directory_stack: DirectoryStack::new(), - functions: FnvHashMap::default(), - previous_job: !0, - previous_status: 0, - flags: 0, - foreground: Vec::new(), - background: Arc::new(Mutex::new(Vec::new())), + builtins: BUILTINS, + context: None, + variables: Variables::default(), + flow_control: FlowControl::default(), + directory_stack: DirectoryStack::new(), + functions: FnvHashMap::default(), + previous_job: !0, + previous_status: 0, + flags: 0, + foreground: Vec::new(), + background: Arc::new(Mutex::new(Vec::new())), is_background_shell: false, - is_library: true, - break_flow: false, - foreground_signals: Arc::new(ForegroundSignals::new()), - ignore_setting: IgnoreSetting::default(), + is_library: true, + break_flow: false, + foreground_signals: Arc::new(ForegroundSignals::new()), + ignore_setting: IgnoreSetting::default(), } } @@ -293,8 +293,7 @@ impl<'a> Shell { eprintln!( "ion: function argument has invalid type: expected {}, found value \ \'{}\'", - expected_type, - value + expected_type, value ); Some(FAILURE) } @@ -335,14 +334,10 @@ impl<'a> Shell { /// Sets a variable of `name` with the given `value` in the shell's /// variable map. - pub fn set_var(&mut self, name: &str, value: &str) { - self.variables.set_var(name, value); - } + pub fn set_var(&mut self, name: &str, value: &str) { self.variables.set_var(name, value); } /// Gets a string variable, if it exists within the shell's variable map. - pub fn get_var(&self, name: &str) -> Option<String> { - self.variables.get_var(name) - } + pub fn get_var(&self, name: &str) -> Option<String> { self.variables.get_var(name) } /// Obtains a variable, returning an empty string if it does not exist. pub(crate) fn get_var_or_empty(&self, name: &str) -> String { @@ -459,9 +454,11 @@ impl<'a> Expander for Shell { if found.is_none() { found = match self.variables.get_map(array) { Some(map) => match selection { - Select::All => { - Some(map.iter().map(|(_, value)| value.clone()).collect::<Array>()) - } + Select::All => Some( + map.iter() + .map(|(_, value)| value.clone()) + .collect::<Array>(), + ), Select::Key(ref key) => { Some(array![map.get(key.get()).unwrap_or(&"".into()).clone()]) } diff --git a/src/shell/pipe_exec/foreground.rs b/src/shell/pipe_exec/foreground.rs index d69bcd46..ff76295d 100644 --- a/src/shell/pipe_exec/foreground.rs +++ b/src/shell/pipe_exec/foreground.rs @@ -15,23 +15,21 @@ const ERRORED: u8 = 2; /// structure to notify a background thread that it needs to wait for and return /// the exit status back to the `fg` function. pub(crate) struct ForegroundSignals { - grab: AtomicU32, + grab: AtomicU32, status: AtomicU8, - reply: AtomicU8, + reply: AtomicU8, } impl ForegroundSignals { pub(crate) fn new() -> ForegroundSignals { ForegroundSignals { - grab: AtomicU32::new(0), + grab: AtomicU32::new(0), status: AtomicU8::new(0), - reply: AtomicU8::new(0), + reply: AtomicU8::new(0), } } - pub(crate) fn signal_to_grab(&self, pid: u32) { - self.grab.store(pid, Ordering::Relaxed); - } + pub(crate) fn signal_to_grab(&self, pid: u32) { self.grab.store(pid, Ordering::Relaxed); } pub(crate) fn reply_with(&self, status: i8) { self.grab.store(0, Ordering::Relaxed); @@ -58,7 +56,5 @@ impl ForegroundSignals { } } - pub(crate) fn was_grabbed(&self, pid: u32) -> bool { - self.grab.load(Ordering::Relaxed) == pid - } + pub(crate) fn was_grabbed(&self, pid: u32) -> bool { self.grab.load(Ordering::Relaxed) == pid } } diff --git a/src/shell/pipe_exec/fork.rs b/src/shell/pipe_exec/fork.rs index 8b6fed4e..4b961626 100644 --- a/src/shell/pipe_exec/fork.rs +++ b/src/shell/pipe_exec/fork.rs @@ -1,9 +1,7 @@ use sys; /// Ensures that the forked child is given a unique process ID. -pub(crate) fn create_process_group(pgid: u32) { - let _ = sys::setpgid(0, pgid); -} +pub(crate) fn create_process_group(pgid: u32) { let _ = sys::setpgid(0, pgid); } use super::job_control::{JobControl, ProcessState}; use super::pipe; @@ -18,7 +16,7 @@ pub(crate) fn fork_pipe( shell: &mut Shell, commands: Vec<(RefinedJob, JobKind)>, command_name: String, - state: ProcessState + state: ProcessState, ) -> i32 { match unsafe { sys::fork() } { Ok(0) => { diff --git a/src/shell/pipe_exec/job_control.rs b/src/shell/pipe_exec/job_control.rs index aab408fe..e5fe69eb 100644 --- a/src/shell/pipe_exec/job_control.rs +++ b/src/shell/pipe_exec/job_control.rs @@ -77,20 +77,20 @@ pub(crate) fn add_to_background( { Some(id) => { (*processes)[id] = BackgroundProcess { - pid: pid, + pid: pid, ignore_sighup: false, - state: state, - name: command, + state: state, + name: command, }; id as u32 } None => { let njobs = (*processes).len(); (*processes).push(BackgroundProcess { - pid: pid, + pid: pid, ignore_sighup: false, - state: state, - name: command, + state: state, + name: command, }); njobs as u32 } @@ -103,10 +103,10 @@ pub(crate) fn add_to_background( /// as the process ID, state that the process is in, and the command that the /// process is executing. pub struct BackgroundProcess { - pub pid: u32, + pub pid: u32, pub ignore_sighup: bool, - pub state: ProcessState, - pub name: String, + pub state: ProcessState, + pub name: String, } impl JobControl for Shell { diff --git a/src/shell/pipe_exec/mod.rs b/src/shell/pipe_exec/mod.rs index 6f2856e0..8fb20e9f 100644 --- a/src/shell/pipe_exec/mod.rs +++ b/src/shell/pipe_exec/mod.rs @@ -225,7 +225,6 @@ fn do_redirection(piped_commands: Vec<RefinedItem>) -> Option<Vec<(RefinedJob, J }} } - // Real logic begins here let mut new_commands = Vec::new(); let mut prev_kind = JobKind::And; @@ -273,11 +272,11 @@ fn do_redirection(piped_commands: Vec<RefinedItem>) -> Option<Vec<(RefinedJob, J // tee both (true, true) => { let mut tee_out = TeeItem { - sinks: Vec::new(), + sinks: Vec::new(), source: None, }; let mut tee_err = TeeItem { - sinks: Vec::new(), + sinks: Vec::new(), source: None, }; for output in outputs { @@ -302,8 +301,7 @@ fn do_redirection(piped_commands: Vec<RefinedItem>) -> Option<Vec<(RefinedJob, J eprintln!( "ion: failed to redirect both stdout and stderr to file \ '{:?}': {}", - f, - e + f, e ); return None; } @@ -433,11 +431,16 @@ impl PipelineExecution for Shell { // If the given pipeline is a background task, fork the shell. if let Some((command_name, disown)) = possible_background_name { - fork_pipe(self, piped_commands, command_name, if disown { - ProcessState::Empty - } else { - ProcessState::Running - }) + fork_pipe( + self, + piped_commands, + command_name, + if disown { + ProcessState::Empty + } else { + ProcessState::Running + }, + ) } else { // While active, the SIGTTOU signal will be ignored. let _sig_ignore = SignalHandler::new(); @@ -502,9 +505,11 @@ impl PipelineExecution for Shell { pgid, last_pid, move || as_string, - move |pid| if let Some(id) = children.iter().position(|&x| x as i32 == pid) { - commands.remove(id); - children.remove(id); + move |pid| { + if let Some(id) = children.iter().position(|&x| x as i32 == pid) { + commands.remove(id); + children.remove(id); + } }, ) } @@ -629,8 +634,7 @@ impl PipelineExecution for Shell { Err(FunctionError::InvalidArgumentType(expected_type, value)) => { eprintln!( "ion: function argument has invalid type: expected {}, found value \'{}\'", - expected_type, - value + expected_type, value ); FAILURE } diff --git a/src/shell/plugins/library_iter/redox.rs b/src/shell/plugins/library_iter/redox.rs index 402b237b..61fed872 100644 --- a/src/shell/plugins/library_iter/redox.rs +++ b/src/shell/plugins/library_iter/redox.rs @@ -9,9 +9,7 @@ pub(crate) struct LibraryIterator { } impl LibraryIterator { - pub(crate) fn new(directory: ReadDir) -> LibraryIterator { - LibraryIterator { directory } - } + pub(crate) fn new(directory: ReadDir) -> LibraryIterator { LibraryIterator { directory } } } impl Iterator for LibraryIterator { @@ -19,7 +17,5 @@ impl Iterator for LibraryIterator { // The `Library` is a handle to dynamic library loaded into memory. type Item = (Identifier, Library); - fn next(&mut self) -> Option<(Identifier, Library)> { - None - } + fn next(&mut self) -> Option<(Identifier, Library)> { None } } diff --git a/src/shell/plugins/library_iter/unix.rs b/src/shell/plugins/library_iter/unix.rs index 17a313f8..79e9a37d 100644 --- a/src/shell/plugins/library_iter/unix.rs +++ b/src/shell/plugins/library_iter/unix.rs @@ -8,9 +8,7 @@ pub(crate) struct LibraryIterator { } impl LibraryIterator { - pub(crate) fn new(directory: ReadDir) -> LibraryIterator { - LibraryIterator { directory } - } + pub(crate) fn new(directory: ReadDir) -> LibraryIterator { LibraryIterator { directory } } } impl Iterator for LibraryIterator { diff --git a/src/shell/plugins/methods/redox.rs b/src/shell/plugins/methods/redox.rs index c082e7db..0f77cb0e 100644 --- a/src/shell/plugins/methods/redox.rs +++ b/src/shell/plugins/methods/redox.rs @@ -9,9 +9,7 @@ pub(crate) enum MethodArguments { pub(crate) struct StringMethodPlugins; impl StringMethodPlugins { - pub(crate) fn new() -> StringMethodPlugins { - StringMethodPlugins - } + pub(crate) fn new() -> StringMethodPlugins { StringMethodPlugins } pub(crate) fn execute( &self, @@ -26,6 +24,4 @@ impl StringMethodPlugins { /// /// This function is meant to be called with `lazy_static` to ensure that there isn't a /// cost to collecting all this information when the shell never uses it in the first place! -pub(crate) fn collect() -> StringMethodPlugins { - StringMethodPlugins::new() -} +pub(crate) fn collect() -> StringMethodPlugins { StringMethodPlugins::new() } diff --git a/src/shell/plugins/methods/unix.rs b/src/shell/plugins/methods/unix.rs index 3e7d5564..e365fb4c 100644 --- a/src/shell/plugins/methods/unix.rs +++ b/src/shell/plugins/methods/unix.rs @@ -15,11 +15,11 @@ use types::Identifier; /// corresponding field to `NULL`. Libraries importing this structure should check for nullness. #[repr(C)] pub(crate) struct RawMethodArguments { - key_ptr: *mut c_char, + key_ptr: *mut c_char, key_array_ptr: *mut *mut c_char, - args_ptr: *mut *mut c_char, - key_len: usize, - args_len: usize, + args_ptr: *mut *mut c_char, + key_len: usize, + args_len: usize, } pub(crate) enum MethodArguments { @@ -82,11 +82,11 @@ impl From<MethodArguments> for RawMethodArguments { } } MethodArguments::NoArgs => RawMethodArguments { - key_ptr: ptr::null_mut(), + key_ptr: ptr::null_mut(), key_array_ptr: ptr::null_mut(), - args_ptr: ptr::null_mut(), - key_len: 0, - args_len: 0, + args_ptr: ptr::null_mut(), + key_len: 0, + args_len: 0, }, } } @@ -112,7 +112,7 @@ impl StringMethodPlugins { pub(crate) fn new() -> StringMethodPlugins { StringMethodPlugins { libraries: Vec::new(), - symbols: FnvHashMap::default(), + symbols: FnvHashMap::default(), } } diff --git a/src/shell/plugins/namespaces/redox.rs b/src/shell/plugins/namespaces/redox.rs index 3f9fc050..480b69ce 100644 --- a/src/shell/plugins/namespaces/redox.rs +++ b/src/shell/plugins/namespaces/redox.rs @@ -6,9 +6,7 @@ use types::Identifier; pub(crate) struct StringNamespace; impl StringNamespace { - pub(crate) fn new() -> Result<StringNamespace, StringError> { - Ok(StringNamespace) - } + pub(crate) fn new() -> Result<StringNamespace, StringError> { Ok(StringNamespace) } pub(crate) fn execute(&self, _function: Identifier) -> Result<Option<String>, StringError> { Ok(None) diff --git a/src/shell/signals.rs b/src/shell/signals.rs index bbf8fde0..e5bf743b 100644 --- a/src/shell/signals.rs +++ b/src/shell/signals.rs @@ -15,14 +15,10 @@ pub const SIGHUP: u8 = 2; pub const SIGTERM: u8 = 4; /// Suspends a given process by it's process ID. -pub(crate) fn suspend(pid: u32) { - let _ = sys::killpg(pid, sys::SIGSTOP); -} +pub(crate) fn suspend(pid: u32) { let _ = sys::killpg(pid, sys::SIGSTOP); } /// Resumes a given process by it's process ID. -pub(crate) fn resume(pid: u32) { - let _ = sys::killpg(pid, sys::SIGCONT); -} +pub(crate) fn resume(pid: u32) { let _ = sys::killpg(pid, sys::SIGCONT); } /// The purpose of the signal handler is to ignore signals when it is active, and then continue /// listening to signals once the handler is dropped. @@ -36,7 +32,5 @@ impl SignalHandler { } impl Drop for SignalHandler { - fn drop(&mut self) { - unblock(); - } + fn drop(&mut self) { unblock(); } } diff --git a/src/shell/status.rs b/src/shell/status.rs index 6f99c27d..65d0b1ef 100644 --- a/src/shell/status.rs +++ b/src/shell/status.rs @@ -5,6 +5,4 @@ pub const COULD_NOT_EXEC: i32 = 126; pub const NO_SUCH_COMMAND: i32 = 127; pub const TERMINATED: i32 = 143; -pub fn get_signal_code(signal: i32) -> i32 { - 128 + signal -} +pub fn get_signal_code(signal: i32) -> i32 { 128 + signal } diff --git a/src/shell/variables/mod.rs b/src/shell/variables/mod.rs index 1ccecce4..26633b6a 100644 --- a/src/shell/variables/mod.rs +++ b/src/shell/variables/mod.rs @@ -6,10 +6,12 @@ use fnv::FnvHashMap; use liner::Context; use std::env; use std::io::{self, BufRead}; -use sys::variables as self_sys; use sys::{self, getpid, is_root}; -use types::{Array, ArrayVariableContext, HashMap, HashMapVariableContext, Identifier, Key, Value, - VariableContext}; +use sys::variables as self_sys; +use types::{ + Array, ArrayVariableContext, HashMap, HashMapVariableContext, Identifier, Key, Value, + VariableContext, +}; use unicode_segmentation::UnicodeSegmentation; use xdg::BaseDirectories; @@ -19,11 +21,11 @@ lazy_static! { #[derive(Clone, Debug)] pub struct Variables { - pub hashmaps: HashMapVariableContext, - pub arrays: ArrayVariableContext, + pub hashmaps: HashMapVariableContext, + pub arrays: ArrayVariableContext, pub variables: VariableContext, - pub aliases: VariableContext, - flags: u8, + pub aliases: VariableContext, + flags: u8, } impl Default for Variables { @@ -34,7 +36,10 @@ impl Default for Variables { map.insert("HISTFILE_SIZE".into(), "1000".into()); map.insert( "PROMPT".into(), - "${x::1B}]0;${USER}: ${PWD}${x::07}${c::0x55,bold}${USER}${c::default}:${c::0x4B}${SWD}${c::default}# ${c::reset}".into(), + "${x::1B}]0;${USER}: \ + ${PWD}${x::07}${c::0x55,bold}${USER}${c::default}:${c::0x4B}${SWD}${c::default}# \ + ${c::reset}" + .into(), ); // Set the PID variable to the PID of the shell let pid = getpid() @@ -62,11 +67,11 @@ impl Default for Variables { |path| env::set_var("HOME", path.to_str().unwrap_or("?")), ); Variables { - hashmaps: FnvHashMap::with_capacity_and_hasher(64, Default::default()), - arrays: FnvHashMap::with_capacity_and_hasher(64, Default::default()), + hashmaps: FnvHashMap::with_capacity_and_hasher(64, Default::default()), + arrays: FnvHashMap::with_capacity_and_hasher(64, Default::default()), variables: map, - aliases: FnvHashMap::with_capacity_and_hasher(64, Default::default()), - flags: 0, + aliases: FnvHashMap::with_capacity_and_hasher(64, Default::default()), + flags: 0, } } } @@ -74,17 +79,11 @@ impl Default for Variables { const PLUGIN: u8 = 1; impl Variables { - pub(crate) fn has_plugin_support(&self) -> bool { - self.flags & PLUGIN != 0 - } + pub(crate) fn has_plugin_support(&self) -> bool { self.flags & PLUGIN != 0 } - pub(crate) fn enable_plugins(&mut self) { - self.flags |= PLUGIN; - } + pub(crate) fn enable_plugins(&mut self) { self.flags |= PLUGIN; } - pub(crate) fn disable_plugins(&mut self) { - self.flags &= 255 ^ PLUGIN; - } + pub(crate) fn disable_plugins(&mut self) { self.flags &= 255 ^ PLUGIN; } pub(crate) fn read<I: IntoIterator>(&mut self, args: I) -> i32 where @@ -155,17 +154,11 @@ impl Variables { } } - pub fn get_map(&self, name: &str) -> Option<&HashMap> { - self.hashmaps.get(name) - } + pub fn get_map(&self, name: &str) -> Option<&HashMap> { self.hashmaps.get(name) } - pub fn get_array(&self, name: &str) -> Option<&Array> { - self.arrays.get(name) - } + pub fn get_array(&self, name: &str) -> Option<&Array> { self.arrays.get(name) } - pub fn unset_array(&mut self, name: &str) -> Option<Array> { - self.arrays.remove(name) - } + pub fn unset_array(&mut self, name: &str) -> Option<Array> { self.arrays.remove(name) } /// Obtains the value for the **SWD** variable. /// @@ -224,9 +217,7 @@ impl Variables { match name { "c" | "color" => Colors::collect(variable).into_string(), "x" | "hex" => match u8::from_str_radix(variable, 16) { - Ok(c) => { - Some((c as char).to_string()) - }, + Ok(c) => Some((c as char).to_string()), Err(why) => { eprintln!("ion: hex parse error: {}: {}", variable, why); None @@ -274,13 +265,9 @@ impl Variables { } } - pub fn get_var_or_empty(&self, name: &str) -> Value { - self.get_var(name).unwrap_or_default() - } + pub fn get_var_or_empty(&self, name: &str) -> Value { self.get_var(name).unwrap_or_default() } - pub fn unset_var(&mut self, name: &str) -> Option<Value> { - self.variables.remove(name) - } + pub fn unset_var(&mut self, name: &str) -> Option<Value> { self.variables.remove(name) } pub fn get_vars<'a>(&'a self) -> impl Iterator<Item = Identifier> + 'a { self.variables @@ -392,9 +379,7 @@ mod tests { struct VariableExpander(pub Variables); impl Expander for VariableExpander { - fn variable(&self, var: &str, _: bool) -> Option<Value> { - self.0.get_var(var) - } + fn variable(&self, var: &str, _: bool) -> Option<Value> { self.0.get_var(var) } } #[test] diff --git a/src/sys/redox.rs b/src/sys/redox.rs index 5e950ff1..3746becf 100644 --- a/src/sys/redox.rs +++ b/src/sys/redox.rs @@ -22,17 +22,11 @@ pub(crate) const STDIN_FILENO: RawFd = 0; pub(crate) const STDOUT_FILENO: RawFd = 1; pub(crate) const STDERR_FILENO: RawFd = 2; -pub(crate) fn is_root() -> bool { - syscall::geteuid().map(|id| id == 0).unwrap_or(false) -} +pub(crate) fn is_root() -> bool { syscall::geteuid().map(|id| id == 0).unwrap_or(false) } -pub unsafe fn fork() -> io::Result<u32> { - cvt(syscall::clone(0)).map(|pid| pid as u32) -} +pub unsafe fn fork() -> io::Result<u32> { cvt(syscall::clone(0)).map(|pid| pid as u32) } -pub(crate) fn getpid() -> io::Result<u32> { - cvt(syscall::getpid()).map(|pid| pid as u32) -} +pub(crate) fn getpid() -> io::Result<u32> { cvt(syscall::getpid()).map(|pid| pid as u32) } pub(crate) fn kill(pid: u32, signal: i32) -> io::Result<()> { cvt(syscall::kill(pid as usize, signal as usize)).and(Ok(())) @@ -105,8 +99,8 @@ pub(crate) fn execve(prog: &str, args: &[&str], clear_env: bool) -> io::Result<( pub(crate) fn signal(signal: i32, handler: extern "C" fn(i32)) -> io::Result<()> { let new = SigAction { sa_handler: unsafe { mem::transmute(handler) }, - sa_mask: [0; 2], - sa_flags: 0, + sa_mask: [0; 2], + sa_flags: 0, }; cvt(syscall::sigaction(signal as usize, Some(&new), None)).and(Ok(())) } @@ -114,8 +108,8 @@ pub(crate) fn signal(signal: i32, handler: extern "C" fn(i32)) -> io::Result<()> pub(crate) fn reset_signal(signal: i32) -> io::Result<()> { let new = SigAction { sa_handler: unsafe { mem::transmute(syscall::flag::SIG_DFL) }, - sa_mask: [0; 2], - sa_flags: 0, + sa_mask: [0; 2], + sa_flags: 0, }; cvt(syscall::sigaction(signal as usize, Some(&new), None)).and(Ok(())) } @@ -136,17 +130,13 @@ pub(crate) fn tcsetpgrp(tty_fd: RawFd, pgid: u32) -> io::Result<()> { cvt(res).and(Ok(())) } -pub(crate) fn dup(fd: RawFd) -> io::Result<RawFd> { - cvt(syscall::dup(fd, &[])) -} +pub(crate) fn dup(fd: RawFd) -> io::Result<RawFd> { cvt(syscall::dup(fd, &[])) } pub(crate) fn dup2(old: RawFd, new: RawFd) -> io::Result<RawFd> { cvt(syscall::dup2(old, new, &[])) } -pub(crate) fn close(fd: RawFd) -> io::Result<()> { - cvt(syscall::close(fd)).and(Ok(())) -} +pub(crate) fn close(fd: RawFd) -> io::Result<()> { cvt(syscall::close(fd)).and(Ok(())) } pub(crate) fn isatty(fd: RawFd) -> bool { if let Ok(tfd) = syscall::dup(fd, b"termios") { @@ -192,7 +182,6 @@ pub mod job_control { // TODO: Implement this using syscall::call::waitpid } - pub(crate) fn watch_foreground<F, D>( shell: &mut Shell, _pid: u32, diff --git a/src/sys/unix/mod.rs b/src/sys/unix/mod.rs index 5a2e0c18..28ff14ea 100644 --- a/src/sys/unix/mod.rs +++ b/src/sys/unix/mod.rs @@ -23,17 +23,11 @@ pub(crate) const STDOUT_FILENO: i32 = libc::STDOUT_FILENO; pub(crate) const STDERR_FILENO: i32 = libc::STDERR_FILENO; pub(crate) const STDIN_FILENO: i32 = libc::STDIN_FILENO; -pub(crate) fn is_root() -> bool { - unsafe { libc::geteuid() == 0 } -} +pub(crate) fn is_root() -> bool { unsafe { libc::geteuid() == 0 } } -pub unsafe fn fork() -> io::Result<u32> { - cvt(libc::fork()).map(|pid| pid as u32) -} +pub unsafe fn fork() -> io::Result<u32> { cvt(libc::fork()).map(|pid| pid as u32) } -pub(crate) fn getpid() -> io::Result<u32> { - cvt(unsafe { libc::getpid() }).map(|pid| pid as u32) -} +pub(crate) fn getpid() -> io::Result<u32> { cvt(unsafe { libc::getpid() }).map(|pid| pid as u32) } pub(crate) fn kill(pid: u32, signal: i32) -> io::Result<()> { cvt(unsafe { libc::kill(pid as pid_t, signal as c_int) }).and(Ok(())) @@ -47,7 +41,9 @@ pub(crate) fn execve(prog: &str, args: &[&str], clear_env: bool) -> io::Result<( // Prepare the program string let prog_str = match CString::new(prog) { Ok(prog_str) => prog_str, - Err(_) => { return Err(io::Error::last_os_error()); } + Err(_) => { + return Err(io::Error::last_os_error()); + } }; // Create the arguments vector @@ -154,21 +150,15 @@ pub(crate) fn tcsetpgrp(fd: RawFd, pgrp: u32) -> io::Result<()> { cvt(unsafe { libc::tcsetpgrp(fd as c_int, pgrp as pid_t) }).and(Ok(())) } -pub(crate) fn dup(fd: RawFd) -> io::Result<RawFd> { - cvt(unsafe { libc::dup(fd) }) -} +pub(crate) fn dup(fd: RawFd) -> io::Result<RawFd> { cvt(unsafe { libc::dup(fd) }) } pub(crate) fn dup2(old: RawFd, new: RawFd) -> io::Result<RawFd> { cvt(unsafe { libc::dup2(old, new) }) } -pub(crate) fn close(fd: RawFd) -> io::Result<()> { - cvt(unsafe { libc::close(fd) }).and(Ok(())) -} +pub(crate) fn close(fd: RawFd) -> io::Result<()> { cvt(unsafe { libc::close(fd) }).and(Ok(())) } -pub(crate) fn isatty(fd: RawFd) -> bool { - unsafe { libc::isatty(fd) == 1 } -} +pub(crate) fn isatty(fd: RawFd) -> bool { unsafe { libc::isatty(fd) == 1 } } trait IsMinusOne { fn is_minus_one(&self) -> bool; -- GitLab