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
use clap::{Parser, Subcommand};

use crate::{config::Config, debug, errors::Error, input, lists::Flag, projects, todoist};

#[derive(Subcommand, Debug, Clone)]
pub enum ProjectCommands {
    #[clap(alias = "c")]
    /// (c) Create a new project in Todoist and add to config
    Create(Create),

    #[clap(alias = "l")]
    /// (l) List all of the projects in config
    List(List),

    #[clap(alias = "r")]
    /// (r) Remove a project from config (not Todoist)
    Remove(Remove),

    #[clap(alias = "d")]
    /// (d) Remove a project from Todoist
    Delete(Delete),

    #[clap(alias = "n")]
    /// (n) Rename a project in config (not in Todoist)
    Rename(Rename),

    #[clap(alias = "i")]
    /// (i) Get projects from Todoist and prompt to add to config
    Import(Import),

    #[clap(alias = "e")]
    /// (e) Empty a project by putting tasks in other projects
    Empty(Empty),
}

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

#[derive(Parser, Debug, Clone)]
pub struct Create {
    #[arg(short, long)]
    /// Project name
    name: Option<String>,

    #[arg(short, long)]
    /// Project description
    description: Option<String>,

    #[arg(short, long, default_value_t = false)]
    /// Whether the project is marked as favorite
    is_favorite: bool,
}

#[derive(Parser, Debug, Clone)]
pub struct Import {
    #[arg(
        short = 'a',
        long,
        default_value_t = false,
        conflicts_with_all = ["project", "id"]
    )]
    /// Add all projects to config that are not there already
    auto: bool,

    #[arg(short = 'p', long, conflicts_with = "id")]
    /// Import a specific project by name from Todoist
    project: Option<String>,

    #[arg(short = 'i', long, conflicts_with = "project")]
    /// Import a specific project by Todoist project ID
    id: Option<String>,
}

#[derive(Parser, Debug, Clone)]
pub struct Remove {
    #[arg(short = 'a', long, default_value_t = false)]
    /// Remove all projects from config that are not in Todoist
    auto: bool,

    #[arg(short = 'r', long, default_value_t = false)]
    /// Keep repeating prompt to remove projects. Use Ctrl/CMD + c to exit.
    repeat: bool,

    #[arg(short = 'l', long, default_value_t = false)]
    /// Remove all projects from config
    all: bool,

    #[arg(short, long)]
    /// Project to remove
    project: Option<String>,
}

#[derive(Parser, Debug, Clone)]
pub struct Delete {
    #[arg(short, long, default_value_t = false)]
    /// Skip deletion confirmation when the project has tasks
    force: bool,

    #[arg(short = 'r', long, default_value_t = false)]
    /// Keep repeating prompt to delete projects. Use Ctrl/CMD + c to exit.
    repeat: bool,

    #[arg(short, long)]
    /// Project to remove
    project: Option<String>,
}

#[derive(Parser, Debug, Clone)]
pub struct Rename {
    #[arg(short, long)]
    /// Project to rename
    project: Option<String>,

    #[arg(short, long)]
    /// New project name
    name: Option<String>,
}
#[derive(Parser, Debug, Clone)]
pub struct Empty {
    #[arg(short, long)]
    /// Project to remove
    project: Option<String>,
}

pub async fn create(config: &mut Config, args: &Create) -> Result<String, Error> {
    let Create {
        name,
        description,
        is_favorite,
    } = args;
    let name = super::fetch_string(name.as_deref(), config, input::NAME)?;
    let description = description.as_deref().unwrap_or_default();

    projects::create(config, name, description, *is_favorite).await
}

pub async fn list(config: &mut Config, _args: &List) -> Result<String, Error> {
    projects::list(config).await
}

pub async fn remove(config: &mut Config, args: &Remove) -> Result<String, Error> {
    let Remove {
        all,
        auto,
        project,
        repeat,
    } = args;
    match (all, auto) {
        (true, false) => projects::remove_all(config).await,
        (false, true) => projects::remove_auto(config).await,
        (false, false) => loop {
            let project = match super::fetch_project(project.as_deref(), config).await? {
                Flag::Project(project) => project,
                Flag::Filter(_) => unreachable!(),
            };
            let value = projects::remove(config, &project).await;

            if !repeat {
                return value;
            }
        },
        (_, _) => Err(Error::new("project_remove", "Incorrect flags provided")),
    }
}

pub async fn delete(config: &mut Config, args: &Delete) -> Result<String, Error> {
    let Delete {
        force,
        project,
        repeat,
    } = args;
    loop {
        let project = match super::fetch_project(project.as_deref(), config).await? {
            Flag::Project(project) => project,
            Flag::Filter(_) => unreachable!(),
        };
        let tasks = todoist::all_tasks_by_project(config, &project, None).await?;

        if !force && !tasks.is_empty() {
            println!();
            let options = vec![input::CANCEL, input::DELETE];
            let num_tasks = tasks.len();
            let desc = format!("Project has {num_tasks} tasks, confirm deletion");
            let result = input::select(&desc, options, config.mock_select)?;

            if result == input::CANCEL {
                return Ok("Cancelled".into());
            }
        }
        let value = projects::delete(config, &project).await;

        if !repeat {
            return value;
        }
    }
}

pub async fn rename(config: &mut Config, args: &Rename) -> Result<String, Error> {
    let Rename { project, name } = args;
    let project = match super::fetch_project(project.as_deref(), config).await? {
        Flag::Project(project) => project,
        Flag::Filter(_) => unreachable!(),
    };
    debug::maybe_print(
        config,
        &format!("Calling projects::rename with project:\n{project}"),
    );
    projects::rename(config, &project, name.as_deref()).await
}

pub async fn import(config: &mut Config, args: &Import) -> Result<String, Error> {
    let Import { auto, project, id } = args;
    projects::import(config, auto, project.as_deref(), id.as_deref()).await
}

pub async fn empty(config: &mut Config, args: &Empty) -> Result<String, Error> {
    let Empty { project } = args;
    let project = match super::fetch_project(project.as_deref(), config).await? {
        Flag::Project(project) => project,
        Flag::Filter(_) => unreachable!(),
    };

    projects::empty(config, &project).await
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test;
    use crate::test::responses::ResponseFromFile;

    #[tokio::test]
    async fn remove_rejects_conflicting_all_and_auto_flags() {
        let mut config = Config::default_test();
        let args = Remove {
            auto: true,
            repeat: false,
            all: true,
            project: None,
        };

        let error = remove(&mut config, &args)
            .await
            .expect_err("conflicting flags should fail");
        assert_eq!(error.source, "project_remove");
        assert_eq!(error.message, "Incorrect flags provided");
    }

    #[tokio::test]
    async fn delete_force_skips_confirmation_prompt_for_non_empty_project() {
        let mut server = mockito::Server::new_async().await;

        let _tasks_mock = server
            .mock("GET", "/api/v1/tasks/?project_id=123&limit=200")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(ResponseFromFile::TodayTasks.read().await)
            .create_async()
            .await;

        let delete_mock = server
            .mock("DELETE", "/api/v1/projects/123")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(ResponseFromFile::Project.read().await)
            .create_async()
            .await;

        let mut config = test::fixtures::config()
            .await
            .with_mock_url(server.url())
            .mock_select(0)
            .create()
            .await
            .expect("config should be created");

        let args = Delete {
            force: true,
            project: Some("myproject".into()),
            repeat: false,
        };

        let result = delete(&mut config, &args)
            .await
            .expect("force delete should succeed");

        assert!(!result.contains("Cancelled"));
        delete_mock.assert_async().await;
    }

    #[tokio::test]
    async fn delete_cancels_when_user_selects_cancel_for_non_empty_project() {
        let mut server = mockito::Server::new_async().await;

        let tasks_mock = server
            .mock("GET", "/api/v1/tasks/?project_id=123&limit=200")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(ResponseFromFile::TodayTasks.read().await)
            .create_async()
            .await;

        let mut config = test::fixtures::config()
            .await
            .with_mock_url(server.url())
            .mock_select(0) // selects CANCEL (first option) in confirmation prompt
            .create()
            .await
            .expect("config should be created");

        let args = Delete {
            force: false,
            project: Some("myproject".into()),
            repeat: false,
        };

        let result = delete(&mut config, &args)
            .await
            .expect("cancel should not error");

        assert_eq!(result, "Cancelled");
        tasks_mock.assert_async().await;
    }

    #[tokio::test]
    async fn delete_confirms_and_removes_project_when_user_selects_delete() {
        let mut server = mockito::Server::new_async().await;

        let _tasks_mock = server
            .mock("GET", "/api/v1/tasks/?project_id=123&limit=200")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(ResponseFromFile::TodayTasks.read().await)
            .create_async()
            .await;

        let delete_mock = server
            .mock("DELETE", "/api/v1/projects/123")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(ResponseFromFile::Project.read().await)
            .create_async()
            .await;

        let mut config = test::fixtures::config()
            .await
            .with_mock_url(server.url())
            .mock_select(1) // selects DELETE (second option) in confirmation prompt
            .create()
            .await
            .expect("config should be created");

        let args = Delete {
            force: false,
            project: Some("myproject".into()),
            repeat: false,
        };

        let result = delete(&mut config, &args)
            .await
            .expect("delete should succeed");

        assert!(!result.contains("Cancelled"));
        delete_mock.assert_async().await;
    }

    #[test]
    fn delete_force_flag_parses() {
        let args =
            Delete::try_parse_from(["tod", "--force"]).expect("delete arguments should parse");
        assert!(args.force);
    }

    #[test]
    fn rename_name_flag_parses() {
        let args = Rename::try_parse_from(["tod", "-p", "myproject", "-n", "renamed"])
            .expect("rename arguments should parse");
        assert_eq!(args.project.as_deref(), Some("myproject"));
        assert_eq!(args.name.as_deref(), Some("renamed"));
    }

    #[tokio::test]
    async fn rename_uses_name_flag_without_prompt() {
        let mut config = test::fixtures::config()
            .await
            .create()
            .await
            .expect("creating config should succeed");
        let args = Rename {
            project: Some("myproject".to_string()),
            name: Some("renamed-project".to_string()),
        };

        let result = rename(&mut config, &args).await;
        assert_eq!(result, Ok("".to_string()));

        let projects = config
            .projects()
            .await
            .expect("loading projects should succeed");
        let project_names = projects
            .iter()
            .map(|project| project.name.as_str())
            .collect::<Vec<&str>>();

        assert!(project_names.contains(&"renamed-project"));
        assert!(!project_names.contains(&"myproject"));
    }
}