hyalo-cli 0.12.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
#![allow(clippy::missing_errors_doc)]
pub mod append;
pub mod backlinks;
pub mod create_index;
pub mod drop_index;
pub mod find;
pub mod init;
pub mod links;
pub mod lint;
pub(crate) mod mutation;
pub mod mv;
pub mod properties;
pub mod read;
pub mod remove;
pub mod section_scanner;
pub mod set;
pub mod summary;
pub mod tags;
pub mod tasks;
pub mod types;
pub mod views;

use crate::output::{CommandOutcome, Format};
use anyhow::Result;
use hyalo_core::discovery::{self, FileResolveError};
use hyalo_core::index::{ScanOptions, ScannedIndex, ScannedIndexBuild, SnapshotIndex, VaultIndex};
use std::path::{Path, PathBuf};

// ---------------------------------------------------------------------------
// Shared file resolution helpers
// ---------------------------------------------------------------------------

/// Outcome of resolving the set of files to operate on.
/// Either a list of `(full_path, rel_path)` pairs or a pre-formed `CommandOutcome`
/// (user error) when the resolution failed.
pub enum FilesOrOutcome {
    Files(Vec<(PathBuf, String)>),
    Outcome(CommandOutcome),
}

/// Resolve the set of files to operate on based on `--file` / `--glob` / all files.
/// Returns a user-error outcome for invalid inputs (e.g. file not found).
/// A glob that matches no files returns an empty file list with exit 0, not an error.
pub fn collect_files(
    dir: &Path,
    files: &[String],
    globs: &[String],
    format: Format,
) -> Result<FilesOrOutcome> {
    match (files.is_empty(), globs.is_empty()) {
        (false, true) => {
            // Resolve each file, best-effort: collect successes and errors
            let mut resolved = Vec::new();
            let mut errors = Vec::new();
            for f in files {
                match discovery::resolve_file(dir, f) {
                    Ok(r) => resolved.push(r),
                    Err(e) => errors.push((f.clone(), e)),
                }
            }
            if resolved.is_empty() {
                // All files failed — return error for the first one (no warning needed)
                let (_, first_err) = errors.into_iter().next().expect("at least one error");
                return Ok(FilesOrOutcome::Outcome(resolve_error_to_outcome(
                    first_err, format,
                )));
            }
            // Some succeeded — warn about the ones that didn't
            for (path, err) in &errors {
                let msg = match err {
                    FileResolveError::NotFound { .. } => format!("file not found: {path}"),
                    FileResolveError::NotFoundSuggestion { suggestion, .. } => {
                        format!("file not found: {path} (did you mean {suggestion}?)")
                    }
                    FileResolveError::MissingExtension { hint, .. } => {
                        format!("file not found: {path} (did you mean {hint}?)")
                    }
                    FileResolveError::IsDirectory { hint, .. } => {
                        format!("path is a directory, not a file: {path} (try {hint})")
                    }
                    FileResolveError::OutsideVault { .. } => {
                        format!("file resolves outside vault boundary: {path}")
                    }
                    FileResolveError::InvalidPath { reason, .. } => {
                        format!("invalid path ({reason}): {path}")
                    }
                };
                crate::warn::warn(&msg);
            }
            Ok(FilesOrOutcome::Files(resolved))
        }
        (true, false) => {
            let all = discovery::discover_files(dir)?;
            let matched = discovery::match_globs(dir, &all, globs)?;
            crate::warn::warn_glob_dir_overlap(dir, globs, matched.len());
            Ok(FilesOrOutcome::Files(matched))
        }
        (true, true) => {
            // Operate on all .md files
            let all = discovery::discover_files(dir)?;
            let with_rel: Vec<(PathBuf, String)> = all
                .into_iter()
                .map(|p| {
                    let rel = discovery::relative_path(dir, &p);
                    (p, rel)
                })
                .collect();
            Ok(FilesOrOutcome::Files(with_rel))
        }
        (false, false) => {
            // Clap enforces mutual exclusivity; this branch is unreachable in practice
            let out = crate::output::format_error(
                format,
                "--file and --glob are mutually exclusive",
                None,
                None,
                None,
            );
            Ok(FilesOrOutcome::Outcome(CommandOutcome::UserError(out)))
        }
    }
}

/// Outcome of building a scanned index — either success or a user-facing error.
pub enum ScannedIndexOutcome {
    Index(ScannedIndexBuild),
    Outcome(CommandOutcome),
}

/// Resolved index — either a borrowed snapshot or an owned scanned build.
pub(crate) enum ResolvedIndex<'a> {
    Snapshot(&'a SnapshotIndex),
    Scanned(ScannedIndexBuild),
}

impl ResolvedIndex<'_> {
    pub(crate) fn as_index(&self) -> &dyn VaultIndex {
        match self {
            ResolvedIndex::Snapshot(idx) => *idx,
            ResolvedIndex::Scanned(build) => &build.index,
        }
    }
}

/// Outcome of [`resolve_index`]: the index is ready, or resolution produced a
/// user-facing error that should be returned early to the caller.
pub(crate) enum IndexResolution<'a> {
    /// The vault index was resolved successfully and is ready to query.
    Resolved(ResolvedIndex<'a>),
    /// File/glob resolution failed with a user-facing error; propagate as-is.
    Outcome(CommandOutcome),
}

/// Resolve the vault index: use the snapshot if available, otherwise scan from disk.
///
/// Returns `Ok(IndexResolution::Resolved(_))` on success.
/// Returns `Ok(IndexResolution::Outcome(_))` when file resolution produced a user-facing error.
/// Returns `Err(e)` for unexpected I/O or parse errors.
#[allow(clippy::too_many_arguments)]
pub(crate) fn resolve_index<'a>(
    snapshot: Option<&'a SnapshotIndex>,
    dir: &Path,
    files: &[String],
    globs: &[String],
    format: Format,
    site_prefix: Option<&str>,
    needs_full_vault: bool,
    options: ScanOptions<'_>,
) -> Result<IndexResolution<'a>> {
    if let Some(idx) = snapshot {
        return Ok(IndexResolution::Resolved(ResolvedIndex::Snapshot(idx)));
    }
    let outcome = build_scanned_index(
        dir,
        files,
        globs,
        format,
        site_prefix,
        needs_full_vault,
        &options,
    )?;
    match outcome {
        ScannedIndexOutcome::Index(build) => {
            Ok(IndexResolution::Resolved(ResolvedIndex::Scanned(build)))
        }
        ScannedIndexOutcome::Outcome(o) => Ok(IndexResolution::Outcome(o)),
    }
}

/// Build a [`ScannedIndex`] from disk, handling file discovery, warnings, and user errors.
///
/// When `needs_full_vault` is `true`, all `.md` files in `dir` are scanned regardless of
/// `files_arg` and `globs`.  Otherwise the normal `collect_files` resolution is used and a
/// user-error outcome is propagated if resolution fails.
pub fn build_scanned_index(
    dir: &Path,
    files_arg: &[String],
    globs: &[String],
    format: Format,
    site_prefix: Option<&str>,
    needs_full_vault: bool,
    options: &ScanOptions<'_>,
) -> Result<ScannedIndexOutcome> {
    let files: Vec<(PathBuf, String)> = if needs_full_vault {
        // Validate --file arguments even when doing a full-vault scan.
        // Without this, missing files silently produce zero results instead
        // of the expected UserError.
        if !files_arg.is_empty() {
            let mut resolved = Vec::new();
            let mut first_err = None;
            for f in files_arg {
                match discovery::resolve_file(dir, f) {
                    Ok(r) => resolved.push(r),
                    Err(e) if first_err.is_none() => first_err = Some(e),
                    Err(_) => {}
                }
            }
            if resolved.is_empty()
                && let Some(e) = first_err
            {
                return Ok(ScannedIndexOutcome::Outcome(resolve_error_to_outcome(
                    e, format,
                )));
            }
        }
        discovery::discover_files(dir)?
            .into_iter()
            .map(|p| {
                let rel = discovery::relative_path(dir, &p);
                (p, rel)
            })
            .collect()
    } else {
        match collect_files(dir, files_arg, globs, format)? {
            FilesOrOutcome::Outcome(o) => return Ok(ScannedIndexOutcome::Outcome(o)),
            FilesOrOutcome::Files(f) => f,
        }
    };

    let build = ScannedIndex::build(&files, site_prefix, options)?;

    for w in &build.warnings {
        crate::warn::warn(format!("skipping {}: {}", w.rel_path, w.message));
    }

    Ok(ScannedIndexOutcome::Index(build))
}

/// Guard that mutation commands require `--file` or `--glob`.
///
/// Returns `Some(CommandOutcome::UserError(...))` when neither flag is provided, or `None`
/// when the caller may proceed.  The `command_name` is used in the error message.
#[must_use]
pub fn require_file_or_glob(
    files: &[String],
    globs: &[String],
    command_name: &str,
    format: Format,
) -> Option<CommandOutcome> {
    if files.is_empty() && globs.is_empty() {
        let out = crate::output::format_error(
            format,
            &format!("{command_name} requires --file or --glob"),
            None,
            Some(
                "use --file <path> to target a single file or --glob <pattern> to target multiple files",
            ),
            None,
        );
        Some(CommandOutcome::UserError(out))
    } else {
        None
    }
}

/// Characters that form the start of comparison operators in filter syntax (`>=`, `<=`,
/// `!=`, `~=`).  When a `--property` key ends with one of these in a mutation command
/// (`set`, `remove`, `append`), it almost certainly means the user intended
/// `--where-property` instead.
const FILTER_OP_SUFFIXES: &[char] = &['<', '>', '!', '~'];

/// Reject a `--property` key that looks like a filter expression (ends with a comparison
/// operator prefix).  Returns `Some(CommandOutcome::UserError(...))` when rejected, or
/// `None` when the key is fine.
#[must_use]
pub fn reject_filter_in_mutation_property(key: &str, format: Format) -> Option<CommandOutcome> {
    let trimmed = key.trim_end();
    let ch = trimmed.chars().last()?;
    if !FILTER_OP_SUFFIXES.contains(&ch) {
        return None;
    }
    let out = crate::output::format_error(
        format,
        &format!(
            "invalid property name '{trimmed}': ends with '{ch}' which looks like a filter \
             operator (e.g. >=, <=, !=, ~=)"
        ),
        None,
        Some(
            "--property in mutation commands is for mutation, not filtering — \
             use --where-property to filter which files are mutated",
        ),
        None,
    );
    Some(CommandOutcome::UserError(out))
}

/// If exactly one file was specified and there is exactly one result, unwrap to a bare
/// JSON object. Otherwise return the full array.
#[must_use]
pub fn unwrap_single_file_result(
    files: &[String],
    mut results: Vec<serde_json::Value>,
) -> serde_json::Value {
    if files.len() == 1 && results.len() == 1 {
        results.pop().unwrap_or_default()
    } else {
        serde_json::json!(results)
    }
}

/// Convert a `FileResolveError` into a user-facing `CommandOutcome`.
#[must_use]
pub fn resolve_error_to_outcome(err: FileResolveError, format: Format) -> CommandOutcome {
    match err {
        FileResolveError::MissingExtension { path, hint } => {
            CommandOutcome::UserError(crate::output::format_error(
                format,
                "file not found",
                Some(&path),
                Some(&format!("did you mean {hint}?")),
                None,
            ))
        }
        FileResolveError::NotFound { path } => CommandOutcome::UserError(
            crate::output::format_error(format, "file not found", Some(&path), None, None),
        ),
        FileResolveError::NotFoundSuggestion { path, suggestion } => {
            CommandOutcome::UserError(crate::output::format_error(
                format,
                "file not found",
                Some(&path),
                Some(&format!("did you mean {suggestion}?")),
                None,
            ))
        }
        FileResolveError::IsDirectory { path, hint } => {
            CommandOutcome::UserError(crate::output::format_error(
                format,
                "path is a directory, not a file",
                Some(&path),
                Some(&hint),
                None,
            ))
        }
        FileResolveError::OutsideVault { path } => {
            CommandOutcome::UserError(crate::output::format_error(
                format,
                "file resolves outside vault boundary",
                Some(&path),
                None,
                None,
            ))
        }
        FileResolveError::InvalidPath { path, reason } => CommandOutcome::UserError(
            crate::output::format_error(format, "invalid path", Some(&path), Some(reason), None),
        ),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use hyalo_core::index::format_iso8601;

    // --- reject_filter_in_mutation_property ---

    #[test]
    fn reject_filter_gt() {
        assert!(reject_filter_in_mutation_property("priority>", Format::Json).is_some());
    }

    #[test]
    fn reject_filter_lt() {
        assert!(reject_filter_in_mutation_property("priority<", Format::Json).is_some());
    }

    #[test]
    fn reject_filter_bang() {
        assert!(reject_filter_in_mutation_property("status!", Format::Json).is_some());
    }

    #[test]
    fn reject_filter_tilde() {
        assert!(reject_filter_in_mutation_property("name~", Format::Json).is_some());
    }

    #[test]
    fn accept_plain_key() {
        assert!(reject_filter_in_mutation_property("status", Format::Json).is_none());
    }

    #[test]
    fn accept_hyphenated_key() {
        assert!(reject_filter_in_mutation_property("my-key", Format::Json).is_none());
    }

    #[test]
    fn accept_underscored_key() {
        assert!(reject_filter_in_mutation_property("key_name", Format::Json).is_none());
    }

    #[test]
    fn accept_empty_key() {
        // Empty keys are handled elsewhere; the guard should not panic
        assert!(reject_filter_in_mutation_property("", Format::Json).is_none());
    }

    // --- iso8601 ---

    #[test]
    fn iso8601_epoch() {
        assert_eq!(format_iso8601(0), "1970-01-01T00:00:00Z");
    }

    #[test]
    fn iso8601_known_date() {
        assert_eq!(format_iso8601(1_705_314_600), "2024-01-15T10:30:00Z");
    }
}