1use chrono::{Datelike, Local, NaiveDate};
2use nu_color_config::StyleComputer;
3use nu_engine::command_prelude::*;
4use nu_protocol::ast::{self, Expr, Expression};
5
6use std::collections::VecDeque;
7
8static DAYS_OF_THE_WEEK: [&str; 7] = ["su", "mo", "tu", "we", "th", "fr", "sa"];
9
10#[derive(Clone)]
11pub struct Cal;
12
13struct Arguments {
14 year: bool,
15 quarter: bool,
16 month: bool,
17 month_names: bool,
18 full_year: Option<Spanned<i64>>,
19 week_start: Option<Spanned<String>>,
20 as_table: bool,
21}
22
23impl Command for Cal {
24 fn name(&self) -> &str {
25 "cal"
26 }
27
28 fn signature(&self) -> Signature {
29 Signature::build("cal")
30 .switch("year", "Display the year column.", Some('y'))
31 .switch("quarter", "Display the quarter column.", Some('q'))
32 .switch("month", "Display the month column.", Some('m'))
33 .switch("as-table", "Output as a table.", Some('t'))
34 .named(
35 "full-year",
36 SyntaxShape::Int,
37 "Display a year-long calendar for the specified year.",
38 None,
39 )
40 .param(
41 Flag::new("week-start")
42 .arg(SyntaxShape::String)
43 .desc(
44 "Display the calendar with the specified day as the first day of the week.",
45 )
46 .completion(Completion::new_list(DAYS_OF_THE_WEEK.as_slice())),
47 )
48 .switch(
49 "month-names",
50 "Display the month names in a separate column.",
51 None,
52 )
53 .input_output_types(vec![
54 (Type::Nothing, Type::String),
55 (Type::Nothing, Type::table()),
56 ])
57 .allow_variants_without_examples(true) .category(Category::Generators)
59 }
60
61 fn description(&self) -> &str {
62 "Display a calendar."
63 }
64
65 fn run(
66 &self,
67 engine_state: &EngineState,
68 stack: &mut Stack,
69 call: &Call,
70 input: PipelineData,
71 ) -> Result<PipelineData, ShellError> {
72 cal(engine_state, stack, call, input)
73 }
74
75 fn examples(&self) -> Vec<Example<'_>> {
76 vec![
77 Example {
78 description: "This month's calendar",
79 example: "cal",
80 result: None,
81 },
82 Example {
83 description: "The calendar for all of 2012",
84 example: "cal --full-year 2012",
85 result: None,
86 },
87 Example {
88 description: "This month's calendar with the week starting on Monday",
89 example: "cal --week-start mo",
90 result: None,
91 },
92 Example {
93 description: "How many 'Friday the Thirteenths' occurred in 2015?",
94 example: "cal --as-table --full-year 2015 | where fr == 13 | length",
95 result: None,
96 },
97 ]
98 }
99}
100
101pub fn cal(
102 engine_state: &EngineState,
103 stack: &mut Stack,
104 call: &Call,
105 _input: PipelineData,
106) -> Result<PipelineData, ShellError> {
107 let mut calendar_vec_deque = VecDeque::new();
108 let tag = call.head;
109
110 let (current_year, current_month, current_day) = get_current_date();
111
112 let arguments = Arguments {
113 year: call.has_flag(engine_state, stack, "year")?,
114 month: call.has_flag(engine_state, stack, "month")?,
115 month_names: call.has_flag(engine_state, stack, "month-names")?,
116 quarter: call.has_flag(engine_state, stack, "quarter")?,
117 full_year: call.get_flag(engine_state, stack, "full-year")?,
118 week_start: call.get_flag(engine_state, stack, "week-start")?,
119 as_table: call.has_flag(engine_state, stack, "as-table")?,
120 };
121
122 let style_computer = &StyleComputer::from_config(engine_state, stack);
123
124 let mut selected_year: i32 = current_year;
125 let mut current_day_option: Option<u32> = Some(current_day);
126
127 let full_year_value = &arguments.full_year;
128 let month_range = if let Some(full_year_value) = full_year_value {
129 selected_year = full_year_value.item as i32;
130
131 if selected_year != current_year {
132 current_day_option = None
133 }
134 (1, 12)
135 } else {
136 (current_month, current_month)
137 };
138
139 add_months_of_year_to_table(
140 &arguments,
141 &mut calendar_vec_deque,
142 tag,
143 selected_year,
144 month_range,
145 current_month,
146 current_day_option,
147 style_computer,
148 )?;
149
150 let mut table_no_index = ast::Call::new(tag);
151 table_no_index.add_named((
152 Spanned {
153 item: "index".to_string(),
154 span: tag,
155 },
156 None,
157 Some(Expression::new_unknown(Expr::Bool(false), tag, Type::Bool)),
158 ));
159
160 let cal_table_output =
161 Value::list(calendar_vec_deque.into_iter().collect(), tag).into_pipeline_data();
162 if !arguments.as_table {
163 crate::Table.run(
164 engine_state,
165 stack,
166 &(&table_no_index).into(),
167 cal_table_output,
168 )
169 } else {
170 Ok(cal_table_output)
171 }
172}
173
174fn get_invalid_year_shell_error(head: Span) -> ShellError {
175 ShellError::TypeMismatch {
176 err_message: "The year is invalid".to_string(),
177 span: head,
178 }
179}
180
181struct MonthHelper {
182 selected_year: i32,
183 selected_month: u32,
184 day_number_of_week_month_starts_on: u32,
185 number_of_days_in_month: u32,
186 quarter_number: u32,
187 month_name: String,
188}
189
190impl MonthHelper {
191 pub fn new(selected_year: i32, selected_month: u32) -> Result<MonthHelper, ()> {
192 let naive_date = NaiveDate::from_ymd_opt(selected_year, selected_month, 1).ok_or(())?;
193 let number_of_days_in_month =
194 MonthHelper::calculate_number_of_days_in_month(selected_year, selected_month)?;
195
196 Ok(MonthHelper {
197 selected_year,
198 selected_month,
199 day_number_of_week_month_starts_on: naive_date.weekday().num_days_from_sunday(),
200 number_of_days_in_month,
201 quarter_number: ((selected_month - 1) / 3) + 1,
202 month_name: naive_date.format("%B").to_string().to_ascii_lowercase(),
203 })
204 }
205
206 fn calculate_number_of_days_in_month(
207 mut selected_year: i32,
208 mut selected_month: u32,
209 ) -> Result<u32, ()> {
210 if selected_month == 12 {
214 selected_year += 1;
215 selected_month = 1;
216 } else {
217 selected_month += 1;
218 };
219
220 let next_month_naive_date =
221 NaiveDate::from_ymd_opt(selected_year, selected_month, 1).ok_or(())?;
222
223 Ok(next_month_naive_date.pred_opt().unwrap_or_default().day())
224 }
225}
226
227fn get_current_date() -> (i32, u32, u32) {
228 let local_now_date = Local::now().date_naive();
229
230 let current_year: i32 = local_now_date.year();
231 let current_month: u32 = local_now_date.month();
232 let current_day: u32 = local_now_date.day();
233
234 (current_year, current_month, current_day)
235}
236
237#[allow(clippy::too_many_arguments)]
238fn add_months_of_year_to_table(
239 arguments: &Arguments,
240 calendar_vec_deque: &mut VecDeque<Value>,
241 tag: Span,
242 selected_year: i32,
243 (start_month, end_month): (u32, u32),
244 current_month: u32,
245 current_day_option: Option<u32>,
246 style_computer: &StyleComputer,
247) -> Result<(), ShellError> {
248 for month_number in start_month..=end_month {
249 let mut new_current_day_option: Option<u32> = None;
250
251 if let Some(current_day) = current_day_option
252 && month_number == current_month
253 {
254 new_current_day_option = Some(current_day)
255 }
256
257 let add_month_to_table_result = add_month_to_table(
258 arguments,
259 calendar_vec_deque,
260 tag,
261 selected_year,
262 month_number,
263 new_current_day_option,
264 style_computer,
265 );
266
267 add_month_to_table_result?
268 }
269
270 Ok(())
271}
272
273fn add_month_to_table(
274 arguments: &Arguments,
275 calendar_vec_deque: &mut VecDeque<Value>,
276 tag: Span,
277 selected_year: i32,
278 current_month: u32,
279 current_day_option: Option<u32>,
280 style_computer: &StyleComputer,
281) -> Result<(), ShellError> {
282 let month_helper_result = MonthHelper::new(selected_year, current_month);
283
284 let full_year_value: &Option<Spanned<i64>> = &arguments.full_year;
285
286 let month_helper = match month_helper_result {
287 Ok(month_helper) => month_helper,
288 Err(()) => match full_year_value {
289 Some(x) => return Err(get_invalid_year_shell_error(x.span)),
290 None => {
291 return Err(ShellError::UnknownOperator {
292 op_token: "Issue parsing command, invalid command".to_string(),
293 span: tag,
294 });
295 }
296 },
297 };
298
299 let mut days_of_the_week = DAYS_OF_THE_WEEK;
300 let mut total_start_offset: u32 = month_helper.day_number_of_week_month_starts_on;
301
302 if let Some(week_start_day) = &arguments.week_start {
303 if let Some(position) = days_of_the_week
304 .iter()
305 .position(|day| *day == week_start_day.item)
306 {
307 days_of_the_week.rotate_left(position);
308 total_start_offset += (days_of_the_week.len() - position) as u32;
309 total_start_offset %= days_of_the_week.len() as u32;
310 } else {
311 return Err(ShellError::TypeMismatch {
312 err_message: format!(
313 "The specified week start day is invalid, expected one of {DAYS_OF_THE_WEEK:?}"
314 ),
315 span: week_start_day.span,
316 });
317 }
318 };
319
320 let mut day_number: u32 = 1;
321 let day_limit: u32 = total_start_offset + month_helper.number_of_days_in_month;
322
323 let should_show_year_column = arguments.year;
324 let should_show_quarter_column = arguments.quarter;
325 let should_show_month_column = arguments.month;
326 let should_show_month_names = arguments.month_names;
327
328 while day_number <= day_limit {
329 let mut record = Record::new();
330
331 if should_show_year_column {
332 record.insert(
333 "year".to_string(),
334 Value::int(month_helper.selected_year as i64, tag),
335 );
336 }
337
338 if should_show_quarter_column {
339 record.insert(
340 "quarter".to_string(),
341 Value::int(month_helper.quarter_number as i64, tag),
342 );
343 }
344
345 if should_show_month_column {
346 record.insert(
347 "month".to_string(),
348 Value::int(month_helper.selected_month as i64, tag),
349 );
350 }
351
352 if should_show_month_names {
353 record.insert(
354 "month_name".to_string(),
355 Value::string(month_helper.month_name.clone(), tag),
356 );
357 }
358
359 for day in &days_of_the_week {
360 let should_add_day_number_to_table =
361 (day_number > total_start_offset) && (day_number <= day_limit);
362
363 let mut value = Value::nothing(tag);
364
365 if should_add_day_number_to_table {
366 let adjusted_day_number = day_number - total_start_offset;
367
368 value = Value::int(adjusted_day_number as i64, tag);
369
370 if let Some(current_day) = current_day_option
371 && current_day == adjusted_day_number
372 {
373 let header_style = style_computer.compute("header", &Value::nothing(tag));
375
376 value = Value::string(
377 header_style
378 .paint(adjusted_day_number.to_string())
379 .to_string(),
380 tag,
381 );
382 }
383 }
384
385 record.insert((*day).to_string(), value);
386
387 day_number += 1;
388 }
389
390 calendar_vec_deque.push_back(Value::record(record, tag))
391 }
392
393 Ok(())
394}
395
396#[cfg(test)]
397mod test {
398 use super::*;
399
400 #[test]
401 fn test_examples() -> nu_test_support::Result {
402 nu_test_support::test().examples(Cal)
403 }
404}