-
Notifications
You must be signed in to change notification settings - Fork 251
/
lib.rs
378 lines (336 loc) · 10.4 KB
/
lib.rs
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
use ansi_term::Style;
use chrono::{Datelike, Local, NaiveDate};
use clap::{App, Arg};
use itertools::izip;
use std::{error::Error, str::FromStr};
#[derive(Debug)]
pub struct Config {
month: Option<u32>,
year: i32,
today: NaiveDate,
}
type MyResult<T> = Result<T, Box<dyn Error>>;
const LINE_WIDTH: usize = 22;
const MONTH_NAMES: [&str; 12] = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
// --------------------------------------------------
pub fn get_args() -> MyResult<Config> {
let matches = App::new("calr")
.version("0.1.0")
.author("Ken Youens-Clark <kyclark@gmail.com>")
.about("Rust cal")
.arg(
Arg::with_name("month")
.value_name("MONTH")
.short("m")
.help("Month name or number (1-12)")
.takes_value(true),
)
.arg(
Arg::with_name("show_current_year")
.value_name("SHOW_YEAR")
.short("y")
.long("year")
.help("Show whole current year")
.conflicts_with_all(&["month", "year"])
.takes_value(false),
)
.arg(
Arg::with_name("year")
.value_name("YEAR")
.help("Year (1-9999)"),
)
.get_matches();
let mut month = matches.value_of("month").map(parse_month).transpose()?;
let mut year = matches.value_of("year").map(parse_year).transpose()?;
let today = Local::today();
if matches.is_present("show_current_year") {
month = None;
year = Some(today.year());
} else if month.is_none() && year.is_none() {
month = Some(today.month());
year = Some(today.year());
}
Ok(Config {
month,
year: year.unwrap_or_else(|| today.year()),
today: today.naive_local(),
})
}
// --------------------------------------------------
pub fn run(config: Config) -> MyResult<()> {
match config.month {
Some(month) => {
let lines = format_month(config.year, month, true, config.today);
println!("{}", lines.join("\n"));
}
None => {
println!("{:>32}", config.year);
let months: Vec<_> = (1..=12)
.into_iter()
.map(|month| {
format_month(config.year, month, false, config.today)
})
.collect();
for (i, chunk) in months.chunks(3).enumerate() {
if let [m1, m2, m3] = chunk {
for lines in izip!(m1, m2, m3) {
println!("{}{}{}", lines.0, lines.1, lines.2);
}
if i < 3 {
println!();
}
}
}
}
}
Ok(())
}
// --------------------------------------------------
fn parse_int<T: FromStr>(val: &str) -> MyResult<T> {
val.parse()
.map_err(|_| format!("Invalid integer \"{}\"", val).into())
}
// --------------------------------------------------
fn parse_year(year: &str) -> MyResult<i32> {
parse_int(year).and_then(|num| {
if (1..=9999).contains(&num) {
Ok(num)
} else {
Err(format!("year \"{}\" not in the range 1 through 9999", year)
.into())
}
})
}
// --------------------------------------------------
fn parse_month(month: &str) -> MyResult<u32> {
match parse_int(month) {
Ok(num) => {
if (1..=12).contains(&num) {
Ok(num)
} else {
Err(format!(
"month \"{}\" not in the range 1 through 12",
month
)
.into())
}
}
_ => {
let lower = &month.to_lowercase();
let matches: Vec<_> = MONTH_NAMES
.iter()
.enumerate()
.filter_map(|(i, name)| {
if name.to_lowercase().starts_with(lower) {
Some(i + 1)
} else {
None
}
})
.collect();
if matches.len() == 1 {
Ok(matches[0] as u32)
} else {
Err(format!("Invalid month \"{}\"", month).into())
}
}
}
}
// --------------------------------------------------
fn last_day_in_month(year: i32, month: u32) -> NaiveDate {
// The first day of the next month...
let (y, m) = if month == 12 {
(year + 1, 1)
} else {
(year, month + 1)
};
// ...is preceded by the last day of the original month
NaiveDate::from_ymd(y, m, 1).pred()
}
// --------------------------------------------------
fn format_month(
year: i32,
month: u32,
print_year: bool,
today: NaiveDate,
) -> Vec<String> {
let first = NaiveDate::from_ymd(year, month, 1);
let mut days: Vec<String> = (1..first.weekday().number_from_sunday())
.into_iter()
.map(|_| " ".to_string()) // two spaces
.collect();
let is_today = |day: u32| {
year == today.year() && month == today.month() && day == today.day()
};
let last = last_day_in_month(year, month);
days.extend((first.day()..=last.day()).into_iter().map(|num| {
let fmt = format!("{:>2}", num);
if is_today(num) {
Style::new().reverse().paint(fmt).to_string()
} else {
fmt
}
}));
let month_name = MONTH_NAMES[month as usize - 1];
let mut lines = Vec::with_capacity(8);
lines.push(format!(
"{:^20} ", // two trailing spaces
if print_year {
format!("{} {}", month_name, year)
} else {
month_name.to_string()
}
));
lines.push("Su Mo Tu We Th Fr Sa ".to_string()); // two trailing spaces
for week in days.chunks(7) {
lines.push(format!(
"{:width$} ", // two trailing spaces
week.join(" "),
width = LINE_WIDTH - 2
));
}
while lines.len() < 8 {
lines.push(" ".repeat(LINE_WIDTH));
}
lines
}
// --------------------------------------------------
#[cfg(test)]
mod tests {
use super::{
format_month, last_day_in_month, parse_int, parse_month, parse_year,
};
use chrono::NaiveDate;
#[test]
fn test_parse_int() {
// Parse positive int as usize
let res = parse_int::<usize>("1");
assert!(res.is_ok());
assert_eq!(res.unwrap(), 1usize);
// Parse negative int as i32
let res = parse_int::<i32>("-1");
assert!(res.is_ok());
assert_eq!(res.unwrap(), -1i32);
// Fail on a string
let res = parse_int::<i64>("foo");
assert!(res.is_err());
assert_eq!(res.unwrap_err().to_string(), "Invalid integer \"foo\"");
}
#[test]
fn test_parse_year() {
let res = parse_year("1");
assert!(res.is_ok());
assert_eq!(res.unwrap(), 1i32);
let res = parse_year("9999");
assert!(res.is_ok());
assert_eq!(res.unwrap(), 9999i32);
let res = parse_year("0");
assert!(res.is_err());
assert_eq!(
res.unwrap_err().to_string(),
"year \"0\" not in the range 1 through 9999"
);
let res = parse_year("10000");
assert!(res.is_err());
assert_eq!(
res.unwrap_err().to_string(),
"year \"10000\" not in the range 1 through 9999"
);
let res = parse_year("foo");
assert!(res.is_err());
assert_eq!(res.unwrap_err().to_string(), "Invalid integer \"foo\"");
}
#[test]
fn test_parse_month() {
let res = parse_month("1");
assert!(res.is_ok());
assert_eq!(res.unwrap(), 1u32);
let res = parse_month("12");
assert!(res.is_ok());
assert_eq!(res.unwrap(), 12u32);
let res = parse_month("jan");
assert!(res.is_ok());
assert_eq!(res.unwrap(), 1u32);
let res = parse_month("0");
assert!(res.is_err());
assert_eq!(
res.unwrap_err().to_string(),
"month \"0\" not in the range 1 through 12"
);
let res = parse_month("13");
assert!(res.is_err());
assert_eq!(
res.unwrap_err().to_string(),
"month \"13\" not in the range 1 through 12"
);
let res = parse_month("foo");
assert!(res.is_err());
assert_eq!(res.unwrap_err().to_string(), "Invalid month \"foo\"");
}
#[test]
fn test_format_month() {
let today = NaiveDate::from_ymd(0, 1, 1);
let leap_february = vec![
" February 2020 ",
"Su Mo Tu We Th Fr Sa ",
" 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 ",
" ",
];
assert_eq!(format_month(2020, 2, true, today), leap_february);
let may = vec![
" May ",
"Su Mo Tu We Th Fr Sa ",
" 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 ",
];
assert_eq!(format_month(2020, 5, false, today), may);
let april_hl = vec![
" April 2021 ",
"Su Mo Tu We Th Fr Sa ",
" 1 2 3 ",
" 4 5 6 \u{1b}[7m 7\u{1b}[0m 8 9 10 ",
"11 12 13 14 15 16 17 ",
"18 19 20 21 22 23 24 ",
"25 26 27 28 29 30 ",
" ",
];
let today = NaiveDate::from_ymd(2021, 4, 7);
assert_eq!(format_month(2021, 4, true, today), april_hl);
}
#[test]
fn test_last_day_in_month() {
assert_eq!(
last_day_in_month(2020, 1),
NaiveDate::from_ymd(2020, 1, 31)
);
assert_eq!(
last_day_in_month(2020, 2),
NaiveDate::from_ymd(2020, 2, 29)
);
assert_eq!(
last_day_in_month(2020, 4),
NaiveDate::from_ymd(2020, 4, 30)
);
}
}