deedar-cli 0.7.1

Operator path: deedar create/get/list/trail/evidence/delete/leave/timestamp/current/migrate
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
//! A value is stored as the seat wrote it, even when it is spelled like a flag.
//!
//! `--help`, `-h`, `--version`, `-V` and `--url` are flags only in flag
//! position: before the verb, or among that verb's own flags. The word after
//! `--excerpt`, `--name` or `--step` is the value.

use std::path::Path;
use std::process::{Command, Output};

fn deedar(home: &Path, args: &[&str]) -> Output {
    Command::new(env!("CARGO_BIN_EXE_deedar"))
        .args(args)
        .env("HOME", home)
        .env("XDG_CONFIG_HOME", home.join(".config"))
        .env("XDG_DATA_HOME", home.join(".local/share"))
        .env("DEEDAR_HOST_SIGNING_KEY", "off")
        .env_remove("DEEDAR_HOST_KEY")
        .env_remove("DEEDAR_URL")
        .current_dir(home)
        .output()
        .expect("deedar runs")
}

fn ok(home: &Path, args: &[&str]) -> String {
    let out = deedar(home, args);
    assert!(
        out.status.success(),
        "deedar {args:?}\nstdout: {}\nstderr: {}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
    assert_eq!(String::from_utf8_lossy(&out.stderr).as_ref(), "");
    String::from_utf8(out.stdout).expect("stdout is utf8")
}

fn store_url(home: &Path) -> String {
    format!("file://{}", home.join("store").display())
}

fn create_quote(home: &Path, url: &str, id: &str, flags: &[&str]) -> String {
    let mut args = vec!["--url", url, "create", "quote", "--id", id];
    args.extend_from_slice(flags);
    args.extend_from_slice(&["--src-url", "https://e.invalid", "--agent", "me"]);
    ok(home, &args)
}

fn line(text: &str, expected: &str) {
    assert!(text.lines().any(|line| line == expected), "{text}");
}

const USAGE: &str = "\
usage: deedar [--url FILE] create|get|list|trail|evidence|delete|leave|timestamp|current|log|export|import|check|vouch|migrate|host|url
deedar --help            this page
deedar help              this page
deedar VERB --help       the page for one verb, with its flags
deedar help VERB         the same page
evidence, current and export take one id, several ids, or - to read them from stdin
list takes --kind KIND, --agent ID and --text WORDS
log takes head, list, audit, backfill, prove ID, or bridge SIZE
import takes a satchel directory, and --allow-unsigned-head for a missing or unlisted signature
check takes a satchel directory, --since KEPT_HEAD, --bridge FILE and --keep FILE; vouch takes sign FILE or check FILE
leave takes an id and a destination directory
timestamp writes a .tsr when DEEDAR_TSA answers, and names the .tsq when that variable is unset
host says whether the store's layout lists the host signing key, and exits 1 when it does not
host accept adds the host signing key to the layout as a signer, and leaves every other line
url prints the store this command resolved
";

const CREATE_HELP: &str = "\
deedar create KIND --agent WHO [flags]
kinds: file set quote patch mailDraft clip page form table procedure event
create file wants --path FILE and --agent WHO
create set wants --member PATH (repeatable) and --agent WHO
create quote wants --excerpt TEXT and --src-url URL
create patch wants --tree TREE and --diff PATH
create mailDraft wants --message-id <local@domain>, --subject TEXT and --path FILE
create clip wants --clip-src PATH and --path FILE
create page wants --page-url URL and --snapshot FILE
create form wants --blank NAME, --field name=value and --path FILE
create table wants --measure name=value
create procedure wants --step TEXT
create event wants --title or --name, --when WHEN, --where WHERE and --who WHO
--name NAME     defaults to the kind, or to --title for an event
--path FILE     the bytes for kind file (not --field path=)
--supersedes ID the deed this one revises
the same create again prints the deed it froze and exits 0; other bytes
under the same name are refused: revise with --name NAME-v2 --supersedes ID
the last stdout line is accession=ID: cite that ID, not the file= line
";

#[test]
fn an_excerpt_equal_to_help_is_stored() {
    let home = tempfile::tempdir().unwrap();
    let home = home.path();
    let url = store_url(home);
    let made = create_quote(home, &url, "deed-quote-h", &["--excerpt", "--help"]);
    line(&made, "excerpt=--help");
    line(&made, "accession=deed-quote-h");
    let got = ok(home, &["--url", &url, "get", "deed-quote-h"]);
    line(&got, "excerpt=--help");
}

#[test]
fn an_excerpt_equal_to_short_version_is_stored() {
    let home = tempfile::tempdir().unwrap();
    let home = home.path();
    let url = store_url(home);
    let made = create_quote(home, &url, "deed-quote-v", &["--excerpt", "-V"]);
    line(&made, "excerpt=-V");
    line(&made, "accession=deed-quote-v");
    let got = ok(home, &["--url", &url, "get", "deed-quote-v"]);
    line(&got, "excerpt=-V");
}

#[test]
fn a_name_equal_to_url_is_stored() {
    let home = tempfile::tempdir().unwrap();
    let home = home.path();
    let url = store_url(home);
    let made = create_quote(
        home,
        &url,
        "deed-quote-u",
        &["--name", "--url", "--excerpt", "x"],
    );
    assert!(made.contains("name=--url"), "{made}");
    line(&made, "accession=deed-quote-u");
    let got = ok(home, &["--url", &url, "get", "deed-quote-u"]);
    assert!(
        got.lines()
            .any(|line| line.starts_with("id=deed-quote-u ") && line.contains("name=--url")),
        "{got}"
    );
    line(&got, "excerpt=x");
}

#[test]
fn a_step_equal_to_version_is_stored() {
    let home = tempfile::tempdir().unwrap();
    let home = home.path();
    let url = store_url(home);
    // `get` prints the step count. The misread prints `deedar <version>` and
    // stores nothing, so the accession line is what shows the step was kept.
    let made = ok(
        home,
        &[
            "--url",
            &url,
            "create",
            "procedure",
            "--id",
            "deed-procedure-version",
            "--step",
            "--version",
            "--agent",
            "me",
        ],
    );
    line(&made, "steps=1");
    line(&made, "accession=deed-procedure-version");
    assert!(!made.starts_with("deedar "), "{made}");
    let got = ok(home, &["--url", &url, "get", "deed-procedure-version"]);
    line(
        &got,
        "id=deed-procedure-version kind=procedure name=procedure",
    );
    line(&got, "steps=1");
}

/// An unknown word names `--help` and does not create a store.
/// `help` and `help create` are the same pages as the flags.
#[test]
fn an_unknown_command_names_help_and_help_prints_the_page() {
    let home = tempfile::tempdir().unwrap();
    let home = home.path();
    let seat = home.join(".local/share/deedar/store");
    let out = deedar(home, &["foo"]);
    assert_eq!(out.status.code(), Some(1));
    assert_eq!(String::from_utf8_lossy(&out.stdout).as_ref(), "");
    assert_eq!(
        String::from_utf8(out.stderr).expect("stderr is utf8"),
        "deedar: unknown command foo; `deedar --help`\n"
    );
    assert!(!seat.exists(), "an unknown command created the seat store");

    let named = home.join("named-store");
    let named_url = format!("file://{}", named.display());
    let out = deedar(home, &["--url", &named_url, "mcp"]);
    assert_eq!(out.status.code(), Some(1));
    assert_eq!(
        String::from_utf8(out.stderr).expect("stderr is utf8"),
        "deedar: unknown command mcp; `deedar --help`\n"
    );
    assert!(
        !named.exists(),
        "an unknown command created the named store"
    );

    assert_eq!(ok(home, &["help"]), USAGE);
    assert_eq!(ok(home, &["help", "create"]), CREATE_HELP);
    assert!(!seat.exists(), "help created the seat store");

    let url = store_url(home);
    create_quote(home, &url, "deed-quote-log", &["--excerpt", "x"]);
    let out = deedar(home, &["--url", &url, "log", "nosuch"]);
    assert_eq!(out.status.code(), Some(1));
    assert_eq!(
        String::from_utf8(out.stderr).expect("stderr is utf8"),
        "deedar: unknown log command nosuch; log takes head, list, audit, backfill, prove ID, or bridge SIZE\n"
    );
    let out = deedar(home, &["--url", &url, "vouch", "nosuch"]);
    assert_eq!(out.status.code(), Some(1));
    assert_eq!(
        String::from_utf8(out.stderr).expect("stderr is utf8"),
        "deedar: unknown vouch command nosuch; vouch takes sign FILE or check FILE\n"
    );
}

/// No verb is the usage page, and it does not create a store on the way there.
#[test]
fn no_verb_prints_usage_and_does_not_make_a_store() {
    let home = tempfile::tempdir().unwrap();
    let home = home.path();
    let seat = home.join(".local/share/deedar/store");
    let out = deedar(home, &[]);
    assert_eq!(out.status.code(), Some(1));
    assert_eq!(String::from_utf8_lossy(&out.stdout).as_ref(), "");
    let err = String::from_utf8(out.stderr).expect("stderr is utf8");
    assert!(err.starts_with("deedar: usage: deedar"), "{err}");
    assert!(
        err.contains("leave takes an id and a destination directory"),
        "{err}"
    );
    assert!(
        err.contains("url prints the store this command resolved"),
        "{err}"
    );
    assert!(!seat.exists(), "usage created the seat store");

    let named = home.join("named-store");
    let url = format!("file://{}", named.display());
    let out = deedar(home, &["--url", &url]);
    assert_eq!(out.status.code(), Some(1));
    assert!(!named.exists(), "usage created the named store");
}

#[test]
fn usage_names_the_list_filters() {
    let home = tempfile::tempdir().unwrap();
    let page = ok(home.path(), &["--help"]);
    line(&page, "list takes --kind KIND, --agent ID and --text WORDS");
}

#[test]
fn help_and_version_print_the_same_pages() {
    let home = tempfile::tempdir().unwrap();
    let home = home.path();
    assert_eq!(ok(home, &["--help"]), USAGE);
    assert_eq!(ok(home, &["-h"]), USAGE);
    assert_eq!(ok(home, &["create", "--help"]), CREATE_HELP);
    assert_eq!(ok(home, &["create", "file", "--help"]), CREATE_HELP);
    let nowhere = home.join("no-such-store");
    let url = format!("file://{}", nowhere.display());
    assert_eq!(ok(home, &["--url", &url, "create", "--help"]), CREATE_HELP);
    let version = format!("deedar {}\n", env!("CARGO_PKG_VERSION"));
    assert_eq!(ok(home, &["-V"]), version);
    assert_eq!(ok(home, &["--version"]), version);
}

const VERBS: [&str; 16] = [
    "create",
    "get",
    "list",
    "trail",
    "evidence",
    "delete",
    "leave",
    "timestamp",
    "current",
    "log",
    "export",
    "import",
    "check",
    "vouch",
    "migrate",
    "host",
];

/// Every verb has its own page, `--help` and `help VERB` print the same one,
/// and neither opens a store.
#[test]
fn each_verb_prints_its_own_help() {
    let home = tempfile::tempdir().unwrap();
    let home = home.path();
    let seat = home.join(".local/share/deedar/store");
    let mut pages = Vec::new();
    for verb in VERBS.into_iter().chain(["url"]) {
        let page = ok(home, &[verb, "--help"]);
        assert_ne!(page, USAGE, "{verb} --help is the top-level page");
        assert!(
            page.starts_with(&format!("deedar {verb}")),
            "{verb} --help does not start with its own line:\n{page}"
        );
        assert_eq!(ok(home, &["help", verb]), page, "help {verb}");
        assert_eq!(ok(home, &[verb, "-h"]), page, "{verb} -h");
        assert!(!pages.contains(&page), "{verb} repeats another page");
        pages.push(page);
    }
    assert!(!seat.exists(), "a help page created the seat store");
}

#[test]
fn verb_pages_name_what_the_verb_takes() {
    let home = tempfile::tempdir().unwrap();
    let home = home.path();
    line(
        &ok(home, &["list", "--help"]),
        "deedar list [--kind KIND] [--agent ID] [--text WORDS]",
    );
    line(
        &ok(home, &["export", "--help"]),
        "deedar export --into DIR ID...",
    );
    line(
        &ok(home, &["import", "--help"]),
        "deedar import DIR [--allow-unsigned-head]",
    );
    line(
        &ok(home, &["check", "--help"]),
        "deedar check DIR [--since KEPT_HEAD] [--bridge FILE] [--keep FILE]",
    );
    line(&ok(home, &["leave", "--help"]), "deedar leave ID DIR");
    let log = ok(home, &["log", "--help"]);
    for word in [
        "head",
        "list",
        "audit",
        "backfill",
        "prove ID",
        "bridge SIZE",
    ] {
        assert!(log.contains(&format!("deedar log {word}")), "{log}");
    }
}

/// A bare `log` used to print the head and exit 0. No page or doc says it
/// does, and `head` is one of six commands, so it is a usage error: stderr,
/// exit 2, nothing on stdout, and no store made for it.
#[test]
fn a_bare_log_prints_the_log_usage_and_exits_2() {
    let home = tempfile::tempdir().unwrap();
    let home = home.path();
    let url = store_url(home);
    create_quote(home, &url, "deed-quote-bare-log", &["--excerpt", "x"]);
    let head = ok(home, &["--url", &url, "log", "head"]);
    assert!(head.starts_with("size=1 root="), "{head}");

    let usage = "deedar: log needs a command; \
        log takes head, list, audit, backfill, prove ID, or bridge SIZE; `deedar log --help`\n";
    for args in [
        vec!["--url", url.as_str(), "log"],
        vec!["log", "--url", url.as_str()],
    ] {
        let out = deedar(home, &args);
        assert_eq!(out.status.code(), Some(2), "{args:?}");
        assert_eq!(String::from_utf8_lossy(&out.stdout).as_ref(), "");
        assert_eq!(String::from_utf8_lossy(&out.stderr).as_ref(), usage);
    }

    let elsewhere = format!("file://{}", home.join("not-made").display());
    let out = deedar(home, &["--url", &elsewhere, "log"]);
    assert_eq!(out.status.code(), Some(2));
    assert!(!home.join("not-made").exists(), "log made a store");
}

#[test]
fn list_url_after_the_verb_selects_that_store() {
    let home = tempfile::tempdir().unwrap();
    let home = home.path();
    let url = store_url(home);
    let other = format!("file://{}", home.join("other").display());
    create_quote(
        home,
        &url,
        "deed-quote-listed",
        &["--excerpt", "kept in this store"],
    );
    let listed = ok(home, &["list", "--url", &url]);
    assert!(listed.contains("deed-quote-listed"), "{listed}");
    line(&listed, "excerpt=kept in this store");
    let out = deedar(home, &["list", "--url", &other]);
    assert!(out.status.success());
    assert_eq!(String::from_utf8_lossy(&out.stdout).as_ref(), "");
}

fn no_store_note(path: &Path) -> String {
    format!(
        "deedar: no store at {} yet; `deedar create --help` shows how to make the first deed, \
         and create makes the store\n",
        path.display()
    )
}

/// `list` at a path with no store used to make the store and print nothing.
/// It leaves the path alone, prints the note on stderr, and exits 0 with an
/// empty list. The first `create` makes the store, and then `list` is quiet.
#[test]
fn list_at_a_new_path_says_there_is_no_store_and_makes_none() {
    let home = tempfile::tempdir().unwrap();
    let home = home.path();
    let at = home.join("fresh");
    let url = format!("file://{}", at.display());
    for args in [
        vec!["--url", url.as_str(), "list"],
        vec!["list", "--url", url.as_str()],
    ] {
        let out = deedar(home, &args);
        assert_eq!(out.status.code(), Some(0), "{args:?}");
        assert_eq!(String::from_utf8_lossy(&out.stdout).as_ref(), "");
        assert_eq!(
            String::from_utf8_lossy(&out.stderr).as_ref(),
            no_store_note(&at)
        );
        assert!(!at.exists(), "{args:?} made the store");
    }

    let mut envs = Command::new(env!("CARGO_BIN_EXE_deedar"));
    let out = envs
        .args(["list"])
        .env("HOME", home)
        .env("XDG_DATA_HOME", home.join(".local/share"))
        .env("DEEDAR_HOST_SIGNING_KEY", "off")
        .env("DEEDAR_URL", &url)
        .output()
        .unwrap();
    assert_eq!(out.status.code(), Some(0));
    assert_eq!(
        String::from_utf8_lossy(&out.stderr).as_ref(),
        no_store_note(&at)
    );
    assert!(!at.exists(), "DEEDAR_URL made the store");

    create_quote(home, &url, "deed-quote-first", &["--excerpt", "x"]);
    assert!(at.is_dir(), "create did not make the store");
    let listed = deedar(home, &["--url", &url, "list"]);
    assert!(listed.status.success());
    assert!(String::from_utf8_lossy(&listed.stdout).contains("deed-quote-first"));
    assert_eq!(String::from_utf8_lossy(&listed.stderr).as_ref(), "");
}

/// A read that needs a deed refuses with the same line, exit 1, and no store.
/// `url` only prints, so it needs none; `check` and `vouch` never open one.
#[test]
fn the_other_reads_refuse_a_missing_store_and_make_none() {
    let home = tempfile::tempdir().unwrap();
    let home = home.path();
    let at = home.join("fresh");
    let url = format!("file://{}", at.display());
    let cases: [&[&str]; 9] = [
        &["get", "deed-quote-x"],
        &["trail", "deed-quote-x"],
        &["evidence", "deed-quote-x"],
        &["evidence", "deed-quote-x", "deed-quote-y"],
        &["current", "deed-quote-x", "deed-quote-y"],
        &["log", "head"],
        &["log", "audit"],
        &["host"],
        &["migrate"],
    ];
    for case in cases {
        let mut args = vec!["--url", url.as_str()];
        args.extend_from_slice(case);
        let out = deedar(home, &args);
        assert_eq!(out.status.code(), Some(1), "{case:?}");
        assert_eq!(String::from_utf8_lossy(&out.stdout).as_ref(), "");
        assert_eq!(
            String::from_utf8_lossy(&out.stderr).as_ref(),
            no_store_note(&at),
            "{case:?}"
        );
        assert!(!at.exists(), "{case:?} made the store");
    }
    assert_eq!(ok(home, &["--url", &url, "url"]), format!("{url}\n"));
    assert!(!at.exists(), "url made the store");
}

/// The writes still make the store: `create`, `import` and `host accept`.
#[test]
fn host_accept_still_makes_a_store() {
    let home = tempfile::tempdir().unwrap();
    let home = home.path();
    let at = home.join("fresh");
    let url = format!("file://{}", at.display());
    let out = deedar(home, &["--url", &url, "host", "accept"]);
    assert!(
        at.is_dir(),
        "host accept made no store: {}",
        String::from_utf8_lossy(&out.stderr)
    );
}

/// `create --help` used to spell the kind `maildraft`, which `create` refuses.
#[test]
fn create_help_spells_mail_draft_and_an_unknown_kind_lists_the_tokens() {
    let home = tempfile::tempdir().unwrap();
    let home = home.path();
    let page = ok(home, &["create", "--help"]);
    assert!(page.contains("mailDraft"), "{page}");
    assert!(!page.contains("maildraft"), "{page}");
    let url = store_url(home);
    let out = deedar(
        home,
        &["--url", &url, "create", "maildraft", "--agent", "you"],
    );
    assert_eq!(out.status.code(), Some(1));
    assert_eq!(String::from_utf8_lossy(&out.stdout).as_ref(), "");
    let err = String::from_utf8(out.stderr).expect("stderr is utf8");
    assert!(err.contains("invalid kind: maildraft"), "{err}");
    assert!(err.contains("mailDraft"), "{err}");
    assert!(err.contains("`deedar create --help`"), "{err}");
    let listed = deedar(home, &["--url", &url, "list", "--kind", "File"]);
    assert_eq!(listed.status.code(), Some(1));
    let err = String::from_utf8(listed.stderr).expect("stderr is utf8");
    assert!(err.contains("invalid kind: File"), "{err}");
    assert!(err.contains("mailDraft"), "{err}");
}

/// The reference lists `--title` for an event. That text is the deed name
/// when `--name` was omitted.
#[test]
fn an_event_title_is_the_deed_name() {
    let home = tempfile::tempdir().unwrap();
    let home = home.path();
    let url = store_url(home);
    let made = ok(
        home,
        &[
            "--url", &url, "create", "event", "--title", "launch", "--when", "now", "--where",
            "here", "--who", "me", "--agent", "you",
        ],
    );
    assert!(made.contains("name=launch"), "{made}");
    line(&made, "accession=deed-event-launch");
    let named = ok(
        home,
        &[
            "--url", &url, "create", "event", "--name", "kept", "--title", "ignored", "--when",
            "now", "--where", "here", "--who", "me", "--agent", "you",
        ],
    );
    assert!(named.contains("name=kept"), "{named}");
}