hyalo-cli 0.13.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
/// Returns `true` when a clap `UnknownArgument` error was triggered by `flag`.
///
/// Inspects `ContextKind::InvalidArg` in the error's context chain.
/// The `flag` parameter must include the leading `--` (e.g. `"--filter"`).
pub fn unknown_arg_is(err: &clap::Error, flag: &str) -> bool {
    use clap::error::{ContextKind, ContextValue};
    err.context().any(|(kind, value)| {
        kind == ContextKind::InvalidArg && matches!(value, ContextValue::String(s) if s == flag)
    })
}

/// Identify the first top-level subcommand token in `args`, accounting for
/// global value-taking flags (e.g. `--dir <path>`).
///
/// Returns `None` if no known top-level subcommand appears before `--` / end.
///
/// This is used by callers that need to show subcommand-specific error hints
/// (e.g. `hyalo append --tag …`) without being fooled by argv positions that
/// merely *contain* the subcommand name as a value (`hyalo read append …` or
/// `hyalo --dir append …`).
pub fn top_level_subcommand<'a>(args: &'a [String], cmd: &clap::Command) -> Option<&'a str> {
    // Value-taking root flags whose next token must be skipped (e.g. `--dir`).
    let value_flags: Vec<&str> = cmd
        .get_arguments()
        .filter(|a| a.get_num_args().is_some_and(|r| r.min_values() > 0))
        .filter_map(|a| a.get_long())
        .collect();

    let top_level_names: Vec<&str> = cmd.get_subcommands().map(clap::Command::get_name).collect();

    let mut skip_next = false;
    for arg in args.iter().skip(1) {
        if skip_next {
            skip_next = false;
            continue;
        }
        if arg == "--" {
            break;
        }
        if let Some(flag) = arg.strip_prefix("--") {
            if value_flags.contains(&flag) {
                skip_next = true;
            }
            continue;
        }
        if arg.starts_with('-') {
            continue;
        }
        if let Some(name) = top_level_names.iter().find(|&&n| n == arg.as_str()) {
            // Return a slice of the matching argv element rather than the
            // borrowed name table entry, so lifetimes tie to `args`.
            return args
                .iter()
                .find(|a| a.as_str() == *name)
                .map(String::as_str);
        }
    }
    None
}

/// Given the raw CLI args and the clap Command tree, detect when an unknown
/// `--flag` matches a known subcommand name and return a corrected command suggestion.
///
/// Returns `Some(suggestion_string)` if a correction was found, `None` otherwise.
pub fn suggest_subcommand_correction(args: &[String], cmd: &clap::Command) -> Option<String> {
    // args[0] is the binary name; find the first positional that matches a top-level subcommand.
    // Ensure args is non-empty (args[0] is the binary name).
    args.first()?;

    // Build a set of long flags that consume the next token as a value (e.g. --dir, --format).
    // Without this, `--dir task` would cause `task` to be misidentified as a parent subcommand.
    let value_flags: Vec<&str> = cmd
        .get_arguments()
        .filter(|a| a.get_num_args().is_some_and(|r| r.min_values() > 0))
        .filter_map(|a| a.get_long())
        .collect();

    // Walk args (skipping bin) to find the top-level subcommand and its position.
    // We stop at `--` (end-of-flags marker) and skip tokens that are values of
    // value-taking flags (e.g. the `foo` in `--dir foo`).
    let top_level_names: Vec<&str> = cmd.get_subcommands().map(clap::Command::get_name).collect();

    let mut parent_name: Option<&str> = None;
    let mut parent_pos: Option<usize> = None; // index into args (0-based, including bin)
    let mut skip_next = false;

    for (i, arg) in args.iter().enumerate().skip(1) {
        if skip_next {
            skip_next = false;
            continue;
        }
        if arg == "--" {
            break;
        }
        if let Some(flag) = arg.strip_prefix("--") {
            if value_flags.contains(&flag) {
                skip_next = true;
            }
            continue;
        }
        if arg.starts_with('-') {
            continue;
        }
        if let Some(name) = top_level_names.iter().find(|&&n| n == arg.as_str()) {
            parent_name = Some(name);
            parent_pos = Some(i);
            break;
        }
    }

    let parent_name = parent_name?;
    let parent_pos = parent_pos?;

    // Find the subcommand Command node for the parent.
    let parent_cmd = cmd
        .get_subcommands()
        .find(|s| s.get_name() == parent_name)?;

    parent_cmd.get_subcommands().next()?;

    // Scan args after the parent for `--<name>` where `<name>` matches a sub-subcommand
    // name or alias. Also skip flag values here for consistency.
    let mut found_flag_pos: Option<usize> = None;
    let mut found_sub_name: Option<&str> = None;
    skip_next = false;

    for (i, arg) in args.iter().enumerate().skip(parent_pos + 1) {
        if skip_next {
            skip_next = false;
            continue;
        }
        if arg == "--" {
            break;
        }
        if let Some(flag_value) = arg.strip_prefix("--") {
            // Match against the canonical name first, then any aliases (including hidden).
            let matched = parent_cmd.get_subcommands().find(|sub| {
                sub.get_name() == flag_value
                    || sub.get_all_aliases().any(|alias| alias == flag_value)
            });
            if let Some(sub) = matched {
                found_flag_pos = Some(i);
                found_sub_name = Some(sub.get_name());
                break;
            }
            // Check if this flag takes a value (look in parent_cmd's args too)
            let parent_value_flags: Vec<&str> = parent_cmd
                .get_arguments()
                .filter(|a| a.get_num_args().is_some_and(|r| r.min_values() > 0))
                .filter_map(|a| a.get_long())
                .collect();
            if parent_value_flags.contains(&flag_value) {
                skip_next = true;
            }
        }
    }

    let flag_pos = found_flag_pos?;
    let sub_name = found_sub_name?;

    // Reconstruct the corrected command:
    // - Remove the `--<name>` flag from its position
    // - Insert `<name>` immediately after the parent subcommand
    // - Shell-quote args that contain spaces or special characters
    let mut corrected: Vec<String> = Vec::with_capacity(args.len());

    for (i, arg) in args.iter().enumerate() {
        if i == flag_pos {
            // Skip the misplaced --<sub> flag
            continue;
        }
        corrected.push(crate::hints::shell_quote(arg));
        if i == parent_pos {
            // Insert the sub-subcommand name right after the parent
            corrected.push(sub_name.to_owned());
        }
    }

    Some(corrected.join(" "))
}

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

    // We build a minimal command tree that mirrors hyalo's real structure.
    // The Cli struct lives in the binary (main.rs), not in the lib, so we
    // construct an equivalent Command inline to keep the unit tests self-contained.

    fn make_cmd() -> clap::Command {
        use clap::{Arg, Command};

        Command::new("hyalo")
            .arg(Arg::new("dir").short('d').long("dir").num_args(1))
            .arg(Arg::new("format").long("format").num_args(1))
            .subcommand(
                Command::new("task")
                    .arg(Arg::new("file").short('f').long("file").num_args(1))
                    .arg(Arg::new("line").short('l').long("line").num_args(1))
                    .subcommand(Command::new("read"))
                    .subcommand(Command::new("toggle"))
                    .subcommand(Command::new("set").alias("set-status")),
            )
            .subcommand(
                Command::new("properties")
                    .subcommand(Command::new("summary"))
                    .subcommand(Command::new("rename")),
            )
            .subcommand(
                Command::new("tags")
                    .subcommand(Command::new("summary"))
                    .subcommand(Command::new("rename")),
            )
            .subcommand(Command::new("find").arg(Arg::new("property").short('p').long("property")))
    }

    fn args(s: &str) -> Vec<String> {
        s.split_whitespace().map(str::to_owned).collect()
    }

    #[test]
    fn toggle_before_file_flag() {
        // hyalo task --toggle --file f --line 1 -> hyalo task toggle --file f --line 1
        let cmd = make_cmd();
        let result =
            suggest_subcommand_correction(&args("hyalo task --toggle --file f --line 1"), &cmd);
        assert_eq!(
            result,
            Some("hyalo task toggle --file f --line 1".to_owned())
        );
    }

    #[test]
    fn toggle_after_other_flags() {
        // hyalo task --file f --line 1 --toggle -> hyalo task toggle --file f --line 1
        let cmd = make_cmd();
        let result =
            suggest_subcommand_correction(&args("hyalo task --file f --line 1 --toggle"), &cmd);
        assert_eq!(
            result,
            Some("hyalo task toggle --file f --line 1".to_owned())
        );
    }

    #[test]
    fn toggle_between_flags() {
        // hyalo task --file f --toggle --line 1 -> hyalo task toggle --file f --line 1
        let cmd = make_cmd();
        let result =
            suggest_subcommand_correction(&args("hyalo task --file f --toggle --line 1"), &cmd);
        assert_eq!(
            result,
            Some("hyalo task toggle --file f --line 1".to_owned())
        );
    }

    #[test]
    fn set_status_hyphenated() {
        // hyalo task --set-status --file f --line 1 --status ? -> hyalo task set --file f --line 1 --status ?
        let cmd = make_cmd();
        let result = suggest_subcommand_correction(
            &args("hyalo task --set-status --file f --line 1 --status ?"),
            &cmd,
        );
        assert_eq!(
            result,
            Some("hyalo task set --file f --line 1 --status '?'".to_owned())
        );
    }

    #[test]
    fn properties_rename() {
        // hyalo properties --rename --from a --to b -> hyalo properties rename --from a --to b
        let cmd = make_cmd();
        let result =
            suggest_subcommand_correction(&args("hyalo properties --rename --from a --to b"), &cmd);
        assert_eq!(
            result,
            Some("hyalo properties rename --from a --to b".to_owned())
        );
    }

    #[test]
    fn properties_summary() {
        // hyalo properties --summary -> hyalo properties summary
        let cmd = make_cmd();
        let result = suggest_subcommand_correction(&args("hyalo properties --summary"), &cmd);
        assert_eq!(result, Some("hyalo properties summary".to_owned()));
    }

    #[test]
    fn tags_rename() {
        // hyalo tags --rename --from a --to b -> hyalo tags rename --from a --to b
        let cmd = make_cmd();
        let result =
            suggest_subcommand_correction(&args("hyalo tags --rename --from a --to b"), &cmd);
        assert_eq!(result, Some("hyalo tags rename --from a --to b".to_owned()));
    }

    #[test]
    fn tags_summary() {
        // hyalo tags --summary -> hyalo tags summary
        let cmd = make_cmd();
        let result = suggest_subcommand_correction(&args("hyalo tags --summary"), &cmd);
        assert_eq!(result, Some("hyalo tags summary".to_owned()));
    }

    #[test]
    fn task_read() {
        // hyalo task --read --file f --line 1 -> hyalo task read --file f --line 1
        let cmd = make_cmd();
        let result =
            suggest_subcommand_correction(&args("hyalo task --read --file f --line 1"), &cmd);
        assert_eq!(result, Some("hyalo task read --file f --line 1".to_owned()));
    }

    #[test]
    fn unknown_flag_no_suggestion() {
        // hyalo task --verbose --file f toggle -> None (--verbose doesn't match any sub-subcommand)
        let cmd = make_cmd();
        let result =
            suggest_subcommand_correction(&args("hyalo task --verbose --file f toggle"), &cmd);
        assert_eq!(result, None);
    }

    #[test]
    fn find_has_no_subcommands() {
        // hyalo find --property status=done -> None (find has no subcommands)
        let cmd = make_cmd();
        let result =
            suggest_subcommand_correction(&args("hyalo find --property status=done"), &cmd);
        assert_eq!(result, None);
    }

    #[test]
    fn short_flags_preserved() {
        // hyalo task --toggle -f foo.md -l 28 -> hyalo task toggle -f foo.md -l 28
        let cmd = make_cmd();
        let result =
            suggest_subcommand_correction(&args("hyalo task --toggle -f foo.md -l 28"), &cmd);
        assert_eq!(result, Some("hyalo task toggle -f foo.md -l 28".to_owned()));
    }

    #[test]
    fn dir_value_not_confused_with_subcommand() {
        // hyalo --dir task --toggle --file f --line 1
        // Here "task" is the value of --dir, not a subcommand.
        // No parent subcommand is found, so no suggestion.
        let cmd = make_cmd();
        let result = suggest_subcommand_correction(
            &args("hyalo --dir task --toggle --file f --line 1"),
            &cmd,
        );
        assert_eq!(result, None);
    }

    #[test]
    fn dir_value_with_real_subcommand_after() {
        // hyalo --dir mydir task --toggle --file f --line 1
        // "mydir" is --dir's value, "task" is the real subcommand
        let cmd = make_cmd();
        let result = suggest_subcommand_correction(
            &args("hyalo --dir mydir task --toggle --file f --line 1"),
            &cmd,
        );
        assert_eq!(
            result,
            Some("hyalo --dir mydir task toggle --file f --line 1".to_owned())
        );
    }

    #[test]
    fn no_parent_subcommand_at_all() {
        // hyalo --toggle (no parent subcommand recognized)
        let cmd = make_cmd();
        let result = suggest_subcommand_correction(&args("hyalo --toggle"), &cmd);
        assert_eq!(result, None);
    }

    #[test]
    fn format_value_not_confused() {
        // hyalo --format json task --toggle --file f --line 1
        let cmd = make_cmd();
        let result = suggest_subcommand_correction(
            &args("hyalo --format json task --toggle --file f --line 1"),
            &cmd,
        );
        assert_eq!(
            result,
            Some("hyalo --format json task toggle --file f --line 1".to_owned())
        );
    }

    #[test]
    fn args_with_spaces_are_quoted() {
        // File path with spaces should be shell-quoted in the suggestion
        let cmd = make_cmd();
        let input = vec![
            "hyalo".to_owned(),
            "task".to_owned(),
            "--toggle".to_owned(),
            "--file".to_owned(),
            "My Notes.md".to_owned(),
            "--line".to_owned(),
            "1".to_owned(),
        ];
        let result = suggest_subcommand_correction(&input, &cmd);
        assert_eq!(
            result,
            Some("hyalo task toggle --file 'My Notes.md' --line 1".to_owned())
        );
    }
}