onetaskgraph 0.3.2

One interface over the ticketing systems your work lives in.
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
//! A GitHub board's `status_mapping` scoped by item kind, through the real command-line
//! boundary against the loopback board.
//!
//! A task and a project are both issues on one board and both kinds' names are options of its
//! one `Status` field, so every journey here configures the two halves of one mapping apart
//! and holds the binary to each: which option a status is written as, which status an option
//! reads as, what `--status` keeps, what `sources fields` asks the field to hold — and that a
//! status one kind has no option for is refused on every verb that writes one before the board
//! is sent a single mutation.

use std::path::PathBuf;
use std::process::Output;

use serde_json::{Value, json};

use crate::common::{Sandbox, stderr, stdout};
use crate::fixtures::{GitHubBoardFields, document, github_projects_with_board};

/// One sandbox configuring the fixture board as `board`, with `status_mapping` in place of the
/// shared one, and a folder of Markdown as `plans` holding a task `A` and a project `P`.
struct Setup {
    sandbox: Sandbox,
    board: GitHubBoardFields,
    root: PathBuf,
}

impl Setup {
    fn new(status_mapping: Value) -> Self {
        let sandbox = Sandbox::new();
        let root = sandbox.subdirectory("plans");
        std::fs::create_dir_all(root.join("projects")).expect("the project folder");
        std::fs::create_dir_all(root.join("tasks")).expect("the task folder");
        std::fs::write(
            root.join("projects/P.md"),
            "---\ntitle: A plan\nstatus: Doing\n---\nthe plan\n",
        )
        .expect("the project");
        std::fs::write(
            root.join("tasks/A.md"),
            "---\ntitle: A step\nstatus: Todo\n---\nthe step\n",
        )
        .expect("the task");
        std::fs::write(root.join("body.md"), "a new task\n").expect("a body file");
        let (mut config, board) = github_projects_with_board(&sandbox);
        config["status_mapping"] = status_mapping;
        sandbox.project_document(&document(&json!({
            "plans": {"plugin":"local-md","config":{
                "root": root,
                "status_mapping": {"Todo":"todo","Doing":"in-progress","Queued":"queued"}}},
            "board": {"plugin":"github-projects","config":config}
        })));
        Self {
            sandbox,
            board,
            root,
        }
    }

    fn run(&self, arguments: &[&str]) -> Output {
        self.sandbox
            .command()
            .args(arguments)
            .assert()
            .get_output()
            .clone()
    }

    fn json(&self, arguments: &[&str]) -> Value {
        let output = self.run(arguments);
        assert_eq!(
            output.status.code(),
            Some(0),
            "`onetaskgraph {}` failed\n{}",
            arguments.join(" "),
            stderr(&output)
        );
        serde_json::from_str(&stdout(&output)).expect("the command emits JSON")
    }

    /// Every mutation the board has received.
    fn mutations(&self) -> Vec<(String, Value)> {
        self.board
            .served()
            .into_iter()
            .filter(|(query, _)| query.trim_start().starts_with("mutation"))
            .collect()
    }

    /// The ids `list` printed, in order.
    fn ids(&self, arguments: &[&str]) -> Vec<String> {
        self.json(arguments)["items"]
            .as_array()
            .expect("a page")
            .iter()
            .map(|item| item["id"].as_str().expect("a qualified id").to_owned())
            .collect()
    }
}

#[test]
fn a_status_its_kind_has_no_option_for_is_refused_on_every_verb_before_any_mutation() {
    // Each: the mapping, the command, the kind and category it writes, and what else the
    // refusal must name — why the kind has no option, or the option the board lacks.
    let cases: Vec<(Value, Vec<&str>, &str, &str, &str)> = vec![
        // Unconfigured, with no shipped default.
        (
            json!({"todo":"Todo","in-progress":"Doing"}),
            vec![
                "task",
                "create",
                "board",
                "--project",
                "P-1",
                "--title",
                "New",
                "--status",
                "draft",
                "--body-file",
                "BODY",
            ],
            "task",
            "draft",
            "does not name draft",
        ),
        // Disabled for every kind.
        (
            json!({"todo":"Todo","in-progress":"Doing","backlog":null}),
            vec!["task", "status", "set", "board:T-1", "backlog"],
            "task",
            "backlog",
            "sets backlog to null",
        ),
        // Named for the other kind only — the shipped `Cancelled` is not the fallback.
        (
            json!({"todo":"Todo","in-progress":"Doing","cancelled":{"project":"Cancelled"}}),
            vec!["task", "update", "board:T-1", "--status", "cancelled"],
            "task",
            "cancelled",
            "names cancelled for the other kind only",
        ),
        (
            json!({"todo":{"project":"Todo"},"in-progress":"Doing"}),
            vec!["task", "copy", "plans:A", "--to", "board"],
            "task",
            "todo",
            "names todo for the other kind only",
        ),
        (
            json!({"todo":"Todo","in-progress":{"task":"Doing"}}),
            vec!["project", "copy", "plans:P", "--to", "board", "--no-tasks"],
            "project",
            "in-progress",
            "names in-progress for the other kind only",
        ),
        // A mapped option the board's `Status` field lacks.
        (
            json!({"todo":{"task":"Ready","project":"Todo"},"in-progress":"Doing"}),
            vec![
                "task",
                "create",
                "board",
                "--project",
                "P-1",
                "--title",
                "New",
                "--status",
                "todo",
                "--body-file",
                "BODY",
            ],
            "task",
            "todo",
            "\"Ready\"",
        ),
        (
            json!({"todo":{"task":"Ready","project":"Todo"},"in-progress":"Doing"}),
            vec!["task", "status", "set", "board:T-3", "todo"],
            "task",
            "todo",
            "\"Ready\"",
        ),
        (
            json!({"todo":"Todo","in-progress":{"task":"Doing","project":"Active"}}),
            vec!["project", "copy", "plans:P", "--to", "board", "--no-tasks"],
            "project",
            "in-progress",
            "\"Active\"",
        ),
    ];
    for (mapping, command, kind, category, why) in cases {
        let setup = Setup::new(mapping.clone());
        let body = setup.root.join("body.md");
        let command: Vec<&str> = command
            .into_iter()
            .map(|argument| {
                if argument == "BODY" {
                    body.to_str().expect("a UTF-8 path")
                } else {
                    argument
                }
            })
            .collect();
        let output = setup.run(&command);
        let said = stderr(&output);
        assert_ne!(
            output.status.code(),
            Some(0),
            "{mapping}: `onetaskgraph {}` was meant to be refused\n{}",
            command.join(" "),
            stdout(&output)
        );
        for part in [
            "board",
            &format!("{kind} status"),
            category,
            &format!("status_mapping.{category}.{kind}"),
            why,
        ] {
            assert!(
                said.contains(part),
                "{mapping}: `onetaskgraph {}` was refused without naming {part:?}:\n{said}",
                command.join(" ")
            );
        }
        assert_eq!(
            setup.mutations(),
            Vec::<(String, Value)>::new(),
            "{mapping}: `onetaskgraph {}` sent a mutation before refusing",
            command.join(" ")
        );
    }
}

#[test]
fn a_project_copy_over_an_item_at_an_option_the_board_lacks_sends_no_mutation_or_restore() {
    // `todo` is the board's `Todo` for both kinds; `in-progress` is `Active` for a project,
    // which the board's `Status` field does not have.
    let setup = Setup::new(json!({
        "todo": "Todo",
        "in-progress": {"task": "Doing", "project": "Active"},
    }));
    let project = setup.root.join("projects/P.md");
    std::fs::write(
        &project,
        "---\ntitle: A plan\nstatus: Todo\n---\nthe plan\n",
    )
    .expect("the project at todo");
    let copied = setup.json(&[
        "--json",
        "project",
        "copy",
        "plans:P",
        "--to",
        "board",
        "--no-tasks",
    ]);
    let landed = copied["items"][0]["destination"]
        .as_str()
        .unwrap_or_else(|| panic!("a destination: {copied:#}"))
        .to_owned();

    // The same project, now in progress: the copy finds the item it landed, and refuses.
    let held = std::fs::read_to_string(&project).expect("the project as the copy left it");
    std::fs::write(&project, held.replace("status: Todo", "status: Doing"))
        .expect("the project in progress");
    let from = setup.mutations().len();
    let output = setup.run(&["project", "copy", "plans:P", "--to", "board", "--no-tasks"]);
    assert_ne!(output.status.code(), Some(0), "{}", stdout(&output));
    let said = stderr(&output);
    for part in [
        "board",
        "project status",
        "in-progress",
        "status_mapping.in-progress.project",
        "\"Active\"",
    ] {
        assert!(
            said.contains(part),
            "refused without naming {part:?}:\n{said}"
        );
    }
    assert_eq!(
        setup.mutations()[from..].to_vec(),
        Vec::<(String, Value)>::new(),
        "an update refused before any write sends no write and no restore"
    );
    let shown = setup.json(&["--json", "project", "show", &landed]);
    assert_eq!(
        shown["items"][0]["item"]["status"]["name"], "Todo",
        "{shown:#}"
    );
}

#[test]
fn a_copy_refused_after_it_overwrote_a_board_project_puts_that_project_back() {
    // A task's `todo` is `Ready`, which the board lacks; a project's is the board's `Todo`.
    let setup = Setup::new(json!({
        "todo": {"task": "Ready", "project": "Todo"},
        "in-progress": "Doing",
    }));
    let project = setup.root.join("projects/P.md");
    std::fs::write(
        &project,
        "---\ntitle: A plan\nstatus: Todo\n---\nthe plan\n",
    )
    .expect("the project at todo");
    let copied = setup.json(&[
        "--json",
        "project",
        "copy",
        "plans:P",
        "--to",
        "board",
        "--no-tasks",
    ]);
    let landed = copied["items"][0]["destination"]
        .as_str()
        .unwrap_or_else(|| panic!("a destination: {copied:#}"))
        .to_owned();

    // Retitled, and now carrying its task: the project's update lands and changes the issue,
    // then the task's status is refused, and the copy's undo writes the issue back.
    let held = std::fs::read_to_string(&project).expect("the project as the copy left it");
    std::fs::write(
        &project,
        held.replace("title: A plan", "title: A renamed plan"),
    )
    .expect("the project retitled");
    std::fs::write(
        setup.root.join("tasks/A.md"),
        "---\ntitle: A step\nstatus: Todo\nproject: P\n---\nthe step\n",
    )
    .expect("the task under the project");
    let from = setup.mutations().len();
    let output = setup.run(&["project", "copy", "plans:P", "--to", "board"]);
    assert_ne!(output.status.code(), Some(0), "{}", stdout(&output));
    let said = stderr(&output);
    assert!(
        said.contains("status_mapping.todo.task") && said.contains("\"Ready\""),
        "{said}"
    );
    let titles = setup.mutations()[from..]
        .iter()
        .filter_map(|(_, variables)| variables["input"]["title"].as_str().map(str::to_owned))
        .collect::<Vec<_>>();
    assert_eq!(
        titles,
        ["A renamed plan", "A plan"],
        "the project's write, then its restore — and no write of the refused task"
    );
    let shown = setup.json(&["--json", "project", "show", &landed]);
    assert_eq!(shown["items"][0]["item"]["title"], "A plan", "{shown:#}");
}

#[test]
fn each_kind_is_written_read_and_narrowed_through_its_own_half_of_the_mapping() {
    // The board's `Todo` is a task's `todo` and a project's `queued`, and its `Doing` is a
    // project's `in-progress` and no task status at all.
    let setup = Setup::new(json!({
        "todo": {"task": "Todo"},
        "queued": {"project": "Todo"},
        "in-progress": {"project": "Doing"},
    }));
    let statuses = |list: &[&str]| -> Vec<(String, Value)> {
        setup.json(list)["items"]
            .as_array()
            .expect("a page")
            .iter()
            .map(|item| {
                (
                    item["id"].as_str().expect("an id").to_owned(),
                    item["item"]["status"].clone(),
                )
            })
            .collect()
    };
    assert_eq!(
        statuses(&["--json", "task", "list", "--source", "board"]),
        [
            (
                "board:T-1".to_owned(),
                json!({"category": "todo", "name": "Todo"})
            ),
            // Closed as completed: the state decides, whatever the option.
            (
                "board:T-2".to_owned(),
                json!({"category": "done", "name": "Shipped"})
            ),
            (
                "board:T-3".to_owned(),
                json!({"category": "todo", "name": "Todo"})
            ),
            // `Doing` is no task category here, so it is `unknown` under its own name.
            (
                "board:T-4".to_owned(),
                json!({"category": "unknown", "name": "Doing"})
            ),
        ]
    );
    assert_eq!(
        statuses(&["--json", "project", "list", "--source", "board"]),
        [
            (
                "board:P-1".to_owned(),
                json!({"category": "in-progress", "name": "Doing"})
            ),
            (
                "board:P-2".to_owned(),
                json!({"category": "queued", "name": "Todo"})
            ),
        ]
    );
    for (status, tasks, projects) in [
        ("todo", vec!["board:T-1", "board:T-3"], vec![]),
        ("queued", vec![], vec!["board:P-2"]),
        ("in-progress", vec![], vec!["board:P-1"]),
        ("unknown", vec!["board:T-4"], vec![]),
        ("done", vec!["board:T-2"], vec![]),
    ] {
        assert_eq!(
            setup.ids(&[
                "--json", "task", "list", "--source", "board", "--status", status
            ]),
            tasks,
            "tasks at {status}"
        );
        assert_eq!(
            setup.ids(&[
                "--json", "project", "list", "--source", "board", "--status", status
            ]),
            projects,
            "projects at {status}"
        );
    }

    // A task set to `todo` lands on `Todo`, the option a project reads as `queued`, and is
    // read back as the task's own category; a project copied in at `queued` lands on that
    // same option and reads back as `queued`.
    let set = setup.json(&["--json", "task", "status", "set", "board:T-4", "todo"]);
    assert_eq!(
        set["status"],
        json!({"category": "todo", "name": "Todo"}),
        "{set}"
    );
    std::fs::write(
        setup.root.join("projects/P.md"),
        "---\ntitle: A plan\nstatus: Queued\n---\nthe plan\n",
    )
    .expect("the project");
    setup.json(&[
        "--json",
        "project",
        "copy",
        "plans:P",
        "--to",
        "board",
        "--no-tasks",
    ]);
    let queued = statuses(&[
        "--json", "project", "list", "--source", "board", "--status", "queued",
    ]);
    assert_eq!(queued.len(), 2, "P-2 and the copy: {queued:?}");
    assert!(
        queued
            .iter()
            .all(|(_, status)| *status == json!({"category": "queued", "name": "Todo"})),
        "{queued:?}"
    );
}

#[test]
fn sources_fields_names_each_kinds_missing_options_and_apply_adds_both_keeping_every_id() {
    let setup = Setup::new(json!({
        "todo": "Todo", "in-progress": "Doing",
        "draft": {"task": "Idea"},
        "queued": {"task": "Queued", "project": "Waiting"},
        "done": {"project": "Shipped"},
    }));
    let before = setup.board.status_options();

    let planned = setup.json(&["--json", "sources", "fields", "board"]);
    let status = &planned["fields"][0];
    assert_eq!(status["field"], "Status");
    assert_eq!(status["missing"], json!(["Idea", "Waiting"]));
    assert_eq!(
        status["kinds"],
        json!([{"kind": "task", "missing": ["Idea"]},
               {"kind": "project", "missing": ["Waiting"]}])
    );
    assert_eq!(status["outcome"], "planned");
    assert!(
        planned["fields"][1].get("kinds").is_none(),
        "Priority carries no kinds: {}",
        planned["fields"][1]
    );
    let text = setup.run(&["sources", "fields", "board"]);
    assert_eq!(
        stdout(&text),
        "board: missing configured Status options: task: Idea; project: Waiting\n\
         board: missing configured Priority options: none\n"
    );
    assert!(setup.mutations().is_empty(), "a plan writes nothing");

    let applied = setup.run(&["sources", "fields", "board", "--apply"]);
    assert_eq!(applied.status.code(), Some(0), "{}", stderr(&applied));
    assert_eq!(
        stdout(&applied),
        "board: added and verified Status options: task: Idea; project: Waiting\n\
         board: missing configured Priority options: none\n"
    );
    let sent = setup.mutations();
    assert_eq!(sent.len(), 1, "one whole-list update: {sent:?}");
    let options = sent[0].1["input"]["singleSelectOptions"]
        .as_array()
        .expect("the whole option list")
        .clone();
    for old in &before {
        assert!(
            options.contains(old),
            "every existing option goes back with its id: {old} in {options:?}"
        );
    }
    let after = setup.board.status_options();
    for old in &before {
        assert!(after.contains(old), "{old} kept its id: {after:?}");
    }
    for added in ["Idea", "Waiting"] {
        assert!(
            after.iter().any(|option| option["name"] == added),
            "{added} was added: {after:?}"
        );
    }

    // The board now holds both kinds' options: nothing is missing, and a task's `draft` lands
    // on the option only a task maps.
    let again = setup.json(&["--json", "sources", "fields", "board"]);
    assert_eq!(again["fields"][0]["missing"], json!([]));
    assert!(again["fields"][0].get("kinds").is_none(), "{again}");
    let set = setup.json(&["--json", "task", "status", "set", "board:T-3", "draft"]);
    assert_eq!(
        set["status"],
        json!({"category": "draft", "name": "Idea"}),
        "{set}"
    );
}