cmdlore 0.4.0

A command library that lives in your shell
Documentation
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
//! Sync between two machines, end to end, against a bare repository on disk
//! standing in for GitHub.
//!
//! Each machine is its own config and data directory. Automatic syncing is
//! off, so every sync in a test is one the test asked for and nothing happens
//! behind its back.

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

struct World {
    root: PathBuf,
    remote: PathBuf,
}

impl World {
    fn new(name: &str) -> Self {
        let root = std::env::temp_dir().join(format!("lore-sync-{}-{name}", std::process::id()));
        let _ = fs::remove_dir_all(&root);
        fs::create_dir_all(&root).expect("the world should be creatable");

        let remote = root.join("remote.git");
        let init = Command::new("git")
            .args(["init", "--quiet", "--bare", "--initial-branch=main"])
            .arg(&remote)
            .output()
            .expect("git should run");
        assert!(
            init.status.success(),
            "{}",
            String::from_utf8_lossy(&init.stderr)
        );

        fs::write(root.join("gitconfig"), "").unwrap();
        Self { root, remote }
    }

    fn machine(&self, name: &str) -> Machine<'_> {
        let dir = self.root.join(name);
        fs::create_dir_all(&dir).unwrap();
        Machine { world: self, dir }
    }

    fn url(&self) -> String {
        self.remote.display().to_string()
    }

    /// Who the repository's commits are by, newest first.
    fn authors(&self) -> Vec<String> {
        let output = Command::new("git")
            .arg("--git-dir")
            .arg(&self.remote)
            .args(["log", "--format=%an <%ae>", "main"])
            .output()
            .expect("git should run");
        assert!(output.status.success(), "nothing was pushed");
        String::from_utf8_lossy(&output.stdout)
            .lines()
            .map(str::to_string)
            .collect()
    }

    /// The library as the repository holds it.
    fn published(&self) -> String {
        let output = Command::new("git")
            .arg("--git-dir")
            .arg(&self.remote)
            .args(["show", "main:commands.yaml"])
            .output()
            .expect("git should run");
        assert!(output.status.success(), "nothing was pushed");
        String::from_utf8_lossy(&output.stdout).into_owned()
    }
}

impl Drop for World {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.root);
    }
}

struct Machine<'a> {
    world: &'a World,
    dir: PathBuf,
}

impl Machine<'_> {
    fn run(&self, arguments: &[&str]) -> Output {
        Command::new(env!("CARGO_BIN_EXE_lore"))
            .args(arguments)
            .env("LORE_CONFIG_DIR", &self.dir)
            .env("LORE_DATA_DIR", &self.dir)
            .env("LORE_NO_AUTO_SYNC", "1")
            // Whoever runs the suite keeps their git settings to themselves.
            .env("GIT_CONFIG_GLOBAL", self.world.root.join("gitconfig"))
            .env("GIT_CONFIG_NOSYSTEM", "1")
            .stdin(std::process::Stdio::null())
            .output()
            .expect("the binary should run")
    }

    fn ok(&self, arguments: &[&str]) -> String {
        let output = self.run(arguments);
        assert!(
            output.status.success(),
            "{arguments:?} failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        String::from_utf8_lossy(&output.stdout).into_owned()
    }

    fn save(&self, command: &str, desc: &str) {
        self.ok(&["save", command, "--desc", desc]);
    }

    fn library(&self) -> String {
        fs::read_to_string(self.dir.join("commands.yaml")).unwrap_or_default()
    }

    fn has(&self, id: &str) -> bool {
        self.library().contains(&format!("id: {id}\n"))
    }

    fn sync_dir(&self) -> PathBuf {
        self.dir.join("sync")
    }
}

/// Whether a failed command's message mentions `text`.
///
/// On Windows lore writes errors to the console device rather than stderr,
/// because a PowerShell key handler hands its child a stderr that goes
/// nowhere. A test has no console to read, so there only the failure itself
/// can be checked.
fn says(output: &Output, text: &str) -> bool {
    cfg!(windows) || String::from_utf8_lossy(&output.stderr).contains(text)
}

fn git(dir: &Path, arguments: &[&str]) {
    let output = Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(arguments)
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn the_first_machine_publishes_its_library() {
    let world = World::new("publish");
    let laptop = world.machine("laptop");
    laptop.save("echo one", "Say one");

    let said = laptop.ok(&["sync", "init", &world.url()]);

    assert!(said.contains("1 change from this one"), "said {said}");
    assert!(world.published().contains("cmd: echo one"));
    assert!(laptop.has("user.echo-one"), "the library itself was lost");
}

#[test]
fn a_second_machine_gets_the_library_and_adds_its_own() {
    let world = World::new("second");
    let laptop = world.machine("laptop");
    let server = world.machine("server");

    laptop.save("echo one", "Say one");
    laptop.ok(&["sync", "init", &world.url()]);

    server.save("echo two", "Say two");
    server.ok(&["sync", "init", &world.url()]);
    assert!(
        server.has("user.echo-one"),
        "the server never got the laptop's command"
    );
    assert!(
        server.has("user.echo-two"),
        "the server lost its own command"
    );

    laptop.ok(&["sync"]);
    assert!(
        laptop.has("user.echo-two"),
        "the laptop never got the server's command"
    );
}

/// Both machines add a command before either syncs, so both append to the end
/// of the same list. Git alone calls that a conflict.
#[test]
fn commands_saved_on_two_machines_at_once_are_both_kept() {
    let world = World::new("concurrent");
    let laptop = world.machine("laptop");
    let server = world.machine("server");
    laptop.ok(&["sync", "init", &world.url()]);
    server.ok(&["sync", "init", &world.url()]);

    laptop.save("echo laptop", "From the laptop");
    server.save("echo server", "From the server");

    laptop.ok(&["sync"]);
    server.ok(&["sync"]);
    laptop.ok(&["sync"]);

    for machine in [&laptop, &server] {
        assert!(machine.has("user.echo-laptop"), "{}", machine.library());
        assert!(machine.has("user.echo-server"), "{}", machine.library());
    }
}

#[test]
fn a_removal_reaches_the_other_machine() {
    let world = World::new("removal");
    let laptop = world.machine("laptop");
    let server = world.machine("server");

    laptop.save("echo one", "Say one");
    laptop.save("echo two", "Say two");
    laptop.ok(&["sync", "init", &world.url()]);
    server.ok(&["sync", "init", &world.url()]);

    laptop.ok(&["rm", "user.echo-one"]);
    laptop.ok(&["sync"]);
    server.ok(&["sync"]);

    assert!(!server.has("user.echo-one"), "{}", server.library());
    assert!(server.has("user.echo-two"));
}

#[test]
fn an_entry_edited_on_both_machines_is_kept_twice_and_settles() {
    let world = World::new("conflict");
    let laptop = world.machine("laptop");
    let server = world.machine("server");

    laptop.save("echo one", "Say one");
    laptop.ok(&["sync", "init", &world.url()]);
    server.ok(&["sync", "init", &world.url()]);

    laptop.ok(&["edit", "user.echo-one", "--desc", "Laptop wording"]);
    server.ok(&["edit", "user.echo-one", "--desc", "Server wording"]);

    laptop.ok(&["sync"]);
    let said = server.ok(&["sync"]);
    assert!(said.contains("user.echo-one-2"), "said {said}");

    laptop.ok(&["sync"]);
    let again = server.ok(&["sync"]);
    assert!(
        again.contains("Already up to date"),
        "never settled: {again}"
    );

    for machine in [&laptop, &server] {
        let library = machine.library();
        assert!(library.contains("Laptop wording"), "{library}");
        assert!(library.contains("Server wording"), "{library}");
        assert_eq!(library.matches("id: user.echo-one").count(), 2, "{library}");
    }
}

#[test]
fn syncing_before_setting_it_up_says_what_to_do() {
    let world = World::new("unset");
    let laptop = world.machine("laptop");

    let output = laptop.run(&["sync"]);
    assert!(!output.status.success());
    assert!(says(&output, "lore sync init"));

    let status = laptop.ok(&["sync", "status"]);
    assert!(status.contains("not set up"), "said {status}");
}

#[test]
fn switching_repositories_needs_a_disconnect_first() {
    let world = World::new("switch");
    let laptop = world.machine("laptop");
    laptop.ok(&["sync", "init", &world.url()]);

    let other = world.root.join("other.git");
    let output = laptop.run(&["sync", "init", &other.display().to_string()]);
    assert!(!output.status.success(), "switched without being asked to");
    assert!(says(&output, "disconnect"));

    laptop.save("echo kept", "Stays");
    laptop.ok(&["sync", "disconnect"]);
    assert!(!laptop.sync_dir().exists());
    assert!(
        laptop.has("user.echo-kept"),
        "disconnecting took the library with it"
    );
}

/// Nobody is watching a background sync, so it must not fail loudly or wait
/// for a password. It leaves the reason where status can report it.
#[test]
fn a_background_sync_that_fails_leaves_a_note() {
    let world = World::new("background");
    let laptop = world.machine("laptop");
    laptop.ok(&["sync", "init", &world.url()]);

    let gone = world.root.join("gone.git");
    git(
        &laptop.sync_dir(),
        &["remote", "set-url", "origin", &gone.display().to_string()],
    );

    let output = laptop.run(&["sync", "--background"]);
    assert!(output.status.success(), "a background sync exited non zero");

    let status = laptop.ok(&["sync", "status"]);
    assert!(status.contains("failed"), "said {status}");

    git(
        &laptop.sync_dir(),
        &["remote", "set-url", "origin", &world.url()],
    );
    laptop.ok(&["sync"]);
    let status = laptop.ok(&["sync", "status"]);
    assert!(
        !status.contains("failed"),
        "the note outlived a good sync: {status}"
    );
}

/// A repository someone created on GitHub with a README already has history,
/// but no library in it yet.
#[test]
fn a_repository_that_already_has_other_files_is_used_as_it_is() {
    let world = World::new("readme");
    let seed = world.root.join("seed");
    let clone = Command::new("git")
        .args(["clone", "--quiet"])
        .arg(&world.remote)
        .arg(&seed)
        .output()
        .unwrap();
    assert!(clone.status.success());
    fs::write(seed.join("README.md"), "my library\n").unwrap();
    git(&seed, &["add", "README.md"]);
    git(
        &seed,
        &[
            "-c",
            "user.name=t",
            "-c",
            "user.email=t@t",
            "commit",
            "--quiet",
            "-m",
            "readme",
        ],
    );
    git(
        &seed,
        &["push", "--quiet", "origin", "HEAD:refs/heads/main"],
    );

    let laptop = world.machine("laptop");
    laptop.save("echo one", "Say one");
    laptop.ok(&["sync", "init", &world.url()]);

    assert!(world.published().contains("cmd: echo one"));
}

/// A sync that could not push must not count as agreement. Otherwise the next
/// one sees the command saved here missing from the repository and takes that
/// for a removal made elsewhere.
#[test]
fn a_failed_push_loses_nothing_on_the_next_sync() {
    let world = World::new("offline");
    let laptop = world.machine("laptop");
    let server = world.machine("server");
    laptop.ok(&["sync", "init", &world.url()]);
    server.ok(&["sync", "init", &world.url()]);

    laptop.save("echo offline", "Saved while offline");
    let gone = world.root.join("gone.git");
    git(
        &laptop.sync_dir(),
        &["remote", "set-url", "origin", &gone.display().to_string()],
    );
    assert!(
        !laptop.run(&["sync"]).status.success(),
        "synced with no repository"
    );
    git(
        &laptop.sync_dir(),
        &["remote", "set-url", "origin", &world.url()],
    );

    server.save("echo meanwhile", "Saved elsewhere meanwhile");
    server.ok(&["sync"]);

    laptop.ok(&["sync"]);
    assert!(laptop.has("user.echo-offline"), "{}", laptop.library());
    assert!(laptop.has("user.echo-meanwhile"), "{}", laptop.library());
    assert!(world.published().contains("echo offline"));
}

/// One commit per saved command, on the default branch of a repository the
/// user owns, is exactly what GitHub counts as a contribution. Filing every
/// save as a day's work on someone's profile is not lore's to do.
#[test]
fn sync_commits_are_by_lore_unless_the_clone_is_given_an_identity() {
    let world = World::new("identity");
    let laptop = world.machine("laptop");
    laptop.save("echo one", "Say one");
    laptop.ok(&["sync", "init", &world.url()]);

    assert_eq!(world.authors(), ["lore <lore@invalid>"]);

    git(&laptop.sync_dir(), &["config", "user.name", "A Person"]);
    git(
        &laptop.sync_dir(),
        &["config", "user.email", "person@example.com"],
    );
    laptop.save("echo two", "Say two");
    laptop.ok(&["sync"]);

    assert_eq!(
        world.authors().first().map(String::as_str),
        Some("A Person <person@example.com>"),
        "an identity set on the clone was ignored"
    );
}