Skip to content

Commit

Permalink
refactored cmd_rediraction, using match instead of if else
Browse files Browse the repository at this point in the history
  • Loading branch information
bexxmodd committed Jul 22, 2021
1 parent 0007c3f commit 3e5f47f
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 31 deletions.
55 changes: 26 additions & 29 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,36 +181,33 @@ pub fn redirect_cmd_execution(cmd_line: &mut Tokenizer) -> Result<process::Comma
proc.args(&args[1..]);

loop {
if cmd_line.peek().eq("<") {
assert_eq!("<".to_string(), cmd_line.next().unwrap());
redirection_count[0] += 1;

// retrieve file name if file/directory doesn't
// exist notify user and restart the shell
if let Some(name) = cmd_line.next() {
// redirect stdin from a given file
match open_stdin_file(&name) {
Ok(f) => proc.stdin(f),
Err(e) => return Err(e),
};
};
}

if cmd_line.peek().eq(">") {
assert_eq!(">".to_string(), cmd_line.next().unwrap());
redirection_count[1] += 1;

// redirect stdout to a give file
if let Some(name) = cmd_line.next() {
match open_stdout_file(&name) {
Ok(f) => proc.stdout(f),
Err(e) => return Err(e),
};
match cmd_line.next().as_deref() {
Some("<") => {
redirection_count[0] += 1;

// retrieve file name if file/directory doesn't
// exist notify user and restart the shell
if let Some(name) = cmd_line.next() {
// redirect stdin from a given file
match open_stdin_file(&name) {
Ok(f) => proc.stdin(f),
Err(e) => return Err(e),
};
}
}
}

if cmd_line.peek().is_empty() {
break;
Some(">") => {
redirection_count[1] += 1;

// redirect stdout to a give file
if let Some(name) = cmd_line.next() {
match open_stdout_file(&name) {
Ok(f) => proc.stdout(f),
Err(e) => return Err(e),
};
}
},
None => break,
_ => continue,
}
}

Expand Down
10 changes: 8 additions & 2 deletions src/tokenizer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,6 @@ impl Tokenizer {
if let Some(cur) = self.current.clone() {
let mut vals = cur.split(' ');
res = vals.next().unwrap().to_string()

}
res
}
Expand All @@ -114,6 +113,10 @@ impl Tokenizer {
}
Tokenizer::new(&before)
}

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

impl Iterator for Tokenizer {
Expand All @@ -124,13 +127,16 @@ impl Iterator for Tokenizer {
let mut split: Vec<_> = s.split(' ').collect();
let nxt = split.remove(0).to_string();

// check if strings are left in the vector
// if yes build string back and store in current
if split.is_empty() {
self.current = None;
} else {
self.current = Some(split.join(" "));
}

if nxt.is_empty() {
if nxt.len() < 1 {
self.current = None;
None
} else {
Some(nxt)
Expand Down

0 comments on commit 3e5f47f

Please sign in to comment.