tod 0.12.0

An unofficial Todoist command-line client
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
use crate::errors::Error;
use crate::{config::Config, regexes};

use chrono::{DateTime, Duration, NaiveDate, NaiveDateTime, Utc};
use chrono_tz::Tz;
use std::str::FromStr;

pub const FORMAT_DATE: &str = "%Y-%m-%d";
const FORMAT_TIME: &str = "%H:%M";
const FORMAT_DATETIME: &str = "%Y-%m-%dT%H:%M:%S";
const FORMAT_DATETIME_ZULU: &str = "%Y-%m-%dT%H:%M:%SZ";
const FORMAT_DATETIME_LONG: &str = "%Y-%m-%dT%H:%M:%S%.fZ";

pub const FORMAT_DATE_AND_TIME: &str = "%Y-%m-%d %H:%M";

#[cfg(test)] //Fixed Time Provider for Testing
use crate::test_time::FixedTimeProvider;

/// Enum for selecting Time Provider
#[derive(Clone, Debug)]
pub enum TimeProviderEnum {
    // Default to System Time Provider
    System(SystemTimeProvider),
    /// Fixed time provider for testing
    #[cfg(test)]
    Fixed(FixedTimeProvider),
}
//Default to SystemTimeProvider for TimeProviderEnum
impl Default for TimeProviderEnum {
    fn default() -> Self {
        TimeProviderEnum::System(SystemTimeProvider)
    }
}

impl TimeProvider for TimeProviderEnum {
    fn now(&self, tz: Tz) -> DateTime<Tz> {
        match self {
            TimeProviderEnum::System(provider) => provider.now(tz),
            #[cfg(test)]
            TimeProviderEnum::Fixed(provider) => provider.now(tz),
        }
    }
    fn today(&self, tz: Tz) -> NaiveDate {
        match self {
            TimeProviderEnum::System(provider) => provider.today(tz),
            #[cfg(test)]
            TimeProviderEnum::Fixed(provider) => provider.today(tz),
        }
    }
}

pub trait TimeProvider: Send + Sync + Clone {
    fn now(&self, tz: Tz) -> DateTime<Tz>;
    fn today(&self, tz: Tz) -> NaiveDate {
        self.now(tz).date_naive()
    }

    #[allow(dead_code)]
    /// Returns a string representation of the current time in the given timezone. If no timezone is given, it defaults to UTC. Currently only used in tests
    fn now_string(&self, tz: Tz) -> String {
        self.now(tz).to_rfc3339()
    }
}

#[derive(Clone, Debug)]
pub struct SystemTimeProvider;

impl TimeProvider for SystemTimeProvider {
    fn now(&self, tz: Tz) -> DateTime<Tz> {
        Utc::now().with_timezone(&tz)
    }
}

// ----------- DATETIME FUNCTIONS ----------

/// Returns the current time in the given timezone
/// If no timezone is given, it defaults to UTC
pub fn datetime_now(config: &Config) -> Result<DateTime<Tz>, Error> {
    let timezone = config.get_timezone()?;
    let tz = timezone_from_str(&timezone)?;

    Ok(config.time_provider.now(tz))
}

// Checks if datetime is today
pub fn datetime_is_today(datetime: DateTime<Tz>, config: &Config) -> Result<bool, Error> {
    is_date_today(datetime.date_naive(), config)
}

/// Parse DateTime
pub fn datetime_from_str(str: &str, timezone: Tz) -> Result<DateTime<Tz>, Error> {
    match str.len() {
        19 => parse_datetime(str, timezone, FORMAT_DATETIME),
        20 => parse_datetime(str, Tz::UTC, FORMAT_DATETIME_ZULU),
        27 => parse_datetime(str, Tz::UTC, FORMAT_DATETIME_LONG),
        length => Err(Error {
            source: "datetime_from_str".to_string(),
            message: format!("cannot parse {length} length DateTime: {str}"),
        }),
    }
}

fn parse_datetime(str: &str, timezone: Tz, format: &str) -> Result<DateTime<Tz>, Error> {
    let naive_datetime = NaiveDateTime::parse_from_str(str, format)?;
    naive_datetime_to_datetime(naive_datetime, timezone)
}

fn naive_datetime_to_datetime(
    datetime: NaiveDateTime,
    timezone: Tz,
) -> Result<DateTime<Tz>, Error> {
    datetime
        .and_local_timezone(timezone)
        .single()
        .ok_or_else(|| {
            Error::new(
                "naive_datetime_to_datetime",
                "Ambiguous or invalid datetime",
            )
        })
}

/// Checks if string is a datetime in format YYYY-MM-DD HH:MM
pub fn is_datetime(string: &str) -> bool {
    regexes::DATETIME_REGEX.is_match(string)
}

// ----------- DATE FUNCTIONS --------------

/// Parses a date string into a `NaiveDate` - The string can be in the format YYYY-MM-DD or YYYY-MM-DD HH:MM or YYYY-MM-DDTHH:MM:SS or YYYY-MM-DDTHH:MM:SSZ. Timezone is used to convert the date to UTC. If the string is not in one of these formats, an error is returned.
pub fn date_from_str(str: &str, timezone: Tz) -> Result<NaiveDate, Error> {
    let date = match str.len() {
        10 => NaiveDate::parse_from_str(str, FORMAT_DATE)?,
        19 => {
            let naive_datetime = NaiveDateTime::parse_from_str(str, FORMAT_DATETIME)?;
            naive_datetime_to_datetime(naive_datetime, timezone)?.date_naive()
        }
        20 => {
            let naive_datetime = NaiveDateTime::parse_from_str(str, FORMAT_DATETIME_ZULU)?;
            naive_datetime_to_datetime(naive_datetime, timezone)?.date_naive()
        }
        _ => {
            return Err(Error::new(
                "date_from_str",
                &format!("Cannot parse NaiveDate, unknown length: {str}"),
            ));
        }
    };

    Ok(date)
}

/// Checks if string is a date in format YYYY-MM-DD
pub fn is_date(string: &str) -> bool {
    regexes::DATE_REGEX.is_match(string)
}
/// Return today's date in Utc from the config timezone (defaults to UTC)
/// This is used for the "today" command
/// and for the "due" command to check if a date is today
pub fn naive_date_today(config: &Config) -> Result<NaiveDate, Error> {
    let tz = timezone_from_str(&config.get_timezone()?)?;
    Ok(config.time_provider.today(tz))
}

/// Returns today's date in given timezone for testing. Only used in tests currently but included for completeness.
#[allow(dead_code)]
pub fn naive_date_today_from_tz(tz: Tz) -> Result<NaiveDate, Error> {
    Ok(chrono::Utc::now().with_timezone(&tz).date_naive())
}

// Check if date is today
pub fn is_date_today(date: NaiveDate, config: &Config) -> Result<bool, Error> {
    let date_string = date.format(FORMAT_DATE).to_string();
    let today_string = date_string_today(config)?;
    Ok(date_string == today_string)
}

// Converts a date string to a NaiveDate
pub fn date_string_to_naive_date(date_string: &str) -> Result<NaiveDate, Error> {
    NaiveDate::from_str(date_string).map_err(Error::from)
}

// / Check if date is in the past
pub fn is_date_in_past(date: NaiveDate, config: &Config) -> Result<bool, Error> {
    Ok(naive_date_days_in_future(date, config)? < 0)
}

/// Returns 0 if today, negative if date given is in the past
pub fn naive_date_days_in_future(date: NaiveDate, config: &Config) -> Result<i64, Error> {
    let duration: Duration = date - naive_date_today(config)?;
    Ok(duration.num_days())
}
// ----------- STRING FUNCTIONS --------------

/// Return today's date in format 2021-09-16
pub fn date_string_today(config: &Config) -> Result<String, Error> {
    let timezone = config.get_timezone()?;
    let tz = timezone_from_str(&timezone)?;
    let today = config.time_provider.today(tz);

    Ok(today.format(FORMAT_DATE).to_string())
}

// Formats a date to a string
pub fn date_to_string(date: &NaiveDate, config: &Config) -> Result<String, Error> {
    if is_date_today(*date, config)? {
        Ok("Today".into())
    } else {
        Ok(date.format(FORMAT_DATE).to_string())
    }
}

// Formats a datetime to a string
pub fn datetime_to_string(datetime: &DateTime<Tz>, config: &Config) -> Result<String, Error> {
    let timezone = config.get_timezone()?;
    let tz = timezone_from_str(&timezone)?;
    if datetime_is_today(*datetime, config)? {
        Ok(datetime.with_timezone(&tz).format(FORMAT_TIME).to_string())
    } else {
        Ok(datetime.with_timezone(&tz).to_string())
    }
}

// ----------- TZ FUNCTIONS --------------

pub fn timezone_from_str(timezone_string: &str) -> Result<Tz, Error> {
    timezone_string
        .parse::<Tz>()
        .or_else(|_| parse_gmt_to_timezone(timezone_string))
}

/// For when we get offsets like GMT -7:00
fn parse_gmt_to_timezone(gmt: &str) -> Result<Tz, Error> {
    let split: Vec<&str> = gmt.split_whitespace().collect();
    let offset = split
        .get(1)
        .ok_or_else(|| Error::new("parse_timezone", "Invalid GMT format: missing offset"))?;
    let offset = offset.replace(":00", "");
    let offset = offset.replace(':', "");
    let offset_num = offset.parse::<i32>()?;

    let tz_string = format!(
        "Etc/GMT{}",
        if offset_num < 0 {
            "+".to_string()
        } else {
            "-".to_string()
        } + &offset_num.abs().to_string()
    );
    tz_string.parse().map_err(Error::from)
}
// -----------------------------------------

#[cfg(test)]
mod tests {
    use crate::{config, time};
    use pretty_assertions::assert_eq;

    use super::*;
    use chrono_tz::Tz;

    #[test]
    fn test_is_date() {
        assert!(is_date("2022-10-05"));
        assert!(!is_date("22-10-05"));
        assert!(!is_date("2022-10-05 24:02"));
        assert!(!is_date("today"));
    }

    #[test]
    fn test_is_datetime() {
        assert!(!is_datetime("2022-10-05"));
        assert!(!is_datetime("22-10-05"));
        assert!(is_datetime("2022-10-05 24:02"));
        assert!(!is_datetime("today"));
    }

    #[test]
    fn test_timezone_from_string() {
        assert_eq!(
            timezone_from_str("America/Los_Angeles"),
            Ok(Tz::America__Los_Angeles),
        );

        assert_eq!(timezone_from_str("GMT -7:00"), Ok(Tz::Etc__GMTPlus7),);
    }

    #[test]
    fn test_today_date_from_tz_utc() {
        let tz = Tz::UTC;
        let result =
            naive_date_today_from_tz(tz).expect("failed to compute today's date for timezone");
        let expected = chrono::Utc::now().with_timezone(&tz).date_naive();
        assert_eq!(result, expected);
    }

    #[test]
    fn test_today_date_from_tz_pacific() {
        let tz = Tz::America__Los_Angeles;
        let result =
            naive_date_today_from_tz(tz).expect("failed to compute today's date for timezone");
        let expected = chrono::Utc::now().with_timezone(&tz).date_naive();
        assert_eq!(result, expected);
    }

    #[test]
    fn trait_default_today_is_used() {
        let provider = SystemTimeProvider;
        let tz: Tz = "UTC".parse().expect("failed to parse timezone 'UTC'");
        let expected = provider.now(tz).date_naive();
        let today = provider.today(tz);
        assert_eq!(today, expected);
    }

    #[tokio::test]
    async fn errors_when_no_timezone() {
        let path = config::generate_path()
            .await
            .expect("failed to generate config path");
        let config = Config::new(None, path)
            .await
            .expect("failed to create Config with path");
        assert_matches!(config.get_timezone(), Err(Error { .. }));
    }

    #[test]
    fn fallback_to_utc_now_when_today_date_from_tz_fails() {
        let tz: Tz = chrono_tz::UTC;

        let result = time::naive_date_today_from_tz(tz)
            .unwrap_or_else(|_| Utc::now().with_timezone(&tz).date_naive());

        let expected = Utc::now().with_timezone(&tz).date_naive();

        // Allow for edge-of-day differences
        assert!(
            result == expected || (result - expected).num_days().abs() <= 1,
            "Got {result}, expected ~{expected}"
        );
    }
    #[tokio::test]
    async fn test_default_config_uses_system_time_provider() {
        // Create a default config
        let config = Config::default();

        // Parse a timezone (e.g., UTC)
        let tz: Tz = "UTC".parse().expect("failed to parse timezone 'UTC'");

        // Call the `today` method via the `time_provider`
        let today_from_provider = config.time_provider.today(tz);

        // Get today's date directly from `SystemTimeProvider` for comparison
        let system_provider = SystemTimeProvider;
        let today_from_system = system_provider.today(tz);

        // Assert that the `time_provider` in the default config behaves like `SystemTimeProvider`
        assert_eq!(today_from_provider, today_from_system)
    }

    #[test]
    fn test_datetime_from_str_zulu() {
        let tz = Tz::UTC;
        let result = datetime_from_str("2024-01-15T10:30:00Z", tz);
        assert!(result.is_ok());
        let dt = result.expect("should parse Zulu datetime");
        assert_eq!(dt.format(FORMAT_DATE).to_string(), "2024-01-15");
    }

    #[test]
    fn test_datetime_from_str_naive() {
        let tz = Tz::America__Los_Angeles;
        let result = datetime_from_str("2024-01-15T10:30:00", tz);
        assert!(result.is_ok());
    }

    #[test]
    fn test_datetime_from_str_long() {
        let tz = Tz::UTC;
        // 27-character format: YYYY-MM-DDTHH:MM:SS.ffffffZ
        let result = datetime_from_str("2024-01-15T10:30:00.000000Z", tz);
        assert!(result.is_ok());
    }

    #[test]
    fn test_datetime_from_str_invalid_length() {
        let tz = Tz::UTC;
        let result = datetime_from_str("2024", tz);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.source, "datetime_from_str");
    }

    #[test]
    fn test_date_from_str_date_only() {
        let tz = Tz::UTC;
        let result = date_from_str("2024-01-15", tz);
        assert!(result.is_ok());
        assert_eq!(
            result.expect("should parse date-only string").to_string(),
            "2024-01-15"
        );
    }

    #[test]
    fn test_date_from_str_datetime_naive() {
        let tz = Tz::UTC;
        let result = date_from_str("2024-01-15T10:30:00", tz);
        assert!(result.is_ok());
        assert_eq!(
            result
                .expect("should parse datetime-naive string")
                .to_string(),
            "2024-01-15"
        );
    }

    #[test]
    fn test_date_from_str_datetime_zulu() {
        let tz = Tz::UTC;
        let result = date_from_str("2024-01-15T10:30:00Z", tz);
        assert!(result.is_ok());
    }

    #[test]
    fn test_date_from_str_invalid() {
        let tz = Tz::UTC;
        let result = date_from_str("2024", tz);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.source, "date_from_str");
    }

    #[test]
    fn test_timezone_from_str_invalid() {
        let result = timezone_from_str("Not/ATimezone");
        assert!(result.is_err());
    }

    #[test]
    fn test_timezone_from_str_gmt_positive() {
        // GMT +5:00 -> Etc/GMT-5 (note sign inversion in Etc/GMT)
        let result = timezone_from_str("GMT +5:00");
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_is_date_in_past() {
        let config = crate::test::fixtures::config()
            .await
            .with_timezone("America/Vancouver");
        let past = NaiveDate::from_ymd_opt(2020, 1, 1).expect("valid past date");
        let future = NaiveDate::from_ymd_opt(2099, 1, 1).expect("valid future date");
        assert!(is_date_in_past(past, &config).expect("past should not error"));
        assert!(!is_date_in_past(future, &config).expect("future should not error"));
    }

    #[tokio::test]
    async fn test_naive_date_days_in_future() {
        let config = crate::test::fixtures::config()
            .await
            .with_timezone("America/Vancouver");
        let far_future = NaiveDate::from_ymd_opt(2099, 1, 1).expect("valid future date");
        let days =
            naive_date_days_in_future(far_future, &config).expect("should compute days in future");
        assert!(days > 0);

        let far_past = NaiveDate::from_ymd_opt(2000, 1, 1).expect("valid past date");
        let days_past =
            naive_date_days_in_future(far_past, &config).expect("should compute days in past");
        assert!(days_past < 0);
    }

    #[tokio::test]
    async fn test_date_to_string_today() {
        let config = crate::test::fixtures::config()
            .await
            .with_timezone("America/Vancouver");
        let today = naive_date_today(&config).expect("should get today");
        let result = date_to_string(&today, &config).expect("should format today");
        assert_eq!(result, "Today");
    }

    #[tokio::test]
    async fn test_date_to_string_not_today() {
        let config = crate::test::fixtures::config()
            .await
            .with_timezone("America/Vancouver");
        let past = NaiveDate::from_ymd_opt(2020, 6, 15).expect("valid date");
        let result = date_to_string(&past, &config).expect("should format past date");
        assert_eq!(result, "2020-06-15");
    }

    #[tokio::test]
    async fn test_date_string_to_naive_date() {
        let result = date_string_to_naive_date("2024-03-20");
        assert!(result.is_ok());
        assert_eq!(
            result.expect("should parse date string").to_string(),
            "2024-03-20"
        );
    }

    #[test]
    fn test_date_string_to_naive_date_invalid() {
        let result = date_string_to_naive_date("not-a-date");
        assert!(result.is_err());
    }
}