folder-auto-banner 0.7.2

Folder Auto Banner — A directory listing with instant context
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
use anyhow::Result;
use clap::Parser;
use folder_auto_banner::cli;
use std::env;

/// Built-in aliases. Each alias expands to a list of clap flags.
///
/// Multiple aliases compose: `f hidden verbose` → `-a -v`.
/// Aliases compose with explicit flags: `f tree -L 2` → `-R -D -L 2`.
/// Aliases compose with paths: `f top ./src` → `-S -r -m 20` for `./src`.
///
/// User intent: bare words (not numbers, not paths) are alias lookups.
/// Unknown bare words show the default cwd banner (no error).
const BUILTIN_ALIASES: &[(&str, &[&str])] = &[
    // Display modes
    ("tree", &["-R", "-D"]), // Recursive, only dirs (like `tree`)
    ("flat", &["-o"]),       // One file per line
    ("compact", &["-c"]),    // Compact output
    ("verbose", &["-v"]),    // Verbose output
    ("hidden", &["-a"]),     // Show hidden files
    ("dirs", &["-D"]),       // Only directories
    // Sort modes
    ("new", &["-t"]),         // Sort by time, newest first
    ("old", &["-t", "-r"]),   // Sort by time, oldest first
    ("big", &["-S"]),         // Sort by size, largest first
    ("small", &["-S", "-r"]), // Sort by size, smallest first
    ("ext", &["-X"]),         // Sort by extension
    ("git", &["-G"]),         // Sort by git status
    ("nosort", &["-U"]),      // No sort
    // Limits
    ("top", &["-S", "-r", "-m", "20"]),    // Top 20 largest files
    ("newest", &["-t", "-r", "-m", "20"]), // 20 newest files
    // Recursion
    ("recurse", &["-R"]), // Recurse into subdirectories
    // Actions
    ("edit", &["-e"]), // Force open in editor
    ("run", &["-x"]),  // Force run file
];

/// Look up an alias by name. Returns the flag list if found, None otherwise.
fn lookup_alias(name: &str) -> Option<&'static [&'static str]> {
    BUILTIN_ALIASES
        .iter()
        .find(|(n, _)| *n == name)
        .map(|(_, flags)| *flags)
}

/// Expand a list of args: for each non-flag arg that matches a
/// built-in alias, substitute the alias's flag list. Unknown bare
/// words — including paths and arbitrary words — are DROPPED (the
/// user said: only numbers, aliases, and flags produce output; paths
/// are dropped along with everything else that's not a number, alias,
/// or flag).
/// Returns the expanded arg list ready for clap to parse.
///
/// The expansion produces: ["f", "banner", <expanded-flags-and-numbers>].
fn expand_aliases_in_args(args: &[String]) -> Vec<String> {
    let mut new_args: Vec<String> = vec!["f".to_string(), "banner".to_string()];
    for a in args {
        if a.starts_with('-') || a.parse::<usize>().is_ok() {
            // Explicit flag or number — pass through unchanged.
            new_args.push(a.clone());
        } else if let Some(flags) = lookup_alias(a) {
            // Known alias — expand to its flags.
            for flag in flags {
                new_args.push(flag.to_string());
            }
        }
        // Anything else (paths, unknown words) — DROP.
    }
    new_args
}

/// Known subcommands that clap should parse. When the first non-flag
/// arg is one of these, we skip alias expansion and let clap handle
/// the invocation directly.
const KNOWN_SUBCOMMANDS: &[&str] = &["banner", "env", "install", "config", "daemon", "help"];

/// Returns true if the user-provided args contain an alias, number,
/// or flag (i.e., anything the banner subcommand should act on).
/// Paths and unknown bare words are not considered useful — they
/// are dropped per the "nothing happens" rule.
fn args_contain_something_useful(args: &[String]) -> bool {
    args.iter()
        .any(|a| a.starts_with('-') || lookup_alias(a).is_some() || a.parse::<usize>().is_ok())
}

/// Returns true if the invocation should exit 0 with no output —
/// the "nothing happens" rule. This is when the user typed at least
/// one arg but none of them are aliases, numbers, or flags. Paths
/// and unknown bare words both match. E.g. `f t`, `f foo`,
/// `f ./src`, `f /tmp`, `f Downloads` all match.
/// `f` (no args) returns false (default banner is shown).
/// `f tree`, `f 4`, `f -t`, `f -V` all return false.
fn should_exit_silently(args: &[String]) -> bool {
    !args.is_empty() && !args_contain_something_useful(args)
}

fn main() -> Result<()> {
    let args: Vec<String> = env::args().skip(1).collect();

    // If the first arg is a known subcommand, let clap handle it
    // directly. Aliases do not apply to subcommand invocations.
    if let Some(first) = args.first() {
        if KNOWN_SUBCOMMANDS.contains(&first.as_str()) {
            let cli = cli::Cli::parse();
            return cli.run();
        }
    }

    // "Nothing happens" rule: if the user typed only args that match
    // no alias, number, or flag (e.g. `f t`, `f foo`, `f ./src`,
    // `f /tmp`, `f Downloads`), the command exits 0 with no output.
    // The user said: "we only take numbers, aliases, and flags, not
    // folders and files by name." `f` (no args) still shows the
    // default banner for cwd.
    if should_exit_silently(&args) {
        return Ok(());
    }

    // If the args contain only flags (no aliases, no numbers), let
    // clap handle directly. This covers `f -V`, `f --help`, `f -e`,
    // `f -f txt`, etc. — invocations where the top-level Cli flags
    // are sufficient and no alias expansion is needed.
    let has_alias_or_number = args
        .iter()
        .any(|a| lookup_alias(a).is_some() || a.parse::<usize>().is_ok());
    if !has_alias_or_number && args.iter().any(|a| a.starts_with('-')) {
        let cli = cli::Cli::parse();
        return cli.run();
    }

    // Expand any built-in aliases in the args. Explicit flags and
    // numbers pass through. Anything else (paths, unknown words) is
    // dropped. The result is routed to the banner subcommand.
    let expanded = expand_aliases_in_args(&args);
    let cli = cli::Cli::parse_from(expanded);
    cli.run()
}

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

    // ===== BUILTIN_ALIASES integrity tests =====

    #[test]
    fn test_builtin_aliases_count_is_18() {
        assert_eq!(
            BUILTIN_ALIASES.len(),
            18,
            "BUILTIN_ALIASES should have 18 entries"
        );
    }

    #[test]
    fn test_builtin_aliases_no_duplicate_names() {
        let mut names: Vec<&str> = BUILTIN_ALIASES.iter().map(|(n, _)| *n).collect();
        names.sort();
        names.dedup();
        assert_eq!(
            names.len(),
            BUILTIN_ALIASES.len(),
            "BUILTIN_ALIASES must have no duplicate names"
        );
    }

    #[test]
    fn test_builtin_aliases_no_empty_flag_list() {
        for (name, flags) in BUILTIN_ALIASES {
            assert!(!flags.is_empty(), "alias {:?} has empty flag list", name);
        }
    }

    #[test]
    fn test_builtin_aliases_value_flag_pairs_valid() {
        // Each value-taking flag (like `-m`) must be followed by a value
        // (a token that doesn't start with `-`). Each boolean flag
        // (like `-t`) is a standalone token.
        const VALUE_TAKING: &[&str] = &["-m", "-f", "-L"];
        for (name, flags) in BUILTIN_ALIASES {
            let mut i = 0;
            while i < flags.len() {
                let flag = flags[i];
                if VALUE_TAKING.contains(&flag) {
                    // Next token must be a value (not start with `-`)
                    assert!(
                        i + 1 < flags.len(),
                        "alias {:?} has value-taking flag {:?} without a value",
                        name,
                        flag
                    );
                    let value = flags[i + 1];
                    assert!(
                        !value.starts_with('-'),
                        "alias {:?} has value-taking flag {:?} followed by another flag {:?}",
                        name,
                        flag,
                        value
                    );
                    i += 2;
                } else {
                    assert!(
                        flag.starts_with('-'),
                        "alias {:?} has flag {:?} that doesn't start with '-'",
                        name,
                        flag
                    );
                    i += 1;
                }
            }
        }
    }

    // ===== lookup_alias tests (one per alias) =====

    #[test]
    fn test_lookup_tree() {
        assert_eq!(lookup_alias("tree"), Some(&["-R", "-D"][..]));
    }

    #[test]
    fn test_lookup_flat() {
        assert_eq!(lookup_alias("flat"), Some(&["-o"][..]));
    }

    #[test]
    fn test_lookup_compact() {
        assert_eq!(lookup_alias("compact"), Some(&["-c"][..]));
    }

    #[test]
    fn test_lookup_verbose() {
        assert_eq!(lookup_alias("verbose"), Some(&["-v"][..]));
    }

    #[test]
    fn test_lookup_hidden() {
        assert_eq!(lookup_alias("hidden"), Some(&["-a"][..]));
    }

    #[test]
    fn test_lookup_dirs() {
        assert_eq!(lookup_alias("dirs"), Some(&["-D"][..]));
    }

    #[test]
    fn test_lookup_new() {
        assert_eq!(lookup_alias("new"), Some(&["-t"][..]));
    }

    #[test]
    fn test_lookup_old() {
        assert_eq!(lookup_alias("old"), Some(&["-t", "-r"][..]));
    }

    #[test]
    fn test_lookup_big() {
        assert_eq!(lookup_alias("big"), Some(&["-S"][..]));
    }

    #[test]
    fn test_lookup_small() {
        assert_eq!(lookup_alias("small"), Some(&["-S", "-r"][..]));
    }

    #[test]
    fn test_lookup_ext() {
        assert_eq!(lookup_alias("ext"), Some(&["-X"][..]));
    }

    #[test]
    fn test_lookup_git() {
        assert_eq!(lookup_alias("git"), Some(&["-G"][..]));
    }

    #[test]
    fn test_lookup_nosort() {
        assert_eq!(lookup_alias("nosort"), Some(&["-U"][..]));
    }

    #[test]
    fn test_lookup_top() {
        assert_eq!(lookup_alias("top"), Some(&["-S", "-r", "-m", "20"][..]));
    }

    #[test]
    fn test_lookup_newest() {
        assert_eq!(lookup_alias("newest"), Some(&["-t", "-r", "-m", "20"][..]));
    }

    #[test]
    fn test_lookup_recurse() {
        assert_eq!(lookup_alias("recurse"), Some(&["-R"][..]));
    }

    #[test]
    fn test_lookup_edit() {
        assert_eq!(lookup_alias("edit"), Some(&["-e"][..]));
    }

    #[test]
    fn test_lookup_run() {
        assert_eq!(lookup_alias("run"), Some(&["-x"][..]));
    }

    #[test]
    fn test_lookup_unknown_returns_none() {
        assert_eq!(lookup_alias(""), None);
        assert_eq!(lookup_alias("foo"), None);
        assert_eq!(lookup_alias("Tree"), None); // case-sensitive
        assert_eq!(lookup_alias("TREE"), None); // case-sensitive
        assert_eq!(lookup_alias("t"), None); // single char not an alias
        assert_eq!(lookup_alias("trc"), None); // chains not aliases
    }

    // ===== expand_aliases_in_args tests =====

    #[test]
    fn test_expand_aliases_empty_args() {
        let result = expand_aliases_in_args(&[]);
        assert_eq!(result, vec!["f", "banner"]);
    }

    // ===== should_exit_silently tests =====

    #[test]
    fn test_should_exit_silently_no_args() {
        // `f` (no args) shows the default banner — not silent.
        assert!(!should_exit_silently(&[]));
    }

    #[test]
    fn test_should_exit_silently_unknown_word() {
        // `f t`, `f foo` — no flag/path/alias/number, exit silently.
        assert!(should_exit_silently(&["t".to_string()]));
        assert!(should_exit_silently(&["foo".to_string()]));
        assert!(should_exit_silently(&["Downloads".to_string()]));
    }

    #[test]
    fn test_should_exit_silently_with_flag() {
        // `f -e` — has flag, not silent.
        assert!(!should_exit_silently(&["-e".to_string()]));
        assert!(!should_exit_silently(&["-t".to_string()]));
        assert!(!should_exit_silently(&["--version".to_string()]));
    }

    #[test]
    fn test_should_exit_silently_with_path() {
        // `f ./src`, `f /tmp` — paths are dropped, exit silently.
        assert!(should_exit_silently(&["./src".to_string()]));
        assert!(should_exit_silently(&["/tmp".to_string()]));
        assert!(should_exit_silently(&["~/Downloads".to_string()]));
    }

    #[test]
    fn test_should_exit_silently_with_alias() {
        // `f tree`, `f hidden verbose` — has alias, not silent.
        assert!(!should_exit_silently(&["tree".to_string()]));
        assert!(!should_exit_silently(&[
            "hidden".to_string(),
            "verbose".to_string()
        ]));
    }

    #[test]
    fn test_should_exit_silently_with_number() {
        // `f 4` — has number, not silent.
        assert!(!should_exit_silently(&["4".to_string()]));
        assert!(!should_exit_silently(&["42".to_string()]));
    }

    #[test]
    fn test_should_exit_silently_mixed() {
        // `f t 4` — has number 4, not silent.
        assert!(!should_exit_silently(&["t".to_string(), "4".to_string()]));
        // `f t ./src` — paths are dropped, so the only useful arg is
        // the (unknown) `t`, which means silent.
        assert!(should_exit_silently(&[
            "t".to_string(),
            "./src".to_string()
        ]));
    }

    #[test]
    fn test_expand_aliases_single_alias() {
        let result = expand_aliases_in_args(&["tree".to_string()]);
        assert_eq!(result, vec!["f", "banner", "-R", "-D"]);
    }

    #[test]
    fn test_expand_aliases_two_aliases() {
        let result = expand_aliases_in_args(&["hidden".to_string(), "verbose".to_string()]);
        assert_eq!(result, vec!["f", "banner", "-a", "-v"]);
    }

    #[test]
    fn test_expand_aliases_three_aliases() {
        let result = expand_aliases_in_args(&[
            "new".to_string(),
            "recurse".to_string(),
            "hidden".to_string(),
        ]);
        assert_eq!(result, vec!["f", "banner", "-t", "-R", "-a"]);
    }

    #[test]
    fn test_expand_aliases_unknown_word_dropped() {
        // User's rule: "if no alias found, nothing happens" — unknown
        // bare words are dropped from the args, leaving the default
        // banner for cwd.
        let result = expand_aliases_in_args(&["nonexistentword".to_string()]);
        assert_eq!(result, vec!["f", "banner"]);
    }

    #[test]
    fn test_expand_aliases_drops_paths() {
        // Paths are dropped (the "nothing happens" rule applies to
        // paths too — only numbers, aliases, and flags are useful).
        let result = expand_aliases_in_args(&["tree".to_string(), "./src".to_string()]);
        assert_eq!(result, vec!["f", "banner", "-R", "-D"]);
    }

    #[test]
    fn test_expand_aliases_drops_unknown_words() {
        // Unknown bare words (e.g. `f`, `foo`, `Downloads`) are dropped.
        let result =
            expand_aliases_in_args(&["f".to_string(), "foo".to_string(), "Downloads".to_string()]);
        assert_eq!(result, vec!["f", "banner"]);
    }

    #[test]
    fn test_expand_aliases_with_number() {
        let result = expand_aliases_in_args(&["1".to_string()]);
        assert_eq!(result, vec!["f", "banner", "1"]);
    }

    #[test]
    fn test_expand_aliases_alias_with_value_flags() {
        // top has 4 flags including a value
        let result = expand_aliases_in_args(&["top".to_string()]);
        assert_eq!(result, vec!["f", "banner", "-S", "-r", "-m", "20"]);
    }

    #[test]
    fn test_expand_aliases_mix_of_alias_and_path_drops_path() {
        // `f hidden /tmp verbose` — /tmp is dropped, alias and verbose
        // are kept.
        let result = expand_aliases_in_args(&[
            "hidden".to_string(),
            "/tmp".to_string(),
            "verbose".to_string(),
        ]);
        assert_eq!(result, vec!["f", "banner", "-a", "-v"]);
    }
}