hyalo-cli 0.10.0

CLI for exploring and managing Markdown knowledge bases with YAML frontmatter
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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
use std::process;

use clap::{CommandFactory, FromArgMatches};

use crate::cli::args::{Cli, Commands, FindFilters};
use crate::cli::help::{filter_examples, filter_long_help};
use crate::commands::init as init_commands;
use crate::dispatch::{CommandContext, dispatch};
use crate::error::AppError;
use crate::hints::{CommonHintFlags, HintContext, HintSource};
use crate::output::{CommandOutcome, Format};
use crate::output_pipeline::{COUNT_UNSUPPORTED_ERROR, OutputPipeline};
use hyalo_core::index::SnapshotIndex;

/// Derive the task selector string for hint context.
fn task_selector(line: &[usize], section: Option<&String>, all: bool) -> Option<String> {
    if all {
        Some("all".to_owned())
    } else if let Some(s) = section {
        Some(format!("section:{s}"))
    } else if line.len() > 1 {
        Some("lines".to_owned())
    } else {
        None
    }
}

#[allow(clippy::too_many_lines)]
pub fn run() {
    match run_inner() {
        Ok(()) => {
            crate::warn::flush_summary();
        }
        Err(e) => {
            crate::warn::flush_summary();
            let code = match e {
                AppError::User(msg) => {
                    if !msg.is_empty() {
                        eprintln!("{msg}");
                    }
                    1
                }
                AppError::Internal(err) => {
                    let s = err.to_string();
                    if !s.is_empty() {
                        eprintln!("Error: {err}");
                    }
                    2
                }
                AppError::Clap(err) => {
                    let code = err.exit_code();
                    let _ = err.print();
                    code
                }
                AppError::Exit(code) => code,
            };
            process::exit(code);
        }
    }
}

#[allow(clippy::too_many_lines)]
fn run_inner() -> Result<(), AppError> {
    // Pre-scan for --quiet / -q so config-loading warnings are also suppressed.
    let early_quiet = std::env::args().any(|a| a == "--quiet" || a == "-q");
    crate::warn::init(early_quiet);

    // Load per-project config from .hyalo.toml in CWD before parsing args.
    // This lets us hide flags that already have config-provided defaults,
    // keeping `--help` output focused on what the user actually needs to set.
    let config = crate::config::load_config();

    // Build the clap Command and hide global flags that are already covered by
    // the project config.  `mut_arg` is scoped to the root command, but because
    // both `--dir` and `--format` are declared `global = true`, hiding them on
    // the root is sufficient for --help at every level.
    let hide_dir = config
        .dir
        .components()
        .ne(std::path::Path::new(".").components());
    let hide_format = config.format != "json";

    let mut cmd = Cli::command();
    if hide_dir {
        cmd = cmd.mut_arg("dir", |a| a.hide(true));
    }
    if hide_format {
        cmd = cmd.mut_arg("format", |a| a.hide(true));
    }

    // Apply runtime-filtered help text so that examples and cookbook entries
    // that reference config-defaulted flags are stripped from help output.
    // `after_help` is shown by `-h`; `after_long_help` is shown by `--help`.
    cmd = cmd
        .after_help(filter_examples(hide_dir, hide_format))
        .after_long_help(filter_long_help(hide_dir, hide_format));

    // Global args (--format, --jq, etc.) are only defined on the root Command
    // in clap derive — they aren't propagated to subcommands until parse time.
    // We can't use mut_subcommand to hide them from `init --help` because
    // they don't exist on the subcommand Command node yet.  This is a known
    // clap limitation with `global = true` derive args.
    let raw_args: Vec<String> = std::env::args().collect();
    let matches = match cmd.try_get_matches_from(raw_args.iter().map(String::as_str)) {
        Ok(m) => m,
        Err(e) => {
            // Intercept `--filter` before falling through to clap's built-in
            // suggestion, which picks `--file` (closest by Levenshtein distance).
            // Users almost always mean `--property` here.
            if e.kind() == clap::error::ErrorKind::UnknownArgument
                && crate::suggest::unknown_arg_is(&e, "--filter")
            {
                eprintln!(
                    "error: unexpected argument '--filter' found\n\n\
                     tip: did you mean '--property'?\n\n\
                     Example: hyalo find --property status=planned\n"
                );
                return Err(AppError::Exit(2));
            }

            // Only attempt subcommand suggestions when clap couldn't recognise a
            // flag or subcommand — this avoids misleading tips for other error kinds.
            if matches!(
                e.kind(),
                clap::error::ErrorKind::InvalidSubcommand | clap::error::ErrorKind::UnknownArgument
            ) && let Some(suggestion) =
                crate::suggest::suggest_subcommand_correction(&raw_args, &Cli::command())
            {
                eprintln!("{e}\n  tip: did you mean:\n\n    {suggestion}\n");
                return Err(AppError::Exit(2));
            }

            // Suggest --version / --help when the user types a close misspelling
            // as a bare subcommand (e.g. `hyalo versio`, `hyalo hep`).
            if e.kind() == clap::error::ErrorKind::InvalidSubcommand {
                use clap::error::{ContextKind, ContextValue};
                if let Some(invalid) = e.context().find_map(|(k, v)| {
                    if k == ContextKind::InvalidSubcommand {
                        if let ContextValue::String(s) = v {
                            Some(s.as_str())
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                }) {
                    for (target, suggestion) in [("version", "--version"), ("help", "--help")] {
                        if strsim::damerau_levenshtein(invalid, target) <= 2 {
                            eprintln!("{e}\n  tip: did you mean `hyalo {suggestion}`?\n");
                            return Err(AppError::Exit(2));
                        }
                    }
                }
            }

            return Err(AppError::Clap(e));
        }
    };
    let mut cli = match Cli::from_arg_matches(&matches) {
        Ok(c) => c,
        Err(e) => return Err(AppError::Clap(e)),
    };

    // Re-apply quiet flag from the fully-parsed CLI (the early pre-scan
    // covers the common case but this ensures correctness after full parsing).
    crate::warn::init(cli.quiet);

    // `init` operates on CWD directly and needs no config or format resolution.
    // Dispatch it before the rest of the setup.
    // The global --dir flag is used as the dir value for .hyalo.toml.
    // Reject --count early — init is not a list command.
    if cli.count
        && matches!(
            cli.command,
            Commands::Init { .. } | Commands::Deinit | Commands::Completion { .. }
        )
    {
        eprintln!("{COUNT_UNSUPPORTED_ERROR}");
        return Err(AppError::Exit(2));
    }
    if let Commands::Init { claude } = cli.command {
        let init_dir = cli.dir.as_deref().and_then(|p| p.to_str());
        match init_commands::run_init(init_dir, claude) {
            Ok(CommandOutcome::Success { output, .. } | CommandOutcome::RawOutput(output)) => {
                println!("{output}");
                return Ok(());
            }
            Ok(CommandOutcome::UserError(output)) => return Err(AppError::User(output)),
            Err(e) => return Err(AppError::Internal(e)),
        }
    }
    if let Commands::Deinit = cli.command {
        match init_commands::run_deinit() {
            Ok(CommandOutcome::Success { output, .. } | CommandOutcome::RawOutput(output)) => {
                println!("{output}");
                return Ok(());
            }
            Ok(CommandOutcome::UserError(output)) => return Err(AppError::User(output)),
            Err(e) => return Err(AppError::Internal(e)),
        }
    }
    if let Commands::Completion { shell } = cli.command {
        let mut cmd = Cli::command();
        clap_complete::generate(shell, &mut cmd, "hyalo", &mut std::io::stdout());
        return Ok(());
    }
    // Merge: CLI args override config, config overrides hardcoded defaults.
    // Track whether --dir was explicitly passed (not from config) so hints
    // can omit it when the user relies on .hyalo.toml.
    let dir_from_cli = cli.dir.is_some();
    let format_from_cli = cli.format.is_some();
    let hints_from_cli = cli.hints;
    let dir = cli.dir.unwrap_or(config.dir);

    // Validate that --dir exists and is a directory (symlinks to directories are fine).
    if !dir.exists() {
        return Err(AppError::User(format!(
            "Error: --dir path '{}' does not exist.",
            dir.display()
        )));
    }
    if dir.is_file() {
        return Err(AppError::User(format!(
            "Error: --dir path '{}' is a file, not a directory. Use --file to target a single file.",
            dir.display()
        )));
    }

    // Derive site_prefix with tri-state precedence:
    //
    //   1. CLI --site-prefix flag  (present → use it; empty string = explicit disable)
    //   2. `site_prefix` in .hyalo.toml  (same: empty string = explicit disable)
    //   3. Auto-derive from canonicalized dir's last path component
    //      (only runs when neither 1 nor 2 is present)
    //
    // Empty strings in (1) and (2) short-circuit the chain and result in
    // site_prefix = None, suppressing all absolute-link resolution.
    let site_prefix_owned: Option<String> = if cli.site_prefix.is_some() {
        // Explicit CLI flag wins — empty string intentionally disables prefix.
        cli.site_prefix.filter(|s| !s.is_empty())
    } else if config.site_prefix.is_some() {
        // Config file override — empty string intentionally disables prefix.
        config.site_prefix.filter(|s| !s.is_empty())
    } else {
        // Auto-derive from the last component of the resolved dir.
        match std::fs::canonicalize(&dir) {
            Ok(canonical) => canonical
                .file_name()
                .and_then(|n| n.to_str())
                .map(std::borrow::ToOwned::to_owned),
            Err(_) => {
                // canonicalize can still fail on valid directories (e.g. broken
                // symlink chains on some platforms). Fall back to the raw path
                // component rather than losing the prefix entirely.
                dir.file_name()
                    .and_then(|n| n.to_str())
                    .filter(|s| *s != ".")
                    .map(std::borrow::ToOwned::to_owned)
            }
        }
    };
    let site_prefix = site_prefix_owned.as_deref();
    // CLI --format is already validated by Clap; fall back to config (String) with runtime parse.
    let format = if let Some(f) = cli.format {
        f
    } else if let Some(fmt) = Format::from_str_opt(&config.format) {
        fmt
    } else {
        eprintln!(
            "Invalid output format '{}' in .hyalo.toml; supported formats are: json, text",
            config.format
        );
        return Err(AppError::Exit(2));
    };
    let hints_flag = if cli.hints {
        true
    } else if cli.no_hints {
        false
    } else {
        config.hints
    };

    // Resolve --view: load the named view from .hyalo.toml and merge CLI overrides.
    if let Commands::Find {
        view: Some(ref view_name),
        ref mut filters,
        ..
    } = cli.command
    {
        let views = crate::commands::views::load_views();
        match views.get(view_name) {
            Some(base) => {
                let overlay = std::mem::take(filters);
                *filters = base.clone();
                filters.merge_from(&overlay);
            }
            None => {
                return Err(AppError::User(format!(
                    "Error: unknown view '{view_name}'\n\n  tip: run 'hyalo views list' to see available views"
                )));
            }
        }
    }

    // --jq operates on JSON, so it conflicts with an explicit --format text.
    let jq_filter = cli.jq.as_deref();

    // `read` defaults to text output (unlike other commands which default to json).
    // Skip the override when --jq is active (jq needs JSON).
    let format = if !format_from_cli
        && jq_filter.is_none()
        && matches!(cli.command, Commands::Read { .. })
    {
        Format::Text
    } else {
        format
    };
    // --count replaces the entire output pipeline, so check its conflicts first.
    if cli.count && jq_filter.is_some() {
        eprintln!("Error: --count cannot be combined with --jq");
        eprintln!(
            "  --count prints the bare total; --jq applies a custom filter — use one or the other"
        );
        return Err(AppError::Exit(2));
    }
    if jq_filter.is_some() && format != Format::Json {
        eprintln!("Error: --jq cannot be combined with --format {format}");
        eprintln!("  --jq always operates on JSON output; drop --format or use --format json");
        return Err(AppError::Exit(2));
    }
    // Always force JSON internally so the output pipeline can wrap results in the
    // envelope.  The user-requested format is applied by the pipeline afterwards.
    let effective_format = Format::Json;

    // Build hint context before the command dispatch.
    // Only include CLI-explicit flags in hints — config values are inherited
    // automatically when the user runs the hint command from the same CWD.
    let hint_ctx = if hints_flag && jq_filter.is_none() {
        // Capture the three global flags that every HintContext arm needs.
        // Computed once here so each arm can call HintContext::from_common
        // instead of repeating the same three field assignments.
        let common = CommonHintFlags {
            dir: if dir_from_cli {
                dir.to_str()
                    .map(std::borrow::ToOwned::to_owned)
                    .filter(|s| s != ".")
            } else {
                None
            },
            format: if format_from_cli {
                Some(format.to_string())
            } else {
                None
            },
            hints: hints_from_cli,
        };

        match &cli.command {
            Commands::Summary { glob, .. } => {
                let mut ctx = HintContext::from_common(HintSource::Summary, &common);
                ctx.glob.clone_from(glob);
                Some(ctx)
            }
            Commands::Properties {
                action: Some(crate::cli::args::PropertiesAction::Summary { glob }),
            } => {
                let mut ctx = HintContext::from_common(HintSource::PropertiesSummary, &common);
                ctx.glob.clone_from(glob);
                Some(ctx)
            }
            Commands::Tags {
                action: Some(crate::cli::args::TagsAction::Summary { glob }),
            } => {
                let mut ctx = HintContext::from_common(HintSource::TagsSummary, &common);
                ctx.glob.clone_from(glob);
                Some(ctx)
            }
            Commands::Tags { action: None } => {
                // Bare `hyalo tags` defaults to summary with no glob.
                Some(HintContext::from_common(HintSource::TagsSummary, &common))
            }
            Commands::Find {
                pattern,
                file_positional,
                view,
                filters:
                    FindFilters {
                        glob,
                        regexp,
                        properties,
                        tag,
                        task,
                        file,
                        fields,
                        sort,
                        limit,
                        sections,
                        ..
                    },
            } => {
                // Merge positional files for hint context (view merging happens later)
                let file = if file_positional.is_empty() {
                    file
                } else {
                    file_positional
                };
                let mut ctx = HintContext::from_common(HintSource::Find, &common);
                ctx.glob.clone_from(glob);
                ctx.fields.clone_from(fields);
                ctx.sort.clone_from(sort);
                ctx.has_limit = limit.is_some();
                ctx.has_body_search = pattern.is_some();
                ctx.has_regex_search = regexp.is_some();
                ctx.property_filters.clone_from(properties);
                ctx.tag_filters.clone_from(tag);
                ctx.task_filter.clone_from(task);
                ctx.file_targets.clone_from(file);
                ctx.section_filters.clone_from(sections);
                ctx.view_name.clone_from(view);
                Some(ctx)
            }
            Commands::Set {
                file_positional,
                file,
                glob,
                dry_run,
                ..
            } => {
                let mut ctx = HintContext::from_common(HintSource::Set, &common);
                ctx.glob.clone_from(glob);
                let src = if file_positional.is_empty() {
                    file
                } else {
                    file_positional
                };
                ctx.file_targets.clone_from(src);
                ctx.dry_run = *dry_run;
                Some(ctx)
            }
            Commands::Remove {
                file_positional,
                file,
                glob,
                dry_run,
                ..
            } => {
                let mut ctx = HintContext::from_common(HintSource::Remove, &common);
                ctx.glob.clone_from(glob);
                let src = if file_positional.is_empty() {
                    file
                } else {
                    file_positional
                };
                ctx.file_targets.clone_from(src);
                ctx.dry_run = *dry_run;
                Some(ctx)
            }
            Commands::Append {
                file_positional,
                file,
                glob,
                dry_run,
                ..
            } => {
                let mut ctx = HintContext::from_common(HintSource::Append, &common);
                ctx.glob.clone_from(glob);
                let src = if file_positional.is_empty() {
                    file
                } else {
                    file_positional
                };
                ctx.file_targets.clone_from(src);
                ctx.dry_run = *dry_run;
                Some(ctx)
            }
            Commands::Read {
                file_positional,
                file,
                ..
            } => {
                let mut ctx = HintContext::from_common(HintSource::Read, &common);
                if let Some(f) = file_positional.as_ref().or(file.as_ref()) {
                    ctx.file_targets = vec![f.clone()];
                }
                Some(ctx)
            }
            Commands::Backlinks {
                file_positional,
                file,
            } => {
                let mut ctx = HintContext::from_common(HintSource::Backlinks, &common);
                if let Some(f) = file_positional.as_ref().or(file.as_ref()) {
                    ctx.file_targets = vec![f.clone()];
                }
                Some(ctx)
            }
            Commands::Mv {
                file_positional,
                file,
                dry_run,
                ..
            } => {
                let mut ctx = HintContext::from_common(HintSource::Mv, &common);
                if let Some(f) = file_positional.as_ref().or(file.as_ref()) {
                    ctx.file_targets = vec![f.clone()];
                }
                ctx.dry_run = *dry_run;
                Some(ctx)
            }
            Commands::Task { action } => {
                let (source, file_pos, file_flag, selector) = match action {
                    crate::cli::args::TaskAction::Toggle {
                        file_positional,
                        file,
                        line,
                        section,
                        all,
                    } => (
                        HintSource::TaskToggle,
                        file_positional,
                        file,
                        task_selector(line, section.as_ref(), *all),
                    ),
                    crate::cli::args::TaskAction::SetStatus {
                        file_positional,
                        file,
                        line,
                        section,
                        all,
                        ..
                    } => (
                        HintSource::TaskSetStatus,
                        file_positional,
                        file,
                        task_selector(line, section.as_ref(), *all),
                    ),
                    crate::cli::args::TaskAction::Read {
                        file_positional,
                        file,
                        line,
                        section,
                        all,
                    } => (
                        HintSource::TaskRead,
                        file_positional,
                        file,
                        task_selector(line, section.as_ref(), *all),
                    ),
                };
                let mut ctx = HintContext::from_common(source, &common);
                if let Some(f) = file_pos.as_ref().or(file_flag.as_ref()) {
                    ctx.file_targets = vec![f.clone()];
                }
                ctx.task_selector = selector;
                Some(ctx)
            }
            Commands::Links { action } => match action {
                crate::cli::args::LinksAction::Fix { apply, glob, .. } => {
                    let mut ctx = HintContext::from_common(HintSource::LinksFix, &common);
                    ctx.glob.clone_from(glob);
                    ctx.dry_run = !apply;
                    Some(ctx)
                }
            },
            Commands::CreateIndex { output, .. } => {
                let mut ctx = HintContext::from_common(HintSource::CreateIndex, &common);
                ctx.index_path = output.as_ref().map(|p| p.to_string_lossy().into_owned());
                Some(ctx)
            }
            Commands::DropIndex { .. } => {
                Some(HintContext::from_common(HintSource::DropIndex, &common))
            }
            Commands::Properties { .. }
            | Commands::Tags { .. }
            | Commands::Init { .. }
            | Commands::Deinit
            | Commands::Completion { .. }
            | Commands::Views { .. } => None,
        }
    } else {
        None
    };

    // Load snapshot index if --index is provided.
    // Read-only commands use it to skip disk scans. Mutation commands use it to
    // keep the index up-to-date after each file write (they still read/write
    // individual files on disk, but patch the index entry in-place).
    let uses_index = !matches!(
        &cli.command,
        Commands::Init { .. }
            | Commands::CreateIndex { .. }
            | Commands::DropIndex { .. }
            | Commands::Read { .. }
            | Commands::Views { .. }
    );
    let mut snapshot_index: Option<SnapshotIndex> = if uses_index {
        if let Some(ref index_path) = cli.index {
            match SnapshotIndex::load(index_path) {
                Ok(Some(idx)) => {
                    // Warn when the snapshot was built for a different vault or
                    // site-prefix — the index data may not match the current run.
                    let canonical_dir = std::fs::canonicalize(&dir).unwrap_or_else(|_| dir.clone());
                    let vault_dir_str = canonical_dir.to_string_lossy();
                    if idx.validate(&vault_dir_str, site_prefix) {
                        Some(idx)
                    } else {
                        let (hdr_vault, hdr_prefix, _, _) = idx.header_info();
                        crate::warn::warn(format!(
                            "index was built for vault '{hdr_vault}' (prefix {hdr_prefix:?}) but current \
                             vault is '{vault_dir_str}' (prefix {site_prefix:?}); falling back to disk scan",
                        ));
                        None
                    }
                }
                Ok(None) => None, // incompatible schema — already warned; fall back to disk scan
                Err(e) => {
                    crate::warn::warn(format!(
                        "failed to load index: {e}; falling back to disk scan"
                    ));
                    None
                }
            }
        } else {
            None
        }
    } else {
        None
    };

    let mut ctx = CommandContext {
        dir: &dir,
        site_prefix,
        effective_format,
        user_format: format,
        snapshot_index: &mut snapshot_index,
        index_path: cli.index.as_deref(),
    };
    let result = dispatch(cli.command, &mut ctx);

    let pipeline = OutputPipeline {
        user_format: format,
        jq_filter,
        hint_ctx: hint_ctx.as_ref(),
        count: cli.count,
    };
    let code = pipeline.finalize(result);
    if code == 0 {
        Ok(())
    } else {
        Err(AppError::Exit(code))
    }
}