nushell/src/commands/size.rs

73 lines
1.9 KiB
Rust
Raw Normal View History

2019-05-26 04:04:13 +02:00
use crate::errors::ShellError;
2019-07-09 06:31:26 +02:00
use crate::object::{SpannedDictBuilder, Value};
2019-05-26 04:04:13 +02:00
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();
2019-07-08 18:44:53 +02:00
let mut list: VecDeque<ReturnValue> = VecDeque::new();
for spanned_name in args.positional_iter() {
let name = spanned_name.as_string()?;
2019-05-26 04:04:13 +02:00
let path = cwd.join(&name);
let mut file = File::open(path)?;
file.read_to_string(&mut contents)?;
2019-07-09 06:31:26 +02:00
list.push_back(count(&name, &contents, spanned_name).into());
2019-05-26 04:04:13 +02:00
contents.clear();
}
Ok(list.to_output_stream())
2019-05-26 04:04:13 +02:00
}
2019-07-09 06:31:26 +02:00
fn count(name: &str, contents: &str, span: impl Into<Span>) -> Spanned<Value> {
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;
}
}
}
2019-07-09 06:31:26 +02: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 04:04:13 +02:00
2019-07-09 06:31:26 +02:00
dict.into_spanned_value()
2019-05-26 04:04:13 +02:00
}