nushell/src/commands/date.rs

76 lines
2.0 KiB
Rust
Raw Normal View History

use crate::data::{Dictionary, Value};
2019-09-11 16:36:50 +02:00
use crate::errors::ShellError;
2019-07-26 06:09:19 +02:00
use crate::prelude::*;
use chrono::{DateTime, Local, Utc};
2019-08-15 07:02:02 +02:00
use crate::commands::WholeStreamCommand;
2019-08-09 06:51:21 +02:00
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-15 07:02:02 +02:00
impl WholeStreamCommand for Date {
fn name(&self) -> &str {
"date"
}
fn signature(&self) -> Signature {
Signature::build("date").switch("utc").switch("local")
}
fn usage(&self) -> &str {
"Get the current datetime."
}
2019-08-09 06:51:21 +02:00
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
date(args, registry)
2019-07-26 06:09:19 +02:00
}
}
pub fn date_to_value<T: TimeZone>(dt: DateTime<T>, tag: Tag) -> Tagged<Value>
2019-07-26 06:09:19 +02:00
where
T::Offset: Display,
{
let mut indexmap = IndexMap::new();
indexmap.insert("year".to_string(), Value::int(dt.year()).tagged(tag));
indexmap.insert("month".to_string(), Value::int(dt.month()).tagged(tag));
indexmap.insert("day".to_string(), Value::int(dt.day()).tagged(tag));
indexmap.insert("hour".to_string(), Value::int(dt.hour()).tagged(tag));
indexmap.insert("minute".to_string(), Value::int(dt.minute()).tagged(tag));
indexmap.insert("second".to_string(), Value::int(dt.second()).tagged(tag));
2019-07-26 06:09:19 +02:00
let tz = dt.offset();
indexmap.insert(
"timezone".to_string(),
Value::string(format!("{}", tz)).tagged(tag),
2019-07-26 06:09:19 +02:00
);
Value::Row(Dictionary::from(indexmap)).tagged(tag)
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 tag = args.call_info.name_tag;
2019-07-26 06:09:19 +02:00
let value = if args.has("utc") {
let utc: DateTime<Utc> = Utc::now();
date_to_value(utc, tag)
2019-07-26 06:09:19 +02:00
} else {
let local: DateTime<Local> = Local::now();
date_to_value(local, tag)
2019-07-26 06:09:19 +02:00
};
date_out.push_back(value);
Ok(date_out.to_output_stream())
}