nushell/src/commands/size.rs

74 lines
1.8 KiB
Rust
Raw Normal View History

2019-05-26 04:04:13 +02: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-22 05:43:37 +02:00
if args.len() == 0 {
2019-06-15 20:36:17 +02:00
return Err(ShellError::maybe_labeled_error(
"Size requires a filepath",
"needs path",
args.name_span,
));
2019-05-26 04:04:13 +02:00
}
2019-06-13 23:47:25 +02:00
let cwd = args
.env
.lock()
.unwrap()
2019-06-15 19:52:55 +02:00
.front()
2019-06-13 23:47:25 +02:00
.unwrap()
.path()
.to_path_buf();
2019-05-26 04:04:13 +02:00
let mut contents = String::new();
let mut list = VecDeque::new();
2019-06-22 05:43:37 +02:00
for name in args.positional_iter() {
2019-05-26 04:04:13 +02:00
let name = name.as_string()?;
let path = cwd.join(&name);
let mut file = File::open(path)?;
file.read_to_string(&mut contents)?;
list.push_back(count(&name, &contents));
2019-05-26 04:04:13 +02:00
contents.clear();
}
Ok(list.boxed())
}
fn count(name: &str, contents: &str) -> ReturnValue {
2019-05-26 04:04:13 +02:00
let mut lines: i64 = 0;
let mut words: i64 = 0;
let mut chars: i64 = 0;
let bytes = contents.len() as i64;
2019-05-26 04:04:13 +02: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();
2019-06-22 22:46:16 +02:00
dict.add("name", Value::string(name));
2019-05-26 04:04:13 +02:00
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))
}