Commit 1b81f39f authored by Thomas Kinnen's avatar Thomas Kinnen
Browse files

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.
parent 7cb16bc3
......@@ -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 {
......
......@@ -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);
......
......@@ -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
......
......@@ -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) {
......
......@@ -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,
}
}
......
......@@ -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
......
......@@ -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.
......
......@@ -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 ]";
......
......@@ -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
......
......@@ -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>> {
......
......@@ -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 {
......
......@@ -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]
......
......@@ -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,
},
],
......
......@@ -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));
......
......@@ -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 }
}
......@@ -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