tod 0.17.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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
use clap::{Parser, Subcommand};
use std::fmt::Write;

use crate::{
    cargo::{self, Version},
    config::{self, Config},
    errors::Error,
    update,
};
use serde_json::Value;
use std::path::PathBuf;
use tokio::io::AsyncWriteExt;

// Values pulled from Cargo.toml
const NAME: &str = env!("CARGO_PKG_NAME");
const VERSION: &str = env!("CARGO_PKG_VERSION");
// Verbose values set at build time
const BUILD_TARGET: &str = env!("BUILD_TARGET");
const BUILD_PROFILE: &str = env!("BUILD_PROFILE");
const BUILD_TIMESTAMP: &str = env!("BUILD_TIMESTAMP");

#[derive(Subcommand, Debug, Clone)]
pub enum ConfigCommands {
    #[clap(alias = "a")]
    /// (a) Get build information about Tod
    About(About),

    #[clap(alias = "v")]
    /// (v) Check to see if tod is on the latest version, returns exit code 1 if out of date. Does not need a configuration file.
    CheckVersion(CheckVersion),

    /// Validate the configuration file and optionally remove invalid values.
    Check(ConfigCheck),

    /// (r) Deletes the configuration file (if present). Errors if the file does not exist.
    #[clap(alias = "r")]
    Reset(ConfigReset),

    #[clap(alias = "o")]
    /// (o) Open the configuration file in the default editor
    Open(ConfigOpen),

    #[clap(alias = "tz")]
    /// (tz) Automatically set the timezone to your Todoist timezone. Can be overriden with the --timezone flag.
    SetTimezone(SetTimezone),

    #[clap(alias = "e")]
    /// (e) Interactively edit the configuration file
    Edit(Edit),
}
#[derive(Parser, Debug, Clone)]
pub struct CheckVersion {
    /// Automatically install the latest version if available
    #[clap(short = 'f', long)]
    pub force: bool,
    /// Manually specify the method to use for installing updates
    #[clap(long, hide = true)]
    pub repo: Option<String>,
}

#[derive(Parser, Debug, Clone)]
pub struct ConfigReset {
    /// Skip confirmation and force deletion
    #[arg(long)]
    pub force: bool,
}

#[derive(Parser, Debug, Clone)]
pub struct ConfigOpen {}

#[derive(Parser, Debug, Clone)]
pub struct ConfigCheck {}

#[derive(Parser, Debug, Clone)]
pub struct About {}

#[derive(Parser, Debug, Clone)]
pub struct Edit {}

#[derive(Parser, Debug, Clone)]
pub struct SetTimezone {
    #[arg(short, long)]
    /// Explicitly set a `TimeZone`, i.e. "Canada/Pacific")
    timezone: Option<String>,
}
pub async fn check_version(args: &CheckVersion, mock_url: Option<String>) -> Result<String, Error> {
    let CheckVersion { force, repo } = args;

    match cargo::compare_versions(mock_url).await {
        Ok(Version::Latest) => {
            let msg = format!("Tod is up to date with version: {VERSION}");
            Ok(msg)
        }
        Ok(Version::Dated(latest)) => {
            let msg = format!(
                "Tod is out of date. Installed version: {VERSION}, Latest version: {latest}"
            );
            let method = update::get_install_method_string(repo.as_deref());
            let upgrade_cmd = update::get_upgrade_command(repo.as_deref());
            let method_msg = format!("Detected installation method: {method}");
            if *force {
                // For testability, return the message instead of printing
                let mut result = format!("{msg}\n{method_msg}");
                match update::perform_auto_update(repo.as_deref()) {
                    Ok(_) => {
                        result.push_str("\nUpdate completed successfully.");
                        Ok(result)
                    }
                    Err(e) => {
                        let _ = write!(
                            result,
                            "\nAuto-update failed: {e}. To update manually: '{upgrade_cmd}'"
                        );
                        Ok(result)
                    }
                }
            } else {
                println!("{msg}");
                println!("{method_msg}");

                let should_update = match inquire::Confirm::new("Do you want to update?")
                    .with_default(false)
                    .prompt()
                {
                    Ok(true) => true,
                    Ok(false) => false,
                    Err(e) => {
                        println!("Could not prompt for update: {e}. To update: '{upgrade_cmd}'");
                        false
                    }
                };

                if should_update {
                    match update::perform_auto_update(repo.as_deref()) {
                        Ok(msg) => Ok(msg),
                        Err(e) => Ok(format!(
                            "Auto-update failed: {e}. To update manually: '{upgrade_cmd}'"
                        )),
                    }
                } else {
                    Ok(format!("Update skipped. To update: '{upgrade_cmd}'"))
                }
            }
        }
        Err(e) => {
            let msg = format!("Error checking version: {e}");
            Err(Error::new("config_check_version", &msg))
        }
    }
}

pub async fn check(cli_config_path: Option<PathBuf>) -> Result<String, Error> {
    check_with_prompts(
        cli_config_path,
        |message| confirm(message, false),
        |message| confirm(message, false),
    )
    .await
}

async fn check_with_prompts<R, S>(
    cli_config_path: Option<PathBuf>,
    prompt_remove: R,
    prompt_save: S,
) -> Result<String, Error>
where
    R: FnOnce(&str) -> Result<bool, Error>,
    S: FnOnce(&str) -> Result<bool, Error>,
{
    let path = resolve_config_path(cli_config_path).await?;

    if !tokio::fs::try_exists(&path).await? {
        return Err(Error::new(
            "config_check",
            &format!(
                "No config file found at {}. Run 'tod auth login' to initialize tod.",
                path.display()
            ),
        ));
    }

    if Config::load(&path).await.is_ok() {
        return Ok(format!("Config file at {} is valid.", path.display()));
    }

    let json = tokio::fs::read_to_string(&path).await?;
    let value: Value = serde_json::from_str(&json).map_err(|e| {
        Error::new(
            "config_check",
            &format!(
                "Config file at {} is invalid and could not be parsed as JSON:\n{e}",
                path.display()
            ),
        )
    })?;

    let repaired = repair_unknown_fields(value).map_err(|e| {
        Error::new(
            "config_check",
            &format!(
                "Config file at {} is invalid and could not be automatically repaired:\n{e}",
                path.display()
            ),
        )
    })?;

    if repaired.removed_fields.is_empty() {
        return Ok(format!("Config file at {} is valid.", path.display()));
    }

    let field_list = repaired.removed_fields.join(", ");
    if !prompt_remove(&format!(
        "Remove invalid config values ({field_list}) from {}?",
        path.display()
    ))? {
        return Ok("Config check aborted. No changes made.".to_string());
    }

    if !prompt_save(&format!("Save updated config file at {}?", path.display()))? {
        return Ok("Config check completed. No changes saved.".to_string());
    }

    let string = serde_json::to_string_pretty(&repaired.value)?;
    tokio::fs::OpenOptions::new()
        .write(true)
        .read(true)
        .truncate(true)
        .open(&path)
        .await?
        .write_all(string.as_bytes())
        .await?;

    Ok(format!("Removed invalid config values: {field_list}"))
}

struct RepairedConfig {
    value: Value,
    removed_fields: Vec<String>,
}

fn repair_unknown_fields(mut value: Value) -> Result<RepairedConfig, serde_json::Error> {
    let mut removed_fields = Vec::new();

    loop {
        match serde_json::from_value::<Config>(value.clone()) {
            Ok(_) => {
                removed_fields.dedup();
                return Ok(RepairedConfig {
                    value,
                    removed_fields,
                });
            }
            Err(error) => {
                let Some(field) = unknown_field(&error.to_string()) else {
                    return Err(error);
                };

                if remove_key_recursive(&mut value, &field) == 0 {
                    return Err(error);
                }

                removed_fields.push(field);
            }
        }
    }
}

fn unknown_field(error: &str) -> Option<String> {
    error
        .split_once("unknown field `")?
        .1
        .split_once('`')
        .map(|(field, _)| field.to_string())
}

fn remove_key_recursive(value: &mut Value, key: &str) -> usize {
    match value {
        Value::Object(object) => {
            let mut removed = usize::from(object.remove(key).is_some());
            for value in object.values_mut() {
                removed += remove_key_recursive(value, key);
            }
            removed
        }
        Value::Array(values) => values
            .iter_mut()
            .map(|value| remove_key_recursive(value, key))
            .sum(),
        _ => 0,
    }
}

async fn resolve_config_path(cli_config_path: Option<PathBuf>) -> Result<PathBuf, Error> {
    match cli_config_path {
        Some(path) => expand_home_dir(path),
        None => config::generate_path().await,
    }
}

fn expand_home_dir(path: PathBuf) -> Result<PathBuf, Error> {
    if let Some(str_path) = path.to_str()
        && str_path.starts_with('~')
    {
        let home =
            homedir::my_home()?.ok_or_else(|| Error::new("homedir", "Could not get homedir"))?;
        let suffix = str_path.trim_start_matches('~').trim_start_matches('/');
        return Ok(home.join(suffix));
    }

    Ok(path)
}

fn confirm(message: &str, default: bool) -> Result<bool, Error> {
    inquire::Confirm::new(message)
        .with_default(default)
        .prompt()
        .map_err(Error::from)
}

pub async fn set_timezone(config: Config, _args: &SetTimezone) -> Result<String, Error> {
    if config
        .token
        .as_ref()
        .is_none_or(|token| token.trim().is_empty())
    {
        return Err(Error::new(
            "config set-timezone",
            "No auth present - run \"tod auth login\"",
        ));
    }

    match config.set_timezone().await {
        Ok(updated_config) => {
            let tz = updated_config.get_timezone()?;
            Ok(format!("Timezone set successfully to: {tz}"))
        }
        Err(e) => Err(Error::new(
            "config set-timezone",
            &format!("Could not reset timezone in config. {e}"),
        )),
    }
}

pub async fn edit(config: Config, _args: &Edit) -> Result<String, Error> {
    config.edit_interactive().await
}

#[allow(clippy::unused_async)]
pub async fn about(_args: &About) -> Result<String, Error> {
    Ok(format!(
        "APP:             {NAME}\nVERSION:         {VERSION}\nBUILD_PROFILE:   {BUILD_PROFILE}\nBUILD_TARGET:    {BUILD_TARGET}\nBUILD_TIMESTAMP: {BUILD_TIMESTAMP}"
    ))
}

#[cfg(test)]
mod tests {

    use super::*;
    use crate::test::responses::ResponseFromFile;
    use mockito::Server;
    use tempfile::tempdir;

    #[tokio::test]
    async fn test_config_check_removes_unknown_key_when_confirmed() {
        let dir = tempdir().expect("temp dir should be created");
        let path = dir.path().join("tod.cfg");
        let contents = serde_json::json!({
            "path": path,
            "timezone": "UTC",
            "unknown_key": []
        })
        .to_string();
        tokio::fs::write(&path, contents)
            .await
            .expect("config should be written");

        let response = check_with_prompts(Some(path.clone()), |_| Ok(true), |_| Ok(true))
            .await
            .expect("config check should repair unknown config key");

        assert!(response.contains("Removed invalid config values: unknown_key"));
        let updated = tokio::fs::read_to_string(&path)
            .await
            .expect("updated config should be readable");
        assert!(!updated.contains("unknown_key"));
        Config::load(&path)
            .await
            .expect("updated config should validate");
    }

    #[tokio::test]
    async fn test_config_check_does_not_save_when_declined() {
        let dir = tempdir().expect("temp dir should be created");
        let path = dir.path().join("tod.cfg");
        let contents = serde_json::json!({
            "path": path,
            "timezone": "UTC",
            "unknown_key": []
        })
        .to_string();
        tokio::fs::write(&path, &contents)
            .await
            .expect("config should be written");

        let response = check_with_prompts(Some(path.clone()), |_| Ok(true), |_| Ok(false))
            .await
            .expect("config check should complete without saving");

        assert_eq!(response, "Config check completed. No changes saved.");
        let unchanged = tokio::fs::read_to_string(&path)
            .await
            .expect("config should be readable");
        assert_eq!(unchanged, contents);
    }

    #[tokio::test]
    async fn test_config_check_missing_file_returns_init_guidance() {
        let dir = tempdir().expect("temp dir should be created");
        let path = dir.path().join("missing.cfg");

        let error = check_with_prompts(Some(path.clone()), |_| Ok(true), |_| Ok(true))
            .await
            .expect_err("missing config should fail");

        assert_eq!(error.source, "config_check");
        assert!(
            error
                .message
                .contains("Run 'tod auth login' to initialize tod."),
            "missing config should guide user to auth login"
        );
    }

    #[tokio::test]
    async fn test_config_check_aborts_when_remove_declined() {
        let dir = tempdir().expect("temp dir should be created");
        let path = dir.path().join("tod.cfg");
        let contents = serde_json::json!({
            "path": path,
            "timezone": "UTC",
            "unknown_key": []
        })
        .to_string();
        tokio::fs::write(&path, &contents)
            .await
            .expect("config should be written");

        let response = check_with_prompts(Some(path.clone()), |_| Ok(false), |_| Ok(true))
            .await
            .expect("config check should abort when remove prompt is declined");

        assert_eq!(response, "Config check aborted. No changes made.");
        let unchanged = tokio::fs::read_to_string(&path)
            .await
            .expect("config should still be readable");
        assert_eq!(unchanged, contents);
    }

    #[tokio::test]
    async fn test_config_check_reports_parse_error_for_invalid_json() {
        let dir = tempdir().expect("temp dir should be created");
        let path = dir.path().join("tod.cfg");
        tokio::fs::write(&path, "{ invalid")
            .await
            .expect("invalid config should be written");

        let error = check_with_prompts(Some(path.clone()), |_| Ok(true), |_| Ok(true))
            .await
            .expect_err("invalid JSON should fail config check");

        assert_eq!(error.source, "config_check");
        assert!(
            error.message.contains("could not be parsed as JSON"),
            "Expected parse guidance in error message, got: {}",
            error.message
        );
    }

    #[tokio::test]
    async fn test_config_check_reports_unrepairable_config_error() {
        let dir = tempdir().expect("temp dir should be created");
        let path = dir.path().join("tod.cfg");
        let contents = serde_json::json!({
            "path": path,
            "timezone": 123
        })
        .to_string();
        tokio::fs::write(&path, contents)
            .await
            .expect("invalid config should be written");

        let error = check_with_prompts(Some(path.clone()), |_| Ok(true), |_| Ok(true))
            .await
            .expect_err("non-repairable config should fail");

        assert_eq!(error.source, "config_check");
        assert!(
            error
                .message
                .contains("could not be automatically repaired"),
            "Expected repair guidance in error message, got: {}",
            error.message
        );
    }

    #[tokio::test]
    async fn test_config_check_valid_file_returns_valid_message() {
        let dir = tempdir().expect("temp dir should be created");
        let path = dir.path().join("tod.cfg");
        Config::default_test()
            .with_path(path.clone())
            .create()
            .await
            .expect("valid config should be created");

        let response = check_with_prompts(Some(path.clone()), |_| Ok(true), |_| Ok(true))
            .await
            .expect("valid config should pass check");

        assert_eq!(
            response,
            format!("Config file at {} is valid.", path.display())
        );
    }

    #[tokio::test]
    async fn test_config_check_version_outdated() {
        // Start mock server
        let mut server = Server::new_async().await;

        // Mock the crates.io versions endpoint
        let mock = server
            .mock("GET", "/v1/crates/tod/versions")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                ResponseFromFile::Versions
                    .read_with_version("999.99.999")
                    .await,
            )
            .create_async()
            .await;

        let args = CheckVersion {
            force: true,
            repo: None,
        };

        // Run the version check
        let response = check_version(&args, Some(server.url()))
            .await
            .expect("Expected version check to succeed");

        // Print full output for debugging if test fails
        println!("Version check output:\n{response}");

        // Assertions — robust against changing installed version
        assert!(
            response.contains("Tod is out of date"),
            "Missing 'Tod is out of date' message"
        );
        assert!(
            response.contains("Installed version:"),
            "Missing installed version line"
        );
        assert!(
            response.contains("Latest version: 999.99.999"),
            "Missing latest version string"
        );
        assert!(
            response.contains("Detected installation method:"),
            "Missing installation method detection"
        );
        assert!(
            response.contains("Auto-update failed:"),
            "Missing auto-update failure notice"
        );
        assert!(
            response.contains("https://github.com/tod-org/tod#installation"),
            "Missing manual update link"
        );

        // Ensure the mock was actually called
        mock.assert();
    }
    #[tokio::test]
    async fn test_set_timezone_requires_auth() {
        let mut config = Config::default_test();
        config.token = None;

        let error = set_timezone(config, &SetTimezone { timezone: None })
            .await
            .expect_err("set-timezone should fail when no auth token is present");

        assert_eq!(error.source, "config set-timezone");
        assert!(
            error
                .message
                .contains("No auth present - run \"tod auth login\""),
            "error should guide user to auth login"
        );
    }

    #[test]
    fn remove_key_recursive_from_array_of_objects() {
        let mut value = serde_json::json!({
            "items": [
                {"keep": 1, "bad": "x"},
                {"keep": 2, "bad": "y"},
                {"keep": 3}
            ]
        });
        let removed = remove_key_recursive(&mut value, "bad");
        assert_eq!(removed, 2);
        // Verify the key is gone from array elements
        let items = value["items"].as_array().expect("items should be an array");
        assert!(items[0]["bad"].is_null());
        assert!(items[1]["bad"].is_null());
        assert_eq!(items[0]["keep"], serde_json::json!(1));
    }

    #[test]
    fn remove_key_recursive_from_nested_arrays() {
        let mut value = serde_json::json!({
            "outer": [
                {"inner": [{"bad": 1}, {"ok": 2}]},
                {"inner": [{"bad": 3}]}
            ]
        });
        let removed = remove_key_recursive(&mut value, "bad");
        assert_eq!(removed, 2);
    }

    #[test]
    fn remove_key_recursive_no_match_returns_zero() {
        let mut value = serde_json::json!({"a": 1, "b": [{"c": 2}]});
        let removed = remove_key_recursive(&mut value, "nonexistent");
        assert_eq!(removed, 0);
    }
}