lazyspec 0.8.0

A little TUI & CLI for project documentation.
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
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
use clap::{CommandFactory, Parser};
use clap_complete::CompleteEnv;
use lazyspec::cli::provenance::ProvenanceCommand;
use lazyspec::cli::reservations::ReservationsCommand;
use lazyspec::cli::{Cli, Commands};
use lazyspec::engine::config::{Config, StoreBackend};
use lazyspec::engine::fs::RealFileSystem;
use lazyspec::engine::gh::GhCli;
use lazyspec::engine::git_ref::GitCli;
use lazyspec::engine::github::resolve_repo;
use lazyspec::engine::issue_cache::IssueCache;
use lazyspec::engine::issue_map::IssueMap;
use lazyspec::engine::store::Store;

fn main() -> anyhow::Result<()> {
    CompleteEnv::with_factory(Cli::command).complete();

    let cli = Cli::parse();
    let cwd = std::env::current_dir()?;

    if matches!(cli.command, Some(Commands::Init)) {
        lazyspec::cli::init::run(&cwd)?;
        return Ok(());
    }

    if let Some(Commands::Completions { shell }) = &cli.command {
        let bin = "lazyspec";
        let shell_name = match shell {
            clap_complete::Shell::Bash => "bash",
            clap_complete::Shell::Zsh => "zsh",
            clap_complete::Shell::Fish => "fish",
            clap_complete::Shell::Elvish => "elvish",
            clap_complete::Shell::PowerShell => "powershell",
            _ => {
                eprintln!("Unsupported shell for dynamic completions");
                std::process::exit(1);
            }
        };
        use clap_complete::env::EnvCompleter;
        let shells: &[&dyn EnvCompleter] = &[
            &clap_complete::env::Zsh,
            &clap_complete::env::Bash,
            &clap_complete::env::Fish,
        ];
        let env_shell = shells.iter().find(|s| s.is(shell_name));
        match env_shell {
            Some(s) => {
                s.write_registration("COMPLETE", "lazyspec", bin, bin, &mut std::io::stdout())?;
            }
            None => {
                // Fallback to static generation for shells without dynamic support
                clap_complete::generate(
                    *shell,
                    &mut Cli::command(),
                    "lazyspec",
                    &mut std::io::stdout(),
                );
            }
        }
        return Ok(());
    }

    let fs = RealFileSystem;
    let config = Config::load(&cwd, &fs)?;

    match cli.command {
        Some(Commands::Init) | Some(Commands::Completions { .. }) => unreachable!(),
        Some(Commands::Fetch { json, doc_type }) => {
            let gh = GhCli::new();
            let git_ref_ops = GitCli;
            lazyspec::cli::fetch::run(
                &cwd,
                &config,
                &gh,
                &git_ref_ops,
                "origin",
                doc_type.as_deref(),
                json,
            )?;
        }
        Some(Commands::Setup) => {
            let gh = GhCli::new();
            lazyspec::cli::setup::run(&cwd, &config, &gh)?;
        }
        Some(Commands::Create {
            doc_type,
            title,
            author,
            body,
            body_file,
            json,
        }) => {
            let body_content = lazyspec::cli::resolve_body(&body, &body_file)?;
            lazyspec::cli::lease::check_lease_gate(&cwd, &config, None)?;
            let store = Store::load(&cwd, &config)?;
            if json {
                let output = lazyspec::cli::create::run_json_with_body(
                    &cwd,
                    &config,
                    &store,
                    &doc_type,
                    &title,
                    &author,
                    body_content.as_deref(),
                    |_| {},
                )?;
                println!("{}", output);
            } else {
                let path = lazyspec::cli::create::run_with_body(
                    &cwd,
                    &config,
                    &store,
                    &doc_type,
                    &title,
                    &author,
                    body_content.as_deref(),
                    |_| {},
                )?;
                println!("{}", path.display());
            }
        }
        Some(Commands::List {
            doc_type,
            status,
            json,
        }) => {
            let store = Store::load(&cwd, &config)?;
            lazyspec::cli::list::run(&store, doc_type.as_deref(), status.as_deref(), json);
        }
        Some(Commands::Show {
            id,
            json,
            expand_references,
            max_ref_lines,
        }) => {
            refresh_github_cache(&cwd, &config);
            let store = Store::load(&cwd, &config)?;
            if json {
                let output = lazyspec::cli::show::run_json(
                    &store,
                    &id,
                    expand_references,
                    max_ref_lines,
                    &fs,
                )?;
                println!("{}", output);
            } else {
                lazyspec::cli::show::run(&store, &id, expand_references, max_ref_lines, &fs)?;
            }
        }
        Some(Commands::Update {
            path,
            status,
            title,
            body,
            body_file,
            json,
        }) => {
            lazyspec::cli::lease::check_lease_gate(&cwd, &config, Some(&path))?;
            let body_content = lazyspec::cli::resolve_body(&body, &body_file)?;
            let store = Store::load(&cwd, &config)?;
            let mut updates = Vec::new();
            if let Some(ref s) = status {
                updates.push(("status", s.as_str()));
            }
            if let Some(ref t) = title {
                updates.push(("title", t.as_str()));
            }
            if let Some(ref b) = body_content {
                updates.push(("body", b.as_str()));
            }
            let resolved = lazyspec::cli::resolve::resolve_to_path(&store, &path)?;
            lazyspec::cli::update::run_with_config(&cwd, &store, &path, &updates, Some(&config))?;
            if json {
                let store = Store::load(&cwd, &config)?;
                let doc = lazyspec::cli::resolve::resolve_shorthand_or_path(&store, &path)?;
                let json_val = lazyspec::cli::json::doc_to_json(doc);
                println!("{}", serde_json::to_string_pretty(&json_val)?);
            } else {
                println!("Updated {}", resolved.display());
            }
        }
        Some(Commands::Delete { path }) => {
            lazyspec::cli::lease::check_lease_gate(&cwd, &config, Some(&path))?;
            let store = Store::load(&cwd, &config)?;
            let resolved = lazyspec::cli::resolve::resolve_to_path(&store, &path)?;
            lazyspec::cli::delete::run_with_config(&cwd, &store, &path, Some(&config))?;
            println!("Deleted {}", resolved.display());
        }
        Some(Commands::Link { from, rel_type, to }) => {
            let store = Store::load(&cwd, &config)?;
            lazyspec::cli::link::link_with_config(
                &cwd,
                &store,
                &from,
                &rel_type,
                &to,
                &fs,
                Some(&config),
            )?;
            let resolved_from = lazyspec::cli::resolve::resolve_to_path(&store, &from)?;
            let resolved_to = lazyspec::cli::resolve::resolve_to_path(&store, &to)?;
            println!(
                "Linked {} --{}--> {}",
                resolved_from.display(),
                rel_type,
                resolved_to.display()
            );
        }
        Some(Commands::Unlink { from, rel_type, to }) => {
            let store = Store::load(&cwd, &config)?;
            lazyspec::cli::link::unlink_with_config(
                &cwd,
                &store,
                &from,
                &rel_type,
                &to,
                &fs,
                Some(&config),
            )?;
            let resolved_from = lazyspec::cli::resolve::resolve_to_path(&store, &from)?;
            let resolved_to = lazyspec::cli::resolve::resolve_to_path(&store, &to)?;
            println!(
                "Unlinked {} --{}--> {}",
                resolved_from.display(),
                rel_type,
                resolved_to.display()
            );
        }
        Some(Commands::Ignore { path }) => {
            let store = Store::load(&cwd, &config)?;
            let resolved = lazyspec::cli::resolve::resolve_to_path(&store, &path)?;
            lazyspec::cli::ignore::ignore(&cwd, &store, &path, &fs)?;
            println!("Ignoring {}", resolved.display());
        }
        Some(Commands::Unignore { path }) => {
            let store = Store::load(&cwd, &config)?;
            let resolved = lazyspec::cli::resolve::resolve_to_path(&store, &path)?;
            lazyspec::cli::ignore::unignore(&cwd, &store, &path, &fs)?;
            println!("Unignoring {}", resolved.display());
        }
        Some(Commands::Search {
            query,
            doc_type,
            json,
        }) => {
            let store = Store::load(&cwd, &config)?;
            lazyspec::cli::search::run(&store, &query, doc_type.as_deref(), json, &fs);
        }
        Some(Commands::Status { json }) => {
            let store = Store::load(&cwd, &config)?;
            if json {
                println!("{}", lazyspec::cli::status::run_json(&store, &config));
            } else {
                let output = lazyspec::cli::status::run_human(&store);
                if output.is_empty() {
                    println!("No documents found.");
                } else {
                    print!("{}", output);
                }
            }
        }
        Some(Commands::Context { id, json }) => {
            refresh_github_cache(&cwd, &config);
            let store = Store::load(&cwd, &config)?;
            if json {
                let output = lazyspec::cli::context::run_json(&store, &id)?;
                println!("{}", output);
            } else {
                let output = lazyspec::cli::context::run_human(&store, &id)?;
                print!("{}", output);
            }
        }
        Some(Commands::Convention {
            preamble,
            tags,
            json,
        }) => {
            let store = Store::load(&cwd, &config)?;
            if json {
                let output = lazyspec::cli::convention::run_json(
                    &store,
                    &config,
                    preamble,
                    tags.as_deref(),
                    &fs,
                )?;
                println!("{}", output);
            } else {
                let output = lazyspec::cli::convention::run_human(
                    &store,
                    &config,
                    preamble,
                    tags.as_deref(),
                    &fs,
                )?;
                print!("{}", output);
            }
        }
        Some(Commands::Fix {
            paths,
            dry_run,
            json,
            renumber,
            doc_type,
        }) => {
            let store = Store::load(&cwd, &config)?;
            let fs = lazyspec::engine::fs::RealFileSystem;
            if let Some(format) = renumber {
                let exit_code = lazyspec::cli::fix::run_renumber(
                    &cwd,
                    &store,
                    &config,
                    &format,
                    doc_type.as_deref(),
                    dry_run,
                    json,
                    &fs,
                );
                if exit_code != 0 {
                    std::process::exit(exit_code);
                }
            } else {
                let exit_code =
                    lazyspec::cli::fix::run(&cwd, &store, &config, &paths, dry_run, json, &fs);
                if exit_code != 0 {
                    std::process::exit(exit_code);
                }
            }
        }
        Some(Commands::Validate { json, warnings }) => {
            let store = Store::load(&cwd, &config)?;
            let exit_code = lazyspec::cli::validate::run_full(&store, &config, json, warnings);
            if exit_code != 0 {
                std::process::exit(exit_code);
            }
        }
        Some(Commands::Pin { id, json }) => {
            let store = Store::load(&cwd, &config)?;
            lazyspec::cli::pin::run(&store, &config, &id, json)?;
        }
        Some(Commands::Reservations { command }) => match command {
            ReservationsCommand::List { json } => {
                lazyspec::cli::reservations::run_list(&cwd, &config, json)?;
            }
            ReservationsCommand::Prune { dry_run, json } => {
                let store = Store::load(&cwd, &config)?;
                lazyspec::cli::reservations::run_prune(
                    &cwd,
                    &config,
                    &store,
                    dry_run,
                    json,
                    |_| {},
                )?;
            }
        },
        Some(Commands::Provenance { command }) => {
            let store = Store::load(&cwd, &config)?;
            let mut stdout = std::io::stdout();
            match command {
                ProvenanceCommand::Add { id, citation, json } => {
                    lazyspec::cli::provenance::run_add(
                        &cwd,
                        &store,
                        &config,
                        &id,
                        &citation,
                        json,
                        &mut stdout,
                    )?;
                }
                ProvenanceCommand::Remove { id, citation, json } => {
                    lazyspec::cli::provenance::run_remove(
                        &cwd,
                        &store,
                        &config,
                        &id,
                        &citation,
                        json,
                        &mut stdout,
                    )?;
                }
                ProvenanceCommand::List { id, json } => {
                    lazyspec::cli::provenance::run_list(&store, id.as_deref(), json, &mut stdout)?;
                }
            }
        }
        Some(Commands::Claim {
            doc_id,
            agent_id,
            force,
            json,
        }) => {
            if let Err(e) = lazyspec::cli::lease::run_claim(
                &cwd,
                &config,
                &doc_id,
                agent_id.as_deref(),
                force,
                json,
            ) {
                if json {
                    println!("{}", serde_json::json!({"error": e.to_string()}));
                    std::process::exit(1);
                } else {
                    return Err(e);
                }
            }
        }
        Some(Commands::Release {
            doc_id,
            agent_id,
            expected_holder,
            json,
        }) => {
            if let Err(e) = lazyspec::cli::lease::run_release(
                &cwd,
                &config,
                &doc_id,
                agent_id.as_deref(),
                expected_holder.as_deref(),
                json,
            ) {
                if json {
                    println!("{}", serde_json::json!({"error": e.to_string()}));
                    std::process::exit(1);
                } else {
                    return Err(e);
                }
            }
        }
        Some(Commands::Leases { json }) => {
            if let Err(e) = lazyspec::cli::lease::run_leases(&cwd, &config, json) {
                if json {
                    println!("{}", serde_json::json!({"error": e.to_string()}));
                    std::process::exit(1);
                } else {
                    return Err(e);
                }
            }
        }
        Some(Commands::Heartbeat {
            doc_id,
            agent_id,
            min_interval,
            json,
        }) => {
            if let Err(e) = lazyspec::cli::lease::run_heartbeat(
                &cwd,
                &config,
                &doc_id,
                agent_id.as_deref(),
                min_interval.as_deref(),
                json,
            ) {
                if json {
                    println!("{}", serde_json::json!({"error": e.to_string()}));
                    std::process::exit(1);
                } else {
                    return Err(e);
                }
            }
        }
        None => {
            let store = Store::load(&cwd, &config)?;
            lazyspec::tui::run(store, &config)?;
        }
    }

    Ok(())
}

/// Refreshes stale github-issues cache entries. Failures are non-fatal and print warnings to stderr.
fn refresh_github_cache(cwd: &std::path::Path, config: &Config) {
    let gh_config = match config.documents.github.as_ref() {
        Some(gh) => gh,
        None => return,
    };

    let gh_types: Vec<_> = config
        .documents
        .types
        .iter()
        .filter(|t| t.store == StoreBackend::GithubIssues)
        .collect();

    if gh_types.is_empty() {
        return;
    }

    let repo = match resolve_repo(config, cwd) {
        Ok(r) => r,
        Err(e) => {
            eprintln!(
                "warning: could not resolve github repo, skipping refresh: {}",
                e
            );
            return;
        }
    };

    let gh = GhCli::new();
    let cache = IssueCache::new(cwd);
    let ttl = chrono::Duration::seconds(gh_config.cache_ttl as i64);

    let mut issue_map = match IssueMap::load(cwd) {
        Ok(m) => m,
        Err(e) => {
            eprintln!("warning: could not load issue map, skipping refresh: {}", e);
            return;
        }
    };

    let mut map_changed = false;
    for type_def in &gh_types {
        let all_type_names: Vec<String> = config
            .documents
            .types
            .iter()
            .map(|t| t.name.clone())
            .collect();
        let result = cache.refresh_stale(
            cwd,
            type_def,
            &gh,
            &repo,
            &mut issue_map,
            ttl,
            &all_type_names,
        );
        for warning in &result.warnings {
            eprintln!("warning: {}", warning.message);
        }
        if result.refreshed > 0 {
            map_changed = true;
        }
    }

    if map_changed {
        if let Err(e) = issue_map.save(cwd) {
            eprintln!("warning: could not save issue map after refresh: {}", e);
        }
    }
}