2019-05-26 02:04:13 +00:00
|
|
|
use crate::errors::ShellError;
|
|
|
|
use crate::object::dict::Dictionary;
|
|
|
|
use crate::object::Value;
|
|
|
|
use crate::prelude::*;
|
|
|
|
use std::fs::File;
|
|
|
|
use std::io::prelude::*;
|
|
|
|
|
|
|
|
pub fn size(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
2019-06-01 05:50:16 +00:00
|
|
|
if args.positional.is_empty() {
|
2019-05-26 02:04:13 +00:00
|
|
|
return Err(ShellError::string("size requires at least one file"));
|
|
|
|
}
|
2019-06-13 21:47:25 +00:00
|
|
|
let cwd = args
|
|
|
|
.env
|
|
|
|
.lock()
|
|
|
|
.unwrap()
|
|
|
|
.first()
|
|
|
|
.unwrap()
|
|
|
|
.path()
|
|
|
|
.to_path_buf();
|
2019-05-26 02:04:13 +00:00
|
|
|
|
|
|
|
let mut contents = String::new();
|
|
|
|
|
|
|
|
let mut list = VecDeque::new();
|
2019-06-01 05:50:16 +00:00
|
|
|
for name in args.positional {
|
2019-05-26 02:04:13 +00:00
|
|
|
let name = name.as_string()?;
|
|
|
|
let path = cwd.join(&name);
|
|
|
|
let mut file = File::open(path)?;
|
|
|
|
file.read_to_string(&mut contents)?;
|
2019-05-26 22:38:26 +00:00
|
|
|
list.push_back(count(&name, &contents));
|
2019-05-26 02:04:13 +00:00
|
|
|
contents.clear();
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(list.boxed())
|
|
|
|
}
|
|
|
|
|
2019-05-26 22:38:26 +00:00
|
|
|
fn count(name: &str, contents: &str) -> ReturnValue {
|
2019-05-26 02:04:13 +00:00
|
|
|
let mut lines: i64 = 0;
|
|
|
|
let mut words: i64 = 0;
|
|
|
|
let mut chars: i64 = 0;
|
2019-05-26 22:38:26 +00:00
|
|
|
let bytes = contents.len() as i64;
|
2019-05-26 02:04:13 +00:00
|
|
|
let mut end_of_word = true;
|
|
|
|
|
|
|
|
for c in contents.chars() {
|
|
|
|
chars += 1;
|
|
|
|
|
|
|
|
match c {
|
|
|
|
'\n' => {
|
|
|
|
lines += 1;
|
|
|
|
end_of_word = true;
|
|
|
|
}
|
|
|
|
' ' => end_of_word = true,
|
|
|
|
_ => {
|
|
|
|
if end_of_word {
|
|
|
|
words += 1;
|
|
|
|
}
|
|
|
|
end_of_word = false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let mut dict = Dictionary::default();
|
|
|
|
dict.add("name", Value::string(name.to_owned()));
|
|
|
|
dict.add("lines", Value::int(lines));
|
|
|
|
dict.add("words", Value::int(words));
|
|
|
|
dict.add("chars", Value::int(chars));
|
|
|
|
dict.add("max length", Value::int(bytes));
|
|
|
|
|
|
|
|
ReturnValue::Value(Value::Object(dict))
|
|
|
|
}
|