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
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
use std::path::Path;
use anyhow::Result;
use crate::cli::args::{
Commands, FindFilters, LinksAction, PropertiesAction, TagsAction, TaskAction, TypesAction,
ViewsAction, resolve_single_file,
};
use crate::commands::{
IndexResolution, ResolvedIndex, append as append_commands, backlinks as backlinks_commands,
create_index as create_index_commands, drop_index as drop_index_commands,
find as find_commands, links as links_commands, lint as lint_commands, mv as mv_commands,
properties, read as read_commands, remove as remove_commands, resolve_index,
set as set_commands, summary as summary_commands, tags as tag_commands, tasks as task_commands,
};
use crate::output::{CommandOutcome, Format};
use hyalo_core::bm25::parse_language;
use hyalo_core::filter;
use hyalo_core::index::{ScanOptions, SnapshotIndex, VaultIndex as _};
use hyalo_core::schema::SchemaConfig;
/// Shared context for command dispatch.
pub(crate) struct CommandContext<'a> {
pub dir: &'a Path,
pub site_prefix: Option<&'a str>,
/// Internal format — always Json; commands build JSON, pipeline handles conversion.
pub effective_format: Format,
/// The user-requested format (Text or Json). Used by `read` to decide between
/// `RawOutput` (text mode) and `Success` (JSON mode).
pub user_format: Format,
pub snapshot_index: &'a mut Option<SnapshotIndex>,
pub index_path: Option<&'a Path>,
/// Default stemming language from `[search] language` in `.hyalo.toml`.
pub config_language: Option<&'a str>,
/// Parsed schema configuration from `[schema.*]` sections in `.hyalo.toml`.
pub schema: &'a SchemaConfig,
/// Optional exit code override set by commands that need a non-0/2 exit code
/// (e.g. `lint` returns 1 when errors are found). The output pipeline uses this
/// to override its own exit code calculation.
pub exit_code_override: Option<i32>,
}
/// Parse `--where-property` filters and validate `--where-tag` names.
/// Returns an error string on invalid input.
fn parse_where_filters(
where_properties: &[String],
where_tags: &[String],
) -> Result<Vec<filter::PropertyFilter>, String> {
let filters = where_properties
.iter()
.map(|s| filter::parse_property_filter(s))
.collect::<Result<Vec<_>, _>>()
.map_err(|e| e.to_string())?;
for tag in where_tags {
crate::commands::tags::validate_tag(tag)?;
}
Ok(filters)
}
pub(crate) fn dispatch(command: Commands, ctx: &mut CommandContext<'_>) -> Result<CommandOutcome> {
let dir = ctx.dir;
let site_prefix = ctx.site_prefix;
let effective_format = ctx.effective_format;
let snapshot_index = &mut *ctx.snapshot_index;
let index_path = ctx.index_path;
match command {
Commands::Find {
pattern,
file_positional,
view: _, // resolved before dispatch
filters: mut filters_raw,
} => {
// Merge positional files into filters (clap prevents positional+--file
// and positional+--glob at parse time; a view may have set glob though).
if !file_positional.is_empty() {
if !filters_raw.glob.is_empty() {
crate::warn::warn(
"positional file arguments override the view's --glob; \
glob filter has been ignored",
);
}
filters_raw.file = file_positional;
filters_raw.glob.clear(); // file overrides view's glob
}
let FindFilters {
pattern: _, // pattern is handled in run.rs before dispatch
regexp,
properties,
tag,
task,
sections,
file,
glob,
fields,
sort,
reverse,
limit,
broken_links,
orphan,
dead_end,
title,
language,
} = filters_raw;
if orphan && dead_end {
crate::warn::warn(
"--orphan and --dead-end are mutually exclusive (no file can be both); results will always be empty",
);
}
// Parse property filters
let prop_filters: Vec<filter::PropertyFilter> = match properties
.iter()
.map(|s| filter::parse_property_filter(s))
.collect::<Result<Vec<_>, _>>()
{
Ok(f) => f,
Err(e) => {
return Ok(CommandOutcome::UserError(format!("Error: {e}")));
}
};
// Parse task filter
let task_filter = match task.as_deref().map(filter::parse_task_filter) {
Some(Ok(f)) => Some(f),
Some(Err(e)) => {
return Ok(CommandOutcome::UserError(format!("Error: {e}")));
}
None => None,
};
// Parse fields
let parsed_fields = match filter::Fields::parse(&fields) {
Ok(f) => f,
Err(e) => {
return Ok(CommandOutcome::UserError(format!("Error: {e}")));
}
};
// Parse sort
let sort_field = match sort.as_deref().map(filter::parse_sort) {
Some(Ok(f)) => Some(f),
Some(Err(e)) => {
return Ok(CommandOutcome::UserError(format!("Error: {e}")));
}
None => None,
};
// Parse section filters
let section_filters: Vec<hyalo_core::heading::SectionFilter> = match sections
.iter()
.map(|s| hyalo_core::heading::SectionFilter::parse(s))
.collect::<Result<Vec<_>, _>>()
{
Ok(f) => f,
Err(e) => {
return Ok(CommandOutcome::UserError(format!("Error: {e}")));
}
};
for t in &tag {
if let Err(msg) = crate::commands::tags::validate_tag(t) {
return Ok(CommandOutcome::UserError(format!("Error: {msg}")));
}
}
// Validate --language flag and config language against supported languages.
if let Some(ref lang) = language
&& let Err(e) = parse_language(lang)
{
return Ok(CommandOutcome::UserError(format!(
"invalid --language value {lang:?}: {e}"
)));
}
if let Some(cfg_lang) = ctx.config_language
&& let Err(e) = parse_language(cfg_lang)
{
return Ok(CommandOutcome::UserError(format!(
"invalid [search].language config value {cfg_lang:?}: {e}"
)));
}
// Strip the dir prefix from --file args so that
// filter_index_entries matches vault-relative paths.
let file: Vec<String> = file
.into_iter()
.map(|f| hyalo_core::discovery::strip_dir_prefix(dir, &f).unwrap_or(f))
.collect();
let sort_needs_backlinks =
matches!(sort_field.as_ref(), Some(filter::SortField::BacklinksCount));
let sort_needs_links =
matches!(sort_field.as_ref(), Some(filter::SortField::LinksCount));
let sort_needs_title = matches!(sort_field.as_ref(), Some(filter::SortField::Title));
let has_task_filter = task_filter.is_some();
let has_section_filter = !section_filters.is_empty();
let has_title_filter = title.is_some();
// BM25 pattern search requires reading file bodies for each candidate.
let has_bm25_search = pattern.is_some();
let needs_body =
find_commands::needs_body(&parsed_fields, has_task_filter, has_section_filter)
|| sort_needs_links
|| sort_needs_title
|| broken_links
|| orphan
|| dead_end
|| has_title_filter
|| has_bm25_search;
let needs_full_vault =
parsed_fields.backlinks || sort_needs_backlinks || orphan || dead_end;
// The link graph is only built when scan_body is true, so
// backlinks / backlink-sort always require body scanning.
let scan_body = needs_body || needs_full_vault;
match resolve_index(
snapshot_index.as_ref(),
dir,
&file,
&glob,
effective_format,
site_prefix,
needs_full_vault,
ScanOptions {
scan_body,
bm25_tokenize: false,
default_language: None,
},
)? {
IndexResolution::Resolved(resolved) => find_commands::find(
resolved.as_index(),
dir,
site_prefix,
pattern.as_deref(),
regexp.as_deref(),
&prop_filters,
&tag,
task_filter.as_ref(),
§ion_filters,
&file,
&glob,
&parsed_fields,
sort_field.as_ref(),
reverse,
limit,
broken_links,
orphan,
dead_end,
title.as_deref(),
effective_format,
language.as_deref(),
ctx.config_language,
),
IndexResolution::Outcome(outcome) => Ok(outcome),
}
}
Commands::Read {
file_positional,
file,
section,
lines,
frontmatter,
} => {
let file = match resolve_single_file(file_positional, file) {
Ok(f) => f,
Err(e) => return Ok(CommandOutcome::UserError(format!("{e}"))),
};
read_commands::run(
dir,
&file,
section.as_deref(),
lines.as_deref(),
frontmatter,
effective_format,
ctx.user_format,
)
}
Commands::Properties { action } => {
let action = action.unwrap_or(PropertiesAction::Summary { glob: vec![] });
match action {
PropertiesAction::Summary { ref glob } => match resolve_index(
snapshot_index.as_ref(),
dir,
&[],
glob,
effective_format,
site_prefix,
false,
ScanOptions {
scan_body: false,
bm25_tokenize: false,
default_language: None,
},
)? {
IndexResolution::Resolved(ResolvedIndex::Snapshot(idx)) => {
let filtered =
find_commands::filter_index_entries(idx.entries(), &[], glob);
match filtered {
Err(e) => Err(e),
Ok(filtered) => {
let paths: Vec<String> =
filtered.iter().map(|e| e.rel_path.clone()).collect();
let file_filter = if glob.is_empty() {
None
} else {
Some(paths.as_slice())
};
properties::properties_summary(idx, file_filter, effective_format)
}
}
}
IndexResolution::Resolved(ResolvedIndex::Scanned(build)) => {
properties::properties_summary(&build.index, None, effective_format)
}
IndexResolution::Outcome(outcome) => Ok(outcome),
},
PropertiesAction::Rename { from, to, glob } => properties::properties_rename(
dir,
&from,
&to,
&glob,
effective_format,
snapshot_index,
index_path,
),
}
}
Commands::Tags { action } => {
let action = action.unwrap_or(TagsAction::Summary { glob: vec![] });
match action {
TagsAction::Summary { ref glob } => match resolve_index(
snapshot_index.as_ref(),
dir,
&[],
glob,
effective_format,
site_prefix,
false,
ScanOptions {
scan_body: false,
bm25_tokenize: false,
default_language: None,
},
)? {
IndexResolution::Resolved(ResolvedIndex::Snapshot(idx)) => {
let filtered =
find_commands::filter_index_entries(idx.entries(), &[], glob);
match filtered {
Err(e) => Err(e),
Ok(filtered) => {
let paths: Vec<String> =
filtered.iter().map(|e| e.rel_path.clone()).collect();
let file_filter = if glob.is_empty() {
None
} else {
Some(paths.as_slice())
};
tag_commands::tags_summary(idx, file_filter, effective_format)
}
}
}
IndexResolution::Resolved(ResolvedIndex::Scanned(build)) => {
tag_commands::tags_summary(&build.index, None, effective_format)
}
IndexResolution::Outcome(outcome) => Ok(outcome),
},
TagsAction::Rename { from, to, glob } => tag_commands::tags_rename(
dir,
&from,
&to,
&glob,
effective_format,
snapshot_index,
index_path,
),
}
}
Commands::Task { action } => match action {
TaskAction::Read {
file_positional,
file,
line,
section,
all,
} => {
let file = match resolve_single_file(file_positional, file) {
Ok(f) => f,
Err(e) => return Ok(CommandOutcome::UserError(format!("{e}"))),
};
task_commands::task_read(
dir,
&file,
&line,
section.as_deref(),
all,
effective_format,
)
}
TaskAction::Toggle {
file_positional,
file,
line,
section,
all,
} => {
let file = match resolve_single_file(file_positional, file) {
Ok(f) => f,
Err(e) => return Ok(CommandOutcome::UserError(format!("{e}"))),
};
task_commands::task_toggle(
dir,
&file,
&line,
section.as_deref(),
all,
effective_format,
snapshot_index,
index_path,
)
}
TaskAction::Set {
file_positional,
file,
line,
section,
all,
status,
} => {
let file = match resolve_single_file(file_positional, file) {
Ok(f) => f,
Err(e) => return Ok(CommandOutcome::UserError(format!("{e}"))),
};
if status.chars().count() != 1 {
let out = crate::output::format_error(
effective_format,
"--status must be a single character",
None,
Some("example: --status '?' or --status '-'"),
None,
);
return Ok(CommandOutcome::UserError(out));
}
// chars().count() == 1 guarantees next() returns Some.
let ch = status
.chars()
.next()
.ok_or_else(|| anyhow::anyhow!("--status must be a single character"))?;
task_commands::task_set_status(
dir,
&file,
&line,
section.as_deref(),
all,
ch,
effective_format,
snapshot_index,
index_path,
)
}
},
Commands::Summary {
glob,
recent,
depth,
} => match resolve_index(
snapshot_index.as_ref(),
dir,
&[],
&glob,
effective_format,
site_prefix,
true,
ScanOptions {
scan_body: true,
bm25_tokenize: false,
default_language: None,
},
)? {
IndexResolution::Resolved(resolved) => summary_commands::summary(
dir,
resolved.as_index(),
&glob,
recent,
depth,
site_prefix,
effective_format,
ctx.schema,
),
IndexResolution::Outcome(outcome) => Ok(outcome),
},
Commands::Set {
file_positional,
properties,
tag,
mut file,
glob,
where_properties,
where_tags,
dry_run,
} => {
if !file_positional.is_empty() {
file = file_positional;
}
let where_prop_filters = match parse_where_filters(&where_properties, &where_tags) {
Ok(f) => f,
Err(e) => {
return Ok(CommandOutcome::UserError(format!("Error: {e}")));
}
};
set_commands::set(
dir,
&properties,
&tag,
&file,
&glob,
&where_prop_filters,
&where_tags,
effective_format,
snapshot_index,
index_path,
dry_run,
)
}
Commands::Remove {
file_positional,
properties,
tag,
mut file,
glob,
where_properties,
where_tags,
dry_run,
} => {
if !file_positional.is_empty() {
file = file_positional;
}
let where_prop_filters = match parse_where_filters(&where_properties, &where_tags) {
Ok(f) => f,
Err(e) => {
return Ok(CommandOutcome::UserError(format!("Error: {e}")));
}
};
remove_commands::remove(
dir,
&properties,
&tag,
&file,
&glob,
&where_prop_filters,
&where_tags,
effective_format,
snapshot_index,
index_path,
dry_run,
)
}
Commands::Append {
file_positional,
properties,
mut file,
glob,
where_properties,
where_tags,
dry_run,
} => {
if !file_positional.is_empty() {
file = file_positional;
}
let where_prop_filters = match parse_where_filters(&where_properties, &where_tags) {
Ok(f) => f,
Err(e) => {
return Ok(CommandOutcome::UserError(format!("Error: {e}")));
}
};
append_commands::append(
dir,
&properties,
&file,
&glob,
&where_prop_filters,
&where_tags,
effective_format,
snapshot_index,
index_path,
dry_run,
)
}
Commands::Backlinks {
file_positional,
file,
} => {
let file = match resolve_single_file(file_positional, file) {
Ok(f) => f,
Err(e) => return Ok(CommandOutcome::UserError(format!("{e}"))),
};
match resolve_index(
snapshot_index.as_ref(),
dir,
&[],
&[],
effective_format,
site_prefix,
true,
ScanOptions {
scan_body: true,
bm25_tokenize: false,
default_language: None,
},
)? {
IndexResolution::Resolved(resolved) => {
backlinks_commands::backlinks(resolved.as_index(), &file, dir, effective_format)
}
IndexResolution::Outcome(outcome) => Ok(outcome),
}
}
Commands::Mv {
file_positional,
file,
to,
dry_run,
} => {
let file = match resolve_single_file(file_positional, file) {
Ok(f) => f,
Err(e) => return Ok(CommandOutcome::UserError(format!("{e}"))),
};
mv_commands::mv(
dir,
&file,
&to,
dry_run,
effective_format,
site_prefix,
snapshot_index,
index_path,
)
}
Commands::CreateIndex {
output,
allow_outside_vault,
} => create_index_commands::create_index(
dir,
site_prefix,
output.as_deref(),
effective_format,
allow_outside_vault,
ctx.config_language,
),
Commands::DropIndex {
path,
allow_outside_vault,
} => drop_index_commands::drop_index(
dir,
path.as_deref(),
effective_format,
allow_outside_vault,
),
Commands::Links { action } => match action {
LinksAction::Fix {
dry_run: _,
apply,
threshold,
glob,
ignore_target,
} => match resolve_index(
snapshot_index.as_ref(),
dir,
&[],
&[],
effective_format,
site_prefix,
true,
ScanOptions {
scan_body: true,
bm25_tokenize: false,
default_language: None,
},
)? {
IndexResolution::Resolved(resolved) => links_commands::links_fix(
resolved.as_index(),
dir,
site_prefix,
&glob,
!apply,
threshold,
&ignore_target,
effective_format,
),
IndexResolution::Outcome(outcome) => Ok(outcome),
},
},
Commands::Lint {
file_positional,
file,
glob,
fix,
dry_run,
} => {
// Build the file list. Positional arg is treated as a single --file.
let mut files_arg: Vec<String> = file;
if let Some(pos) = file_positional {
files_arg.insert(0, pos);
}
let file_pairs =
match crate::commands::collect_files(dir, &files_arg, &glob, ctx.user_format)? {
crate::commands::FilesOrOutcome::Files(f) => f,
crate::commands::FilesOrOutcome::Outcome(o) => return Ok(o),
};
let fix_mode = if fix {
if dry_run {
lint_commands::FixMode::DryRun
} else {
lint_commands::FixMode::Apply
}
} else {
lint_commands::FixMode::Off
};
let (outcome, counts) =
lint_commands::lint_files_with_options(&file_pairs, ctx.schema, fix_mode)?;
// Signal exit code 1 when errors remain after fixes (set before returning).
if counts.errors > 0 {
ctx.exit_code_override = Some(1);
}
Ok(outcome)
}
// `Init`, `Deinit`, and `Completion` are handled as early returns before dispatch is called.
Commands::Init { .. } => unreachable!("Init is dispatched before this match reached"),
Commands::Deinit => unreachable!("Deinit is dispatched before this match reached"),
Commands::Completion { .. } => {
unreachable!("Completion is dispatched before this match reached")
}
Commands::Views { action } => {
let action = action.unwrap_or(ViewsAction::List);
match action {
ViewsAction::List => crate::commands::views::list_views(),
ViewsAction::Set {
name,
pattern,
mut filters,
} => {
if pattern.is_some() && filters.regexp.is_some() {
return Ok(CommandOutcome::UserError(
"Error: PATTERN and --regexp are mutually exclusive".to_owned(),
));
}
filters.pattern = pattern;
crate::commands::views::set_view(&name, &filters)
}
ViewsAction::Remove { name } => crate::commands::views::remove_view(&name),
}
}
Commands::Types { action } => {
let action = action.unwrap_or(TypesAction::List);
match action {
TypesAction::List => Ok(crate::commands::types::list_types(ctx.schema)),
TypesAction::Show { type_name } => {
Ok(crate::commands::types::show_type(&type_name, ctx.schema))
}
TypesAction::Create { type_name, print } => {
crate::commands::types::create_type(&type_name, print)
}
TypesAction::Remove { type_name } => {
crate::commands::types::remove_type(&type_name)
}
TypesAction::Set {
type_name,
required,
default,
property_type,
property_values,
filename_template,
dry_run,
} => crate::commands::types::set_type(
dir,
&type_name,
&required,
&default,
&property_type,
&property_values,
filename_template.as_deref(),
dry_run,
),
}
}
}
}