nushell/src/commands/date.rs

89 lines
2.3 KiB
Rust
Raw Normal View History

2019-07-26 06:09:19 +02:00
use crate::errors::ShellError;
use crate::object::{Dictionary, Value};
use crate::prelude::*;
use chrono::{DateTime, Local, Utc};
2019-08-09 06:51:21 +02:00
use crate::commands::StaticCommand;
use crate::parser::registry::Signature;
2019-07-26 06:09:19 +02:00
use chrono::{Datelike, TimeZone, Timelike};
use core::fmt::Display;
use indexmap::IndexMap;
pub struct Date;
2019-08-09 06:51:21 +02:00
impl StaticCommand for Date {
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
date(args, registry)
2019-07-26 06:09:19 +02:00
}
fn name(&self) -> &str {
"date"
}
2019-08-09 06:51:21 +02:00
fn signature(&self) -> Signature {
Signature::build("mkdir").switch("utc").switch("local")
2019-07-26 06:09:19 +02:00
}
}
2019-08-01 03:58:42 +02:00
pub fn date_to_value<T: TimeZone>(dt: DateTime<T>, span: Span) -> Tagged<Value>
2019-07-26 06:09:19 +02:00
where
T::Offset: Display,
{
let mut indexmap = IndexMap::new();
indexmap.insert(
"year".to_string(),
Tagged::from_simple_spanned_item(Value::int(dt.year()), span),
2019-07-26 06:09:19 +02:00
);
indexmap.insert(
"month".to_string(),
Tagged::from_simple_spanned_item(Value::int(dt.month()), span),
2019-07-26 06:09:19 +02:00
);
indexmap.insert(
"day".to_string(),
Tagged::from_simple_spanned_item(Value::int(dt.day()), span),
2019-07-26 06:09:19 +02:00
);
indexmap.insert(
"hour".to_string(),
Tagged::from_simple_spanned_item(Value::int(dt.hour()), span),
2019-07-26 06:09:19 +02:00
);
indexmap.insert(
"minute".to_string(),
Tagged::from_simple_spanned_item(Value::int(dt.minute()), span),
2019-07-26 06:09:19 +02:00
);
indexmap.insert(
"second".to_string(),
Tagged::from_simple_spanned_item(Value::int(dt.second()), span),
2019-07-26 06:09:19 +02:00
);
let tz = dt.offset();
indexmap.insert(
"timezone".to_string(),
Tagged::from_simple_spanned_item(Value::string(format!("{}", tz)), span),
2019-07-26 06:09:19 +02:00
);
Tagged::from_simple_spanned_item(Value::Object(Dictionary::from(indexmap)), span)
2019-07-26 06:09:19 +02:00
}
2019-08-09 06:51:21 +02:00
pub fn date(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream, ShellError> {
let args = args.evaluate_once(registry)?;
2019-07-26 06:09:19 +02:00
let mut date_out = VecDeque::new();
let span = args.call_info.name_span;
2019-07-26 06:09:19 +02:00
let value = if args.has("utc") {
let utc: DateTime<Utc> = Utc::now();
date_to_value(utc, span)
} else {
let local: DateTime<Local> = Local::now();
date_to_value(local, span)
};
date_out.push_back(value);
Ok(date_out.to_output_stream())
}