Commit a61f0ec9 authored by Michael Aaron Murphy's avatar Michael Aaron Murphy
Browse files

Further rustfmt improvements

parent 4b90fbc0
......@@ -7,7 +7,7 @@ use version_check::is_nightly;
// Specifies the minimum version needed to compile Ion.
// NOTE: 1.19 is required due to the usage of `break` with values for
// `loop` (RFC 1624, rust-lang/rust GitHub issue #37339).
//const MIN_VERSION: &'static str = "1.19.0";
// const MIN_VERSION: &'static str = "1.19.0";
use std::env;
use std::fs::File;
......@@ -43,7 +43,7 @@ fn main() {
Red.bold().paint("Error:"),
White.paint("Ion requires nighlty to build.")
);
//print_version_err(&*version_string);
// print_version_err(&*version_string);
printerr!(
"{}{}{}",
Blue.paint("Use `"),
......
chain_one_line_max = 100
comment_width = 100
condense_wildcard_suffixes = true
error_on_line_overflow = false
fn_call_width = 80
fn_call_width = 100
fn_single_line = true
format_strings = true
imports_indent = "Block"
match_pattern_separator_break_point = "Front"
max_width = 100
normalize_comments = true
reorder_imported_names = true
reorder_imports = true
reorder_imports_in_group = true
single_line_if_else_max_width = 80
single_line_if_else_max_width = 100
struct_field_align_threshold = 30
trailing_semicolon = false
where_style = "legacy"
wrap_comments = true
write_mode = "overwrite"
......@@ -24,10 +24,7 @@ impl AsciiReplaceInPlace for str {
// I tried replacing these `assert!` calls with `debug_assert!` but it looks
// like they get const-folded away anyway since it doesn't affect the speed
fn ascii_replace_in_place(&mut self, needle: char, haystack: char) {
assert!(
needle.is_ascii(),
"AsciiReplace functions can only be used for ascii characters"
);
assert!(needle.is_ascii(), "AsciiReplace functions can only be used for ascii characters");
assert!(
haystack.is_ascii(),
"AsciiReplace functions can only be used for ascii characters"
......
......@@ -24,7 +24,7 @@ pub fn calc(args: &[&str]) -> Result<(), String> {
let mut input = String::new();
let _ = io::stdin().read_line(&mut input);
if input.is_empty() {
break
break;
} else {
match input.trim() {
"" => (),
......
......@@ -39,7 +39,7 @@ OPTIONS
\r carriage return
\t horizontal tab (HT)
\v vertical tab (VT)
"#; /* @MANEND */
"#; // @MANEND
pub fn echo(args: &[&str]) -> Result<(), io::Error> {
let mut flags = Flags::empty();
......@@ -63,7 +63,7 @@ pub fn echo(args: &[&str]) -> Result<(), io::Error> {
'h' => short_flags |= HELP,
_ => {
is_opts = false;
break
break;
}
}
}
......@@ -84,7 +84,7 @@ pub fn echo(args: &[&str]) -> Result<(), io::Error> {
if flags.contains(HELP) {
buffer.write_all(MAN_PAGE.as_bytes())?;
buffer.flush()?;
return Ok(())
return Ok(());
}
let mut first = true;
......@@ -114,7 +114,7 @@ pub fn echo(args: &[&str]) -> Result<(), io::Error> {
}
b'c' if check => {
buffer.flush()?;
return Ok(())
return Ok(());
}
b'e' if check => {
buffer.write_all(&[27u8])?; // escape
......
......@@ -68,7 +68,7 @@ EXAMPLES
AUTHOR
Written by Fabian Würfl.
Heavily based on implementation of the test builtin, which was written by Michael Murph.
"#; /* @MANEND */
"#; // @MANEND
pub fn exists(args: &[&str], shell: &Shell) -> Result<bool, String> {
let stdout = io::stdout();
......@@ -86,9 +86,7 @@ fn evaluate_arguments<W: io::Write>(
match arguments.first() {
Some(&"--help") => {
// not handled by the second case, so that we don't have to pass the buffer around
buffer
.write_all(MAN_PAGE.as_bytes())
.map_err(|x| x.description().to_owned())?;
buffer.write_all(MAN_PAGE.as_bytes()).map_err(|x| x.description().to_owned())?;
buffer.flush().map_err(|x| x.description().to_owned())?;
Ok(true)
}
......@@ -143,16 +141,12 @@ fn match_option_argument(option: &str, argument: &str, shell: &Shell) -> bool {
/// Returns true if the file is a regular file
fn path_is_file(filepath: &str) -> bool {
fs::metadata(filepath)
.ok()
.map_or(false, |metadata| metadata.file_type().is_file())
fs::metadata(filepath).ok().map_or(false, |metadata| metadata.file_type().is_file())
}
/// Returns true if the file is a directory
fn path_is_directory(filepath: &str) -> bool {
fs::metadata(filepath)
.ok()
.map_or(false, |metadata| metadata.file_type().is_dir())
fs::metadata(filepath).ok().map_or(false, |metadata| metadata.file_type().is_dir())
}
/// Returns true if the binary is found in path (and is executable)
......@@ -166,7 +160,7 @@ fn binary_is_in_path(binaryname: &str, shell: &Shell) -> bool {
let fname = format!("{}/{}", dir, binaryname);
if let Ok(metadata) = fs::metadata(&fname) {
if metadata.is_file() && file_has_execute_permission(&fname) {
return true
return true;
}
}
}
......@@ -246,9 +240,7 @@ fn test_evaluate_arguments() {
// check `exists -a`
// no argument means we treat it as a string
assert_eq!(evaluate_arguments(&["-a"], &mut sink, &shell), Ok(true));
shell
.variables
.set_array("emptyarray", SmallVec::from_vec(Vec::new()));
shell.variables.set_array("emptyarray", SmallVec::from_vec(Vec::new()));
assert_eq!(evaluate_arguments(&["-a", "emptyarray"], &mut sink, &shell), Ok(false));
let mut vec = Vec::new();
vec.push("element".to_owned());
......@@ -261,10 +253,7 @@ fn test_evaluate_arguments() {
// TODO: see test_binary_is_in_path()
// no argument means we treat it as a string
assert_eq!(evaluate_arguments(&["-b"], &mut sink, &shell), Ok(true));
let oldpath = shell
.variables
.get_var("PATH")
.unwrap_or("/usr/bin".to_owned());
let oldpath = shell.variables.get_var("PATH").unwrap_or("/usr/bin".to_owned());
shell.variables.set_var("PATH", "testing/");
assert_eq!(evaluate_arguments(&["-b", "executable_file"], &mut sink, &shell), Ok(true));
......@@ -342,10 +331,7 @@ fn test_match_flag_argument() {
let shell = Shell::new(&builtins);
// we don't really care about the passed values, as long as both sited return the same value
assert_eq!(
match_flag_argument('a', "ARRAY", &shell),
array_var_is_not_empty("ARRAY", &shell)
);
assert_eq!(match_flag_argument('a', "ARRAY", &shell), array_var_is_not_empty("ARRAY", &shell));
assert_eq!(match_flag_argument('b', "binary", &shell), binary_is_in_path("binary", &shell));
assert_eq!(match_flag_argument('d', "path", &shell), path_is_directory("path"));
assert_eq!(match_flag_argument('f', "file", &shell), path_is_file("file"));
......@@ -361,10 +347,7 @@ fn test_match_option_argument() {
let shell = Shell::new(&builtins);
// we don't really care about the passed values, as long as both sited return the same value
assert_eq!(
match_option_argument("fn", "FUN", &shell),
array_var_is_not_empty("FUN", &shell)
);
assert_eq!(match_option_argument("fn", "FUN", &shell), array_var_is_not_empty("FUN", &shell));
// Any option which is not implemented
assert_eq!(match_option_argument("foo", "ARG", &shell), false);
......@@ -419,16 +402,12 @@ fn test_array_var_is_not_empty() {
let builtins = Builtin::map();
let mut shell = Shell::new(&builtins);
shell
.variables
.set_array("EMPTY_ARRAY", SmallVec::from_vec(Vec::new()));
shell.variables.set_array("EMPTY_ARRAY", SmallVec::from_vec(Vec::new()));
assert_eq!(array_var_is_not_empty("EMPTY_ARRAY", &shell), false);
let mut not_empty_vec = Vec::new();
not_empty_vec.push("array not empty".to_owned());
shell
.variables
.set_array("NOT_EMPTY_ARRAY", SmallVec::from_vec(not_empty_vec));
shell.variables.set_array("NOT_EMPTY_ARRAY", SmallVec::from_vec(not_empty_vec));
assert_eq!(array_var_is_not_empty("NOT_EMPTY_ARRAY", &shell), true);
// test for array which does not even exist
......@@ -454,9 +433,7 @@ fn test_string_var_is_not_empty() {
// string_var_is_not_empty should NOT match for arrays with the same name
let mut vec = Vec::new();
vec.push("not-empty".to_owned());
shell
.variables
.set_array("ARRAY_NOT_EMPTY", SmallVec::from_vec(vec));
shell.variables.set_array("ARRAY_NOT_EMPTY", SmallVec::from_vec(vec));
assert_eq!(string_var_is_not_empty("ARRAY_NOT_EMPTY", &shell), false);
// test for a variable which does not even exist
......
......@@ -9,12 +9,12 @@ const DOCPATH: &str = "/usr/share/ion/docs/index.html";
pub fn ion_docs(_: &[&str], shell: &mut Shell) -> i32 {
if !Path::new(DOCPATH).exists() {
eprintln!("ion: ion shell documentation is not installed");
return FAILURE
return FAILURE;
}
if let Some(cmd) = shell.variables.get_var("BROWSER".into()) {
if let Ok(_) = Command::new(&cmd).arg(DOCPATH).spawn() {
return SUCCESS
return SUCCESS;
}
} else {
eprintln!("ion: BROWSER variable isn't defined");
......
......@@ -7,7 +7,8 @@ use shell::status::*;
use std::io::{stderr, Write};
/// Disowns given process job IDs, and optionally marks jobs to not receive SIGHUP signals.
/// The `-a` flag selects all jobs, `-r` selects all running jobs, and `-h` specifies to mark SIGHUP ignoral.
/// The `-a` flag selects all jobs, `-r` selects all running jobs, and `-h` specifies to mark
/// SIGHUP ignoral.
pub fn disown(shell: &mut Shell, args: &[&str]) -> i32 {
let stderr = stderr();
let mut stderr = stderr.lock();
......@@ -26,7 +27,7 @@ pub fn disown(shell: &mut Shell, args: &[&str]) -> i32 {
Ok(jobspec) => jobspecs.push(jobspec),
Err(_) => {
let _ = writeln!(stderr, "ion: disown: invalid jobspec: '{}'", arg);
return FAILURE
return FAILURE;
}
},
}
......@@ -96,7 +97,7 @@ pub fn fg(shell: &mut Shell, args: &[&str]) -> i32 {
} else {
let stderr = stderr();
let _ = writeln!(stderr.lock(), "ion: fg: job {} does not exist", njob);
return FAILURE
return FAILURE;
}
// Bring the process into the foreground and wait for it to finish.
......@@ -141,27 +142,21 @@ pub fn fg(shell: &mut Shell, args: &[&str]) -> i32 {
/// Resumes a stopped background process, if it was stopped.
pub fn bg(shell: &mut Shell, args: &[&str]) -> i32 {
fn bg_job(shell: &mut Shell, njob: u32) -> bool {
if let Some(job) = shell
.background
.lock()
.unwrap()
.iter_mut()
.nth(njob as usize)
{
if let Some(job) = shell.background.lock().unwrap().iter_mut().nth(njob as usize) {
match job.state {
ProcessState::Running => {
eprintln!("ion: bg: job {} is already running", njob);
return true
return true;
}
ProcessState::Stopped => signals::resume(job.pid),
ProcessState::Empty => {
eprintln!("ion: bg: job {} does not exist", njob);
return true
return true;
}
}
} else {
eprintln!("ion: bg: job {} does not exist", njob);
return true
return true;
}
false
}
......
......@@ -45,21 +45,21 @@ impl Builtin {
let mut commands: FnvHashMap<&str, Self> =
FnvHashMap::with_capacity_and_hasher(32, Default::default());
/*
Quick and clean way to insert a builtin, define a function named as the builtin
for example:
fn builtin_not (args: &[&str], shell: &mut Shell) -> i32 {
let cmd = args[1..].join(" ");
shell.on_command(&cmd);
match shell.previous_status {
SUCCESS => FAILURE,
FAILURE => SUCCESS,
_ => shell.previous_status
}
}
insert_builtin!("not", builtin_not, "Reverses the exit status value of the given command.");
*/
// Quick and clean way to insert a builtin, define a function named as the builtin
// for example:
// fn builtin_not (args: &[&str], shell: &mut Shell) -> i32 {
// let cmd = args[1..].join(" ");
// shell.on_command(&cmd);
// match shell.previous_status {
// SUCCESS => FAILURE,
// FAILURE => SUCCESS,
// _ => shell.previous_status
// }
// }
//
// insert_builtin!("not", builtin_not, "Reverses the exit status value of the given
// command.");
//
macro_rules! insert_builtin {
($name:expr, $func:ident, $help:expr) => {
......@@ -74,23 +74,23 @@ impl Builtin {
}
}
/* Directories */
// Directories
insert_builtin!("cd", builtin_cd, "Change the current directory\n cd <path>");
insert_builtin!("dirs", builtin_dirs, "Display the current directory stack");
insert_builtin!("pushd", builtin_pushd, "Push a directory to the stack");
insert_builtin!("popd", builtin_popd, "Pop a directory from the stack");
/* Aliases */
// Aliases
insert_builtin!("alias", builtin_alias, "View, set or unset aliases");
insert_builtin!("unalias", builtin_unalias, "Delete an alias");
/* Variables */
// Variables
insert_builtin!("fn", builtin_fn, "Print list of functions");
insert_builtin!("read", builtin_read, "Read some variables\n read <variable>");
insert_builtin!("drop", builtin_drop, "Delete a variable");
/* Misc */
// Misc
insert_builtin!("matches", builtin_matches, "Checks if a string matches a given regex");
insert_builtin!("not", builtin_not, "Reverses the exit status value of the given command.");
insert_builtin!(
......@@ -140,7 +140,8 @@ impl Builtin {
insert_builtin!(
"help",
builtin_help,
"Display helpful information about a given command or list commands if none specified\n help <command>"
"Display helpful information about a given command or list commands if none \
specified\n help <command>"
);
insert_builtin!(
"and",
......@@ -174,7 +175,7 @@ impl Builtin {
}
}
/* Definitions of simple builtins go here */
// Definitions of simple builtins go here
fn builtin_cd(args: &[&str], shell: &mut Shell) -> i32 {
match shell.directory_stack.cd(args, &shell.variables) {
......@@ -372,11 +373,7 @@ fn builtin_exit(args: &[&str], shell: &mut Shell) -> i32 {
}
}
let previous_status = shell.previous_status;
shell.exit(
args.get(1)
.and_then(|status| status.parse::<i32>().ok())
.unwrap_or(previous_status),
)
shell.exit(args.get(1).and_then(|status| status.parse::<i32>().ok()).unwrap_or(previous_status))
}
use regex::Regex;
......@@ -385,7 +382,7 @@ fn builtin_matches(args: &[&str], _: &mut Shell) -> i32 {
let stderr = io::stderr();
let mut stderr = stderr.lock();
let _ = stderr.write_all(b"match takes two arguments\n");
return BAD_ARG
return BAD_ARG;
}
let input = args[1];
let re = match Regex::new(args[2]) {
......@@ -395,7 +392,7 @@ fn builtin_matches(args: &[&str], _: &mut Shell) -> i32 {
let mut stderr = stderr.lock();
let _ = stderr
.write_all(format!("couldn't compile input regex {}: {}\n", args[2], e).as_bytes());
return FAILURE
return FAILURE;
}
};
......
......@@ -45,18 +45,18 @@ pub fn set(args: &[&str], shell: &mut Shell) -> i32 {
if arg.starts_with("--") {
if arg.len() == 2 {
positionals = Some(UnsetIfNone);
break
break;
}
if &arg[2..] == "help" {
let mut stdout = stdout.lock();
let _ = stdout.write(HELP.as_bytes());
} else {
return 0
return 0;
}
} else if arg.starts_with('-') {
if arg.len() == 1 {
positionals = Some(RetainIfNone);
break
break;
}
for flag in arg.bytes().skip(1) {
match flag {
......@@ -74,11 +74,11 @@ pub fn set(args: &[&str], shell: &mut Shell) -> i32 {
}
Some(_) => {
let _ = stderr.lock().write_all(b"set: invalid keymap\n");
return 0
return 0;
}
None => {
let _ = stderr.lock().write_all(b"set: no keymap given\n");
return 0
return 0;
}
},
b'x' => shell.flags |= PRINT_COMMS,
......@@ -103,9 +103,7 @@ pub fn set(args: &[&str], shell: &mut Shell) -> i32 {
// This used to take a `&[String]` but cloned them all, so although
// this is non-ideal and could probably be better done with `Rc`, it
// hasn't got any slower.
let arguments = iter::once(command)
.chain(args_iter.map(|i| i.to_string()))
.collect();
let arguments = iter::once(command).chain(args_iter.map(|i| i.to_string())).collect();
match kind {
UnsetIfNone => shell.variables.set_array("args", arguments),
RetainIfNone => if arguments.len() != 1 {
......
......@@ -109,7 +109,7 @@ EXAMPLES
AUTHOR
Written by Michael Murphy.
"#; /* @MANEND */
"#; // @MANEND
pub fn test(args: &[&str]) -> Result<bool, String> {
let stdout = io::stdout();
......@@ -122,9 +122,7 @@ pub fn test(args: &[&str]) -> Result<bool, String> {
fn evaluate_arguments<W: io::Write>(arguments: &[&str], buffer: &mut W) -> Result<bool, String> {
match arguments.first() {
Some(&"--help") => {
buffer
.write_all(MAN_PAGE.as_bytes())
.map_err(|x| x.description().to_owned())?;
buffer.write_all(MAN_PAGE.as_bytes()).map_err(|x| x.description().to_owned())?;
buffer.flush().map_err(|x| x.description().to_owned())?;
Ok(true)
}
......@@ -142,15 +140,13 @@ fn evaluate_arguments<W: io::Write>(arguments: &[&str], buffer: &mut W) -> Resul
}
Some(arg) => {
// If there is no operator, check if the first argument is non-zero
arguments
.get(1)
.map_or(Ok(string_is_nonzero(arg)), |operator| {
// If there is no right hand argument, a condition was expected
let right_arg = arguments
.get(2)
.ok_or_else(|| SmallString::from("parse error: condition expected"))?;
evaluate_expression(arg, operator, right_arg)
})
arguments.get(1).map_or(Ok(string_is_nonzero(arg)), |operator| {
// If there is no right hand argument, a condition was expected
let right_arg = arguments
.get(2)
.ok_or_else(|| SmallString::from("parse error: condition expected"))?;
evaluate_expression(arg, operator, right_arg)
})
}
None => Ok(false),
}
......@@ -192,9 +188,7 @@ fn files_have_same_device_and_inode_numbers(first: &str, second: &str) -> bool {
/// Obtains the device and inode numbers of the file specified
fn get_dev_and_inode(filename: &str) -> Option<(u64, u64)> {
fs::metadata(filename)
.map(|file| (file.dev(), file.ino()))
.ok()
fs::metadata(filename).map(|file| (file.dev(), file.ino())).ok()
}
/// Exits SUCCESS if the first file is newer than the second file.
......@@ -211,9 +205,7 @@ fn file_is_newer_than(first: &str, second: &str) -> bool {
/// Obtain the time the file was last modified as a `SystemTime` type.
fn get_modified_file_time(filename: &str) -> Option<SystemTime> {
fs::metadata(filename)
.ok()
.and_then(|file| file.modified().ok())
fs::metadata(filename).ok().and_then(|file| file.modified().ok())
}
/// Attempt to parse a &str as a usize.
......@@ -244,11 +236,11 @@ fn match_flag_argument(flag: char, argument: &str) -> bool {
'e' => file_exists(argument),
'f' => file_is_regular(argument),
//'g' => file_is_set_group_id(argument),
//'G' => file_is_owned_by_effective_group_id(argument),
// 'G' => file_is_owned_by_effective_group_id(argument),
'h' | 'L' => file_is_symlink(argument),
//'k' => file_has_sticky_bit(argument),
//'O' => file_is_owned_by_effective_user_id(argument),
//'p' => file_is_named_pipe(argument),
// 'O' => file_is_owned_by_effective_user_id(argument),
// 'p' => file_is_named_pipe(argument),
'r' => file_has_read_permission(argument),
's' => file_size_is_greater_than_zero(argument),
'S' => file_is_socket(argument),
......@@ -263,9 +255,7 @@ fn match_flag_argument(flag: char, argument: &str) -> bool {
/// Exits SUCCESS if the file size is greather than zero.
fn file_size_is_greater_than_zero(filepath: &str) -> bool {
fs::metadata(filepath)
.ok()
.map_or(false, |metadata| metadata.len() > 0)
fs::metadata(filepath).ok().map_or(false, |metadata| metadata.len() > 0)
}
/// Exits SUCCESS if the file has read permissions. This function is rather low level because
......@@ -317,23 +307,17 @@ fn file_has_execute_permission(filepath: &str) -> bool {
/// Exits SUCCESS if the file argument is a socket
fn file_is_socket(filepath: &str) -> bool {
fs::metadata(filepath)
.ok()
.map_or(false, |metadata| metadata.file_type().is_socket())
fs::metadata(filepath).ok().map_or(false, |metadata| metadata.file_type().is_socket())
}
/// Exits SUCCESS if the file argument is a block device
fn file_is_block_device(filepath: &str) -> bool {
fs::metadata(filepath)
.ok()
.map_or(false, |metadata| metadata.file_type().is_block_device())
fs::metadata(filepath).ok().map_or(false, |metadata| metadata.file_type().is_block_device())
}
/// Exits SUCCESS if the file argument is a character device
fn file_is_character_device(filepath: &str) -> bool {
fs::metadata(filepath)
.ok()
.map_or(false, |metadata| metadata.file_type().is_char_device())
fs::metadata(filepath).ok().map_or(false, |metadata| metadata.file_type().is_char_device())
}
/// Exits SUCCESS if the file exists
......@@ -341,23 +325,17 @@ 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 {
fs::metadata(filepath)
.ok()
.map_or(false, |metadata| metadata.file_type().is_file())
fs::metadata(filepath).ok().map_or(false, |metadata| metadata.file_type().is_file())
}
/// Exits SUCCESS if the file is a directory
fn file_is_directory(filepath: &str) -> bool {
fs::metadata(filepath)
.ok()
.map_or(false, |metadata| metadata.file_type().is_dir())
fs::metadata(filepath).ok().map_or(false, |metadata| metadata.file_type().is_dir())
}
/// Exits SUCCESS if the file is a symbolic link
fn file_is_symlink(filepath: &str) -> bool {
fs::symlink_metadata(filepath)
.ok()
.map_or(false, |metadata| metadata.file_type().is_symlink())
fs::symlink_metadata(filepath).ok().map_or(false, |metadata| metadata.file_type().is_symlink())
}
/// Exits SUCCESS if the string is not empty
......
......@@ -56,32 +56,32 @@ fn parse_alias(args: &str) -> Binding {
operator = Some(Operator::Plus);
found_key = true;
}
break
break;
}
'-' => {
if char_iter.next() == Some('=') {
operator = Some(Operator::Minus);
found_key = true;
}
break
break;
}
'*' => {
if char_iter.next() == Some('=') {
operator = Some(Operator::Multiply);
found_key = true;
}
break
break;
}