2019-05-26 02:04:13 +00:00
|
|
|
use crate::errors::ShellError;
|
2019-07-09 04:31:26 +00:00
|
|
|
use crate::object::{SpannedDictBuilder, Value};
|
2019-05-26 02:04:13 +00:00
|
|
|
use crate::prelude::*;
|
|
|
|
use std::fs::File;
|
|
|
|
use std::io::prelude::*;
|
|
|
|
|
|
|
|
pub fn size(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
2019-06-22 03:43:37 +00:00
|
|
|
if args.len() == 0 {
|
2019-06-15 18:36:17 +00:00
|
|
|
return Err(ShellError::maybe_labeled_error(
|
|
|
|
"Size requires a filepath",
|
|
|
|
"needs path",
|
|
|
|
args.name_span,
|
|
|
|
));
|
2019-05-26 02:04:13 +00:00
|
|
|
}
|
2019-06-13 21:47:25 +00:00
|
|
|
let cwd = args
|
|
|
|
.env
|
|
|
|
.lock()
|
|
|
|
.unwrap()
|
2019-06-15 17:52:55 +00:00
|
|
|
.front()
|
2019-06-13 21:47:25 +00:00
|
|
|
.unwrap()
|
|
|
|
.path()
|
|
|
|
.to_path_buf();
|
2019-05-26 02:04:13 +00:00
|
|
|
|
|
|
|
let mut contents = String::new();
|
|
|
|
|
2019-07-08 16:44:53 +00:00
|
|
|
let mut list: VecDeque<ReturnValue> = VecDeque::new();
|
|
|
|
for spanned_name in args.positional_iter() {
|
|
|
|
let name = spanned_name.as_string()?;
|
2019-05-26 02:04:13 +00:00
|
|
|
let path = cwd.join(&name);
|
|
|
|
let mut file = File::open(path)?;
|
|
|
|
file.read_to_string(&mut contents)?;
|
2019-07-09 04:31:26 +00:00
|
|
|
list.push_back(count(&name, &contents, spanned_name).into());
|
2019-05-26 02:04:13 +00:00
|
|
|
contents.clear();
|
|
|
|
}
|
|
|
|
|
2019-07-03 20:31:15 +00:00
|
|
|
Ok(list.to_output_stream())
|
2019-05-26 02:04:13 +00:00
|
|
|
}
|
|
|
|
|
2019-07-09 04:31:26 +00:00
|
|
|
fn count(name: &str, contents: &str, span: impl Into<Span>) -> Spanned<Value> {
|
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;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-07-09 04:31:26 +00:00
|
|
|
let mut dict = SpannedDictBuilder::new(span);
|
|
|
|
dict.insert("name", Value::string(name));
|
|
|
|
dict.insert("lines", Value::int(lines));
|
|
|
|
dict.insert("words", Value::int(words));
|
|
|
|
dict.insert("chars", Value::int(chars));
|
|
|
|
dict.insert("max length", Value::int(bytes));
|
2019-05-26 02:04:13 +00:00
|
|
|
|
2019-07-09 04:31:26 +00:00
|
|
|
dict.into_spanned_value()
|
2019-05-26 02:04:13 +00:00
|
|
|
}
|