1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
use chrono::Local;
use chrono::{DateTime, TimeZone};
use nu_engine::CallExt;
use nu_protocol::{
ast::Call,
engine::{Command, EngineState, Stack},
Category, Example, PipelineData, ShellError, Signature, Span, Spanned, SyntaxShape, Value,
};
use std::fmt::{Display, Write};
use super::utils::parse_date_from_string;
#[derive(Clone)]
pub struct SubCommand;
impl Command for SubCommand {
fn name(&self) -> &str {
"date format"
}
fn signature(&self) -> Signature {
Signature::build("date format")
.switch("list", "lists strftime cheatsheet", Some('l'))
.optional(
"format string",
SyntaxShape::String,
"the desired date format",
)
.category(Category::Date)
}
fn usage(&self) -> &str {
"Format a given date using a format string."
}
fn search_terms(&self) -> Vec<&str> {
vec!["date", "format", "strftime"]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
let head = call.head;
if call.has_flag("list") {
return Ok(PipelineData::Value(
generate_strftime_list(head, false),
None,
));
}
let format = call.opt::<Spanned<String>>(engine_state, stack, 0)?;
input.map(
move |value| match &format {
Some(format) => format_helper(value, format.item.as_str(), format.span, head),
None => format_helper_rfc2822(value, head),
},
engine_state.ctrlc.clone(),
)
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Format a given date using the default format (RFC 2822).",
example: r#""2021-10-22 20:00:12 +01:00" | date format"#,
result: Some(Value::String {
val: "Fri, 22 Oct 2021 20:00:12 +0100".to_string(),
span: Span::test_data(),
}),
},
Example {
description: "Format a given date using a given format string.",
example: "date format '%Y-%m-%d'",
result: None,
},
Example {
description: "Format a given date using a given format string.",
example: r#"date format "%Y-%m-%d %H:%M:%S""#,
result: None,
},
Example {
description: "Format a given date using a given format string.",
example: r#""2021-10-22 20:00:12 +01:00" | date format "%Y-%m-%d""#,
result: None,
},
]
}
}
fn format_from<Tz: TimeZone>(date_time: DateTime<Tz>, formatter: &str, span: Span) -> Value
where
Tz::Offset: Display,
{
let mut formatter_buf = String::new();
let format = date_time.format(formatter);
match formatter_buf.write_fmt(format_args!("{}", format)) {
Ok(_) => Value::String {
val: formatter_buf,
span,
},
Err(_) => Value::Error {
error: ShellError::UnsupportedInput("invalid format".to_string(), span),
},
}
}
fn format_helper(value: Value, formatter: &str, formatter_span: Span, head_span: Span) -> Value {
match value {
Value::Date { val, .. } => format_from(val, formatter, formatter_span),
Value::String { val, .. } => {
let dt = parse_date_from_string(&val, formatter_span);
match dt {
Ok(x) => format_from(x, formatter, formatter_span),
Err(e) => e,
}
}
Value::Nothing { .. } => {
let dt = Local::now();
format_from(dt, formatter, formatter_span)
}
_ => Value::Error {
error: ShellError::DatetimeParseError(head_span),
},
}
}
fn format_helper_rfc2822(value: Value, span: Span) -> Value {
match value {
Value::Date { val, span: _ } => Value::String {
val: val.to_rfc2822(),
span,
},
Value::String {
val,
span: val_span,
} => {
let dt = parse_date_from_string(&val, val_span);
match dt {
Ok(x) => Value::String {
val: x.to_rfc2822(),
span,
},
Err(e) => e,
}
}
Value::Nothing { span: _ } => {
let dt = Local::now();
Value::String {
val: dt.with_timezone(dt.offset()).to_rfc2822(),
span,
}
}
_ => Value::Error {
error: ShellError::DatetimeParseError(span),
},
}
}
pub(crate) fn generate_strftime_list(head: Span, show_parse_only_formats: bool) -> Value {
let column_names = vec![
"Specification".into(),
"Example".into(),
"Description".into(),
];
let now = Local::now();
struct FormatSpecification<'a> {
spec: &'a str,
description: &'a str,
}
let specifications = vec![
FormatSpecification {
spec: "%Y",
description: "The full proleptic Gregorian year, zero-padded to 4 digits.",
},
FormatSpecification {
spec: "%C",
description: "The proleptic Gregorian year divided by 100, zero-padded to 2 digits.",
},
FormatSpecification {
spec: "%Y",
description: "The full proleptic Gregorian year, zero-padded to 4 digits.",
},
FormatSpecification {
spec: "%C",
description: "The proleptic Gregorian year divided by 100, zero-padded to 2 digits.",
},
FormatSpecification {
spec: "%y",
description: "The proleptic Gregorian year modulo 100, zero-padded to 2 digits.",
},
FormatSpecification {
spec: "%m",
description: "Month number (01--12), zero-padded to 2 digits.",
},
FormatSpecification {
spec: "%b",
description: "Abbreviated month name. Always 3 letters.",
},
FormatSpecification {
spec: "%B",
description: "Full month name. Also accepts corresponding abbreviation in parsing.",
},
FormatSpecification {
spec: "%h",
description: "Same as %b.",
},
FormatSpecification {
spec: "%d",
description: "Day number (01--31), zero-padded to 2 digits.",
},
FormatSpecification {
spec: "%e",
description: "Same as %d but space-padded. Same as %_d.",
},
FormatSpecification {
spec: "%a",
description: "Abbreviated weekday name. Always 3 letters.",
},
FormatSpecification {
spec: "%A",
description: "Full weekday name. Also accepts corresponding abbreviation in parsing.",
},
FormatSpecification {
spec: "%w",
description: "Sunday = 0, Monday = 1, ..., Saturday = 6.",
},
FormatSpecification {
spec: "%u",
description: "Monday = 1, Tuesday = 2, ..., Sunday = 7. (ISO 8601)",
},
FormatSpecification {
spec: "%U",
description: "Week number starting with Sunday (00--53), zero-padded to 2 digits.",
},
FormatSpecification {
spec: "%W",
description:
"Same as %U, but week 1 starts with the first Monday in that year instead.",
},
FormatSpecification {
spec: "%G",
description: "Same as %Y but uses the year number in ISO 8601 week date.",
},
FormatSpecification {
spec: "%g",
description: "Same as %y but uses the year number in ISO 8601 week date.",
},
FormatSpecification {
spec: "%V",
description: "Same as %U but uses the week number in ISO 8601 week date (01--53).",
},
FormatSpecification {
spec: "%j",
description: "Day of the year (001--366), zero-padded to 3 digits.",
},
FormatSpecification {
spec: "%D",
description: "Month-day-year format. Same as %m/%d/%y.",
},
FormatSpecification {
spec: "%x",
description: "Locale's date representation (e.g., 12/31/99).",
},
FormatSpecification {
spec: "%F",
description: "Year-month-day format (ISO 8601). Same as %Y-%m-%d.",
},
FormatSpecification {
spec: "%v",
description: "Day-month-year format. Same as %e-%b-%Y.",
},
FormatSpecification {
spec: "%H",
description: "Hour number (00--23), zero-padded to 2 digits.",
},
FormatSpecification {
spec: "%k",
description: "Same as %H but space-padded. Same as %_H.",
},
FormatSpecification {
spec: "%I",
description: "Hour number in 12-hour clocks (01--12), zero-padded to 2 digits.",
},
FormatSpecification {
spec: "%l",
description: "Same as %I but space-padded. Same as %_I.",
},
FormatSpecification {
spec: "%P",
description: "am or pm in 12-hour clocks.",
},
FormatSpecification {
spec: "%p",
description: "AM or PM in 12-hour clocks.",
},
FormatSpecification {
spec: "%M",
description: "Minute number (00--59), zero-padded to 2 digits.",
},
FormatSpecification {
spec: "%S",
description: "Second number (00--60), zero-padded to 2 digits.",
},
FormatSpecification {
spec: "%f",
description: "The fractional seconds (in nanoseconds) since last whole second.",
},
FormatSpecification {
spec: "%.f",
description: "Similar to .%f but left-aligned. These all consume the leading dot.",
},
FormatSpecification {
spec: "%.3f",
description: "Similar to .%f but left-aligned but fixed to a length of 3.",
},
FormatSpecification {
spec: "%.6f",
description: "Similar to .%f but left-aligned but fixed to a length of 6.",
},
FormatSpecification {
spec: "%.9f",
description: "Similar to .%f but left-aligned but fixed to a length of 9.",
},
FormatSpecification {
spec: "%3f",
description: "Similar to %.3f but without the leading dot.",
},
FormatSpecification {
spec: "%6f",
description: "Similar to %.6f but without the leading dot.",
},
FormatSpecification {
spec: "%9f",
description: "Similar to %.9f but without the leading dot.",
},
FormatSpecification {
spec: "%R",
description: "Hour-minute format. Same as %H:%M.",
},
FormatSpecification {
spec: "%T",
description: "Hour-minute-second format. Same as %H:%M:%S.",
},
FormatSpecification {
spec: "%X",
description: "Locale's time representation (e.g., 23:13:48).",
},
FormatSpecification {
spec: "%r",
description: "Hour-minute-second format in 12-hour clocks. Same as %I:%M:%S %p.",
},
FormatSpecification {
spec: "%Z",
description:
"Local time zone name. Skips all non-whitespace characters during parsing.",
},
FormatSpecification {
spec: "%z",
description: "Offset from the local time to UTC (with UTC being +0000).",
},
FormatSpecification {
spec: "%:z",
description: "Same as %z but with a colon.",
},
FormatSpecification {
spec: "%c",
description: "Locale's date and time (e.g., Thu Mar 3 23:05:25 2005).",
},
FormatSpecification {
spec: "%+",
description: "ISO 8601 / RFC 3339 date & time format.",
},
FormatSpecification {
spec: "%s",
description: "UNIX timestamp, the number of seconds since 1970-01-01",
},
FormatSpecification {
spec: "%t",
description: "Literal tab (\\t).",
},
FormatSpecification {
spec: "%n",
description: "Literal newline (\\n).",
},
FormatSpecification {
spec: "%%",
description: "Literal percent sign.",
},
];
let mut records = specifications
.iter()
.map(|s| Value::Record {
cols: column_names.clone(),
vals: vec![
Value::String {
val: s.spec.to_string(),
span: head,
},
Value::String {
val: now.format(s.spec).to_string(),
span: head,
},
Value::String {
val: s.description.to_string(),
span: head,
},
],
span: head,
})
.collect::<Vec<Value>>();
if show_parse_only_formats {
let example = now
.format("%:z")
.to_string()
.get(0..3)
.unwrap_or("")
.to_string();
records.push(Value::Record {
cols: column_names,
vals: vec![
Value::String {
val: "%#z".to_string(),
span: head,
},
Value::String {
val: example,
span: head,
},
Value::String {
val: "Parsing only: Same as %z but allows minutes to be missing or present."
.to_string(),
span: head,
},
],
span: head,
});
}
Value::List {
vals: records,
span: head,
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(SubCommand {})
}
}