tsk-bin 0.26.2

tsk — work with a clear context
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
pub mod background;
pub mod doc_hook;
pub mod docs;
pub mod dolt;
pub mod fetch;
pub mod git;
pub mod location;
pub mod manifest;
pub mod migrate_docs;
pub mod migrate_transport;
pub mod nexus;
pub mod push;
pub mod refs;
pub mod refs_cmd;
pub mod register;
pub mod status;
pub mod store;
pub mod tips;
pub mod transport;

use clap::Subcommand;
use std::io::{Read, Write};
use std::path::PathBuf;

use store::{LedgerStore, PushReport, RefreshOutcome};

#[derive(Subcommand)]
pub enum LedgerCommands {
    #[command(
        about = "Fetch the ledger branch and materialise it at the fixed worktree path, refreshing in place; prints the path"
    )]
    Fetch,
    #[command(about = "Print the ledger worktree path without fetching or writing anything")]
    Path,
    #[command(
        about = "Commit every change in the ledger worktree, rebase onto the latest ledger branch, and push it with a bounded compare and swap retry; prints the commit the branch holds"
    )]
    Push {
        #[arg(
            help = "Commit message for the worktree changes; with --background it defaults to \"Background publish\"",
            required_unless_present = "background"
        )]
        message: Option<String>,
        #[arg(
            long,
            help = "Publish in the background: exit 0 at once with no output when nothing is unpushed or a push already runs, else start a detached one-shot child that runs this push and writes background-push.result. A failure shows as a warning on the next tsk command"
        )]
        background: bool,
    },
    #[command(
        name = "background-push-run",
        hide = true,
        about = "The child of tsk ledger push --background. Not for direct use"
    )]
    BackgroundPushRun {
        #[arg(long, help = "The inherited descriptor that holds the push lock")]
        lock_fd: i32,
        message: String,
    },
    #[command(
        about = "Print two answers, Local (what is not pushed, with a line per changed table or file, and one line for a schema upgrade) and Origin (whether it is ahead or behind); --porcelain prints tab-separated facts instead; fetches the remote refs and changes nothing else"
    )]
    Status {
        #[arg(
            long,
            help = "Print one tab-separated fact per line, the stable form for scripts, instead of the Local and Origin summary"
        )]
        porcelain: bool,
        #[arg(
            long,
            help = "Do not ask origin anything: print the Local block from what was last fetched, and the Origin line as not checked. No network"
        )]
        local: bool,
    },
    #[command(
        about = "Drop every local change that is not pushed, in the data and the documents, and reset both to origin's state; without --yes it prints what it would drop and exits 1"
    )]
    Discard {
        #[arg(
            long,
            help = "Discard now. Without it nothing changes and the changes are printed"
        )]
        yes: bool,
        #[arg(
            long,
            help = "Print the changes as tab-separated lines, the stable form for scripts, instead of the Local summary"
        )]
        porcelain: bool,
    },
    #[command(
        name = "migrate-docs",
        about = "Move the documents of a version 1 Dolt ledger from the documents table to the tsk/docs branch; prints migrated-docs:<count>"
    )]
    MigrateDocs {
        #[arg(
            long,
            help = "Do everything except the drop and the pushes: write and check the files, print the counts and dry-run:ok"
        )]
        dry_run: bool,
    },
    #[command(
        name = "migrate-transport",
        about = "Convert a ledger whose ref holds Dolt's blobstore to a Dolt file remote carried by plain git; prints migrated-transport:file-remote and the commit the ref now holds"
    )]
    MigrateTransport,
    #[command(
        about = "Read, write, list and remove ledger documents in the local store; none of them fetches or pushes"
    )]
    Doc {
        #[command(subcommand)]
        action: DocCommands,
    },
    #[command(
        about = "Inspect and control the local Dolt server of this clone's ledger store (the switch TSK_DOLT_SERVER or [ledger] server turns its use on; see ADR 0018)"
    )]
    Server {
        #[command(subcommand)]
        action: store::server::ServerCommands,
    },
}

#[derive(Subcommand)]
pub enum DocCommands {
    #[command(
        about = "Print the absolute path of a document's file, for opening it in another tool; exit status 1 when it does not exist"
    )]
    Path {
        #[arg(help = "Document path relative to the ledger root")]
        path: String,
    },
    #[command(
        about = "Print a document exactly as stored, with no added newline; exit status 1 when it does not exist"
    )]
    Get {
        #[arg(help = "Document path relative to the ledger root, for example index.md")]
        path: String,
    },
    #[command(
        about = "Write a document in the local store from a file or stdin; does not push; prints nothing"
    )]
    Put {
        #[arg(help = "Document path relative to the ledger root")]
        path: String,
        #[arg(help = "File holding the body; reads stdin when omitted")]
        file: Option<PathBuf>,
    },
    #[command(about = "List document paths that start with a prefix, one per line, sorted")]
    List {
        #[arg(help = "Path prefix, for example missions/; lists every document when omitted")]
        prefix: Option<String>,
    },
    #[command(
        about = "Remove a document from the local store; exit status 1 when it does not exist"
    )]
    Rm {
        #[arg(help = "Document path relative to the ledger root")]
        path: String,
    },
}

pub fn run(action: LedgerCommands) -> Result<(), String> {
    crate::config::refuse_files_backend_from_env()?;
    let cwd = std::env::current_dir()
        .map_err(|e| format!("error: could not read the current directory: {}", e))?;
    if let LedgerCommands::MigrateDocs { dry_run } = action {
        return migrate_docs::run(&cwd, dry_run);
    }
    if let LedgerCommands::MigrateTransport = action {
        return migrate_transport::run(&cwd);
    }
    if let LedgerCommands::Server { action } = action {
        return store::server::run_command(action, &cwd);
    }
    if let LedgerCommands::BackgroundPushRun { lock_fd, message } = action {
        return background::run_child(&cwd, lock_fd, &message);
    }
    if matches!(action, LedgerCommands::Push { .. }) {
        // A push reports its own outcome; an earlier failure is not news to it.
        background::be_quiet();
    }
    let store = store::open(&cwd)?;
    match action {
        LedgerCommands::Fetch => {
            let outcome = report_refresh(store.refresh_for_fetch()?);
            println!("{}", outcome.path.display());
            Ok(())
        }
        LedgerCommands::Path => {
            println!("{}", store.path()?.display());
            Ok(())
        }
        LedgerCommands::Push {
            message,
            background: true,
        } => {
            let message = message.unwrap_or_else(|| background::DEFAULT_MESSAGE.to_string());
            background::start(store.as_ref(), &message)?;
            Ok(())
        }
        LedgerCommands::Push {
            message,
            background: false,
        } => {
            let message = message.unwrap_or_default();
            // A push does not ask origin first. The record of the last fetch stands in for
            // what origin holds, and a push that finds origin moved is rejected and
            // retried after a fetch.
            store.trust_last_fetch();
            let report = push_reporting(store.as_ref(), &message)?;
            println!("{}", report.head);
            Ok(())
        }
        LedgerCommands::Status { porcelain, local } => {
            let status = if local {
                store.status_local()?
            } else {
                store.status()?
            };
            if let Some(note) = &status.fetch_note {
                eprintln!("{}", note);
            }
            let lines = if porcelain {
                status.lines()
            } else {
                status.human_lines()
            };
            for line in lines {
                println!("{}", line);
            }
            if !porcelain {
                if let Ok(path) = store.path() {
                    println!("{}", server_line(&path));
                    if let Some(line) = background::status_line(&path) {
                        println!("{}", line);
                    }
                }
            }
            Ok(())
        }
        LedgerCommands::Discard { yes, porcelain } => run_discard(store.as_ref(), yes, porcelain),
        LedgerCommands::Doc { action } => run_doc(store.as_ref(), action),
        LedgerCommands::MigrateDocs { .. }
        | LedgerCommands::MigrateTransport
        | LedgerCommands::BackgroundPushRun { .. }
        | LedgerCommands::Server { .. } => {
            unreachable!("handled before the store opens")
        }
    }
}

/// The `Server` line of `tsk ledger status`: whether the local Dolt server runs, and the
/// switch. Asks origin nothing.
fn server_line(db: &std::path::Path) -> String {
    let status = store::server::status(db);
    let text = match (status.state, &status.info) {
        ("running", Some(info)) => format!(
            "running (pid {}, idle stop {} s)",
            info.dolt.unwrap_or(info.supervisor),
            info.idle
        ),
        (state, _) => {
            let (on, _) = store::server::switch();
            format!("{} (switch {})", state, if on { "on" } else { "off" })
        }
    };
    format!("{:<8}{}", "Server", text)
}

/// `tsk ledger discard`. Without `yes` it prints the local changes and refuses.
fn run_discard(store: &dyn LedgerStore, yes: bool, porcelain: bool) -> Result<(), String> {
    if !yes {
        let status = store.status()?;
        if let Some(note) = &status.fetch_note {
            eprintln!("{}", note);
        }
        let lines = if porcelain {
            status.changes_lines()
        } else {
            status.human_local()
        };
        for line in lines {
            println!("{}", line);
        }
        if status.is_clean() {
            return Ok(());
        }
        return Err(
            "error: this would discard the local changes above. Rerun with --yes to discard them."
                .to_string(),
        );
    }
    store.discard()?;
    println!("discarded");
    Ok(())
}

fn no_such_document(path: &str) -> String {
    format!("error: no such document: {}", path)
}

fn run_doc(store: &dyn LedgerStore, action: DocCommands) -> Result<(), String> {
    match action {
        DocCommands::Path { path } => {
            let file = store
                .doc_path(&path)?
                .ok_or_else(|| no_such_document(&path))?;
            let file = std::fs::canonicalize(&file).unwrap_or(file);
            println!("{}", file.display());
            Ok(())
        }
        DocCommands::Get { path } => {
            let body = store
                .doc_get(&path)?
                .ok_or_else(|| no_such_document(&path))?;
            let mut out = std::io::stdout();
            out.write_all(body.as_bytes())
                .and_then(|()| out.flush())
                .map_err(|e| format!("error: could not write to stdout: {}", e))
        }
        DocCommands::Put { path, file } => {
            let body = match file {
                Some(file) => std::fs::read_to_string(&file)
                    .map_err(|e| format!("error: could not read {}: {}", file.display(), e))?,
                None => {
                    let mut text = String::new();
                    std::io::stdin()
                        .read_to_string(&mut text)
                        .map_err(|e| format!("error: could not read stdin: {}", e))?;
                    text
                }
            };
            store.doc_put(&path, &body)
        }
        DocCommands::List { prefix } => {
            for path in store.doc_list(prefix.as_deref().unwrap_or(""))? {
                println!("{}", path);
            }
            Ok(())
        }
        DocCommands::Rm { path } => {
            if store.doc_remove(&path)? {
                Ok(())
            } else {
                Err(no_such_document(&path))
            }
        }
    }
}

pub fn fetch_reporting(store: &dyn LedgerStore) -> Result<RefreshOutcome, String> {
    Ok(report_refresh(store.refresh()?))
}

/// [`fetch_reporting`] for the thread commands: local changes are kept, not refused.
pub fn fetch_keeping_local_reporting(store: &dyn LedgerStore) -> Result<RefreshOutcome, String> {
    Ok(report_refresh(store.refresh_keeping_local()?))
}

/// Print the notes of a refresh to stderr and hand the outcome back.
pub(crate) fn report_refresh(outcome: RefreshOutcome) -> RefreshOutcome {
    if let Some(note) = &outcome.pending_note {
        eprintln!("{}", note);
    }
    if let Some(note) = &outcome.unpublished_note {
        eprintln!("{}", note);
        if let Some(cloud) = refs::cloud_default_note() {
            eprintln!("{}", cloud);
        }
    }
    outcome
}

pub fn push_reporting(store: &dyn LedgerStore, message: &str) -> Result<PushReport, String> {
    let report = store.commit_and_push(message, &mut |note| eprintln!("{}", note))?;
    if let Ok(path) = store.path() {
        background::clear_failure(&path);
    }
    for line in &report.renumbered {
        println!("{}", line);
    }
    Ok(report)
}

pub(crate) fn retry_note(attempt: usize, status: &push::PushStatus) -> String {
    format!(
        "note: push rejected (attempt {}/{}): {}; fetching again and retrying",
        attempt,
        push::MAX_ATTEMPTS,
        status.summary
    )
}

pub(crate) fn push_notes(outcome: &push::PushOutcome) -> Vec<String> {
    let mut notes = Vec::new();
    if !outcome.committed {
        notes.push(format!(
            "note: nothing to commit in {}; checking whether an earlier run left a commit to push",
            outcome.path.display()
        ));
    }
    if outcome.result == push::PushResult::AlreadyOnRemote {
        notes.push(format!(
            "note: {}'s {} already holds this worktree's state; nothing to push",
            outcome.location.label(),
            outcome.location.ref_name()
        ));
    }
    notes
}

pub(crate) fn unpublished_note(outcome: &fetch::FetchOutcome) -> String {
    unpublished_text(
        outcome.location.label(),
        outcome.location.ref_name(),
        &outcome.path,
    )
}

pub(crate) fn unpublished_text(label: &str, ref_name: &str, path: &std::path::Path) -> String {
    let kind = if ref_name.starts_with("refs/heads/") {
        "branch"
    } else {
        "ref"
    };
    format!(
        "note: {}'s {} does not exist yet; {} holds a new ledger.\n      The first tsk ledger push creates the {}",
        label,
        ref_name,
        path.display(),
        kind
    )
}

pub(crate) fn pending_note(outcome: &fetch::FetchOutcome) -> String {
    let location = &outcome.location;
    let mut note = format!(
        "note: {} holds a commit that is not on {}'s {}:\n",
        outcome.path.display(),
        location.label(),
        location.ref_name()
    );
    for line in &outcome.pending {
        note.push_str(&format!("        {}\n", line));
    }
    note.push_str("      Leaving the worktree as it is rather than resetting over it.\n");
    note.push_str(
        "      Push it with tsk ledger push. To see what would be lost, run tsk ledger status.\n",
    );
    note.push_str("      To drop it deliberately, run tsk ledger discard.");
    note
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    #[test]
    fn pending_note_names_each_commit_and_the_reset_command() {
        let outcome = fetch::FetchOutcome {
            location: location::LedgerLocation::in_repo(),
            path: PathBuf::from("/s/tsk/repos/x/ledger"),
            pending: vec!["1111111 first".to_string(), "2222222 second".to_string()],
            unpublished: false,
        };
        let note = pending_note(&outcome);
        assert!(note.starts_with("note: /s/tsk/repos/x/ledger holds a commit"));
        assert!(note.contains("refs/heads/tsk/ledger"));
        assert!(note.contains("        1111111 first\n"));
        assert!(note.contains("        2222222 second\n"));
        assert!(note.contains("run tsk ledger status"));
        assert!(note.ends_with("To drop it deliberately, run tsk ledger discard."));
        assert!(!note.contains("reset --hard"));
    }

    #[test]
    fn unpublished_note_names_the_ref_and_the_first_push() {
        let outcome = fetch::FetchOutcome {
            location: location::LedgerLocation::nexus("https://example.test/o/nexus", "work-api"),
            path: PathBuf::from("/s/tsk/repos/x/ledger"),
            pending: Vec::new(),
            unpublished: true,
        };
        let note = unpublished_note(&outcome);
        assert!(note.contains("the nexus's refs/heads/ledgers/work-api does not exist yet"));
        assert!(note.contains("/s/tsk/repos/x/ledger holds a new ledger"));
        assert!(note.ends_with("The first tsk ledger push creates the branch"));
    }

    fn push_outcome(committed: bool, result: push::PushResult) -> push::PushOutcome {
        push::PushOutcome {
            location: location::LedgerLocation::in_repo(),
            path: PathBuf::from("/s/tsk/repos/x/ledger"),
            committed,
            commit: "abc123".to_string(),
            result,
        }
    }

    #[test]
    fn push_notes_are_empty_after_a_commit_and_push() {
        let outcome = push_outcome(true, push::PushResult::Pushed { attempts: 1 });
        assert!(push_notes(&outcome).is_empty());
    }

    #[test]
    fn push_notes_name_nothing_to_commit_and_already_on_remote() {
        let outcome = push_outcome(false, push::PushResult::AlreadyOnRemote);
        let notes = push_notes(&outcome);
        assert_eq!(notes.len(), 2);
        assert!(notes[0].contains("nothing to commit in /s/tsk/repos/x/ledger"));
        assert!(notes[1].contains("origin's refs/heads/tsk/ledger already holds"));
    }

    #[test]
    fn retry_note_names_the_attempt_and_the_summary() {
        let status = push::PushStatus {
            flag: '!',
            summary: "[rejected] (stale info)".to_string(),
        };
        assert_eq!(
            retry_note(2, &status),
            "note: push rejected (attempt 2/10): [rejected] (stale info); fetching again and retrying"
        );
    }
}