bmrk 0.4.0

A fast TUI for directory navigation and bookmark management
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
mod app;
mod bookmarks;
mod config;
mod dir_index;
mod disks;
mod event_handler;
mod navigation;
mod platform;
mod quick_jump;
mod search;
mod terminal;
mod theme;
mod tree_node;
mod ui;

use anyhow::Result;
use app::App;
use bookmarks::Bookmarks;
use clap::Parser;
use config::Config;
use platform::canonicalize_and_normalize;
use std::path::{Path, PathBuf};
use terminal::{cleanup_terminal_compact, run_app, setup_terminal_compact};

#[derive(Parser)]
#[command(name = "bmrk")]
#[command(about = "Interactive bookmark manager and directory navigator")]
#[command(disable_help_flag = true)]
#[command(disable_version_flag = true)]
struct Args {
    /// Print help information
    #[arg(short = 'h', long = "help")]
    help: bool,

    /// Print version information
    #[arg(short = 'v', long = "version")]
    version: bool,

    /// List all bookmarks
    #[arg(short = 'l', long = "list")]
    list: bool,

    /// Add a bookmark with the given name (uses current dir or trailing path arg)
    #[arg(
        short = 'a',
        long = "add",
        visible_short_alias = 'c',
        value_name = "NAME"
    )]
    add: Option<String>,

    /// Delete a bookmark by name
    #[arg(short = 'd', long = "del", value_name = "NAME")]
    del: Option<String>,

    /// All positional arguments (path or bookmark name)
    #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
    args: Vec<String>,
}

/// Split `input` at its first path separator into `(head, tail)`, stripping any
/// leading separators from `tail` so it can never re-root the later join.
///
/// Returns [`None`] when `input` contains no separator. On Windows both `/` and
/// `\` count as separators; on Unix only `/`.
fn split_bookmark_prefix(input: &str) -> Option<(&str, &str)> {
    #[cfg(windows)]
    let sep: &[char] = &['/', '\\'];
    #[cfg(not(windows))]
    let sep: &[char] = &['/'];

    let idx = input.find(sep)?;
    let head = &input[..idx];
    let tail = input[idx + 1..].trim_start_matches(sep);
    Some((head, tail))
}

/// Resolve a positional argument to a directory path.
///
/// Accepted forms, in resolution order:
/// - an explicit absolute or relative path (`/x`, `./x`, `../x`, `C:\x`) — resolved
///   against `base` and never reinterpreted as a bookmark reference;
/// - `name/sub/dir` — if `name` is a saved bookmark, the remainder is resolved
///   against that bookmark's directory (an existing plain relative path of the same
///   spelling still wins, so this never shadows a real `dir/subdir` under `base`);
/// - a bare bookmark name;
/// - a plain relative path resolved against `base`.
///
/// `base` is the directory relative paths are resolved against (the process's
/// current directory in normal use; an explicit value keeps tests hermetic).
fn resolve_path_or_bookmark(input: &str, bookmarks: &Bookmarks, base: &Path) -> Result<PathBuf> {
    // Windows: Handle bare drive letters (e.g., "C:", "E:")
    #[cfg(windows)]
    {
        if input.len() == 2 && input.chars().nth(1) == Some(':') {
            let drive_letter = input.chars().next().unwrap();
            if drive_letter.is_ascii_alphabetic() {
                let root_path = format!("{}\\", input);
                let path = PathBuf::from(&root_path);
                if path.exists() {
                    return Ok(canonicalize_and_normalize(&path)?);
                } else {
                    anyhow::bail!("Drive not found: {}", input);
                }
            }
        }
    }

    // An explicit absolute or relative path. `is_absolute_path` also returns true
    // for a leading `./` or `../`, so such a path is always resolved literally and
    // never treated as a `<bookmark>/<subpath>` reference. Joining an absolute
    // path onto `base` simply yields the absolute path.
    if platform::is_absolute_path(input) {
        let path = base.join(input);
        if !path.exists() {
            anyhow::bail!("Directory not found: {}", input);
        }
        return Ok(canonicalize_and_normalize(&path)?);
    }

    // `name/sub/dir`: a bookmark name followed by a path relative to it.
    if let Some((head, tail)) = split_bookmark_prefix(input) {
        // A real relative path that exists always wins, so this can never shadow
        // an existing `dir/subdir` under `base`.
        let literal = base.join(input);
        if literal.exists() {
            return Ok(canonicalize_and_normalize(&literal)?);
        }

        if let Some(bookmark) = bookmarks.get(head) {
            if !bookmark.path.exists() {
                anyhow::bail!(
                    "Bookmark '{}' points to non-existent directory: {}\n\
                    Use 'bm -l' to see all bookmarks",
                    head,
                    bookmark.path.display()
                );
            }

            let target = if tail.is_empty() {
                bookmark.path.clone()
            } else {
                bookmark.path.join(platform::normalize_path_separator(tail))
            };

            if !target.exists() {
                anyhow::bail!(
                    "Bookmark '{}' has no entry '{}': {} does not exist",
                    head,
                    tail,
                    target.display()
                );
            }

            return Ok(canonicalize_and_normalize(&target)?);
        }

        // `head` is not a bookmark — fall through to the generic handling below,
        // which ends in the combined "neither bookmark nor directory" error.
    }

    if let Some(bookmark) = bookmarks.get(input) {
        if bookmark.path.exists() {
            return Ok(bookmark.path.clone());
        } else {
            anyhow::bail!(
                "Bookmark '{}' points to non-existent directory: {}\n\
                Use 'bm -l' to see all bookmarks",
                input,
                bookmark.path.display()
            );
        }
    }

    let path = base.join(input);
    if path.exists() {
        return Ok(canonicalize_and_normalize(&path)?);
    }

    anyhow::bail!(
        "Neither bookmark '{}' nor directory '{}' found.\n\
        Use 'bm -l' to see all bookmarks",
        input,
        input
    );
}

fn main() -> Result<()> {
    let args = Args::parse();

    if args.version {
        println!("bmrk {}", env!("CARGO_PKG_VERSION"));
        println!("{}", env!("CARGO_PKG_DESCRIPTION"));
        println!();
        println!(
            "Platform:  {} ({})",
            std::env::consts::OS,
            std::env::consts::ARCH
        );
        match Config::global_config_path() {
            Some(path) => println!("Config:    {}", path.display()),
            None => println!("Config:    (could not determine config directory)"),
        }
        match dirs::config_dir() {
            Some(dir) => println!(
                "Bookmarks: {}",
                dir.join("bmrk").join("bookmarks.json").display()
            ),
            None => println!("Bookmarks: (could not determine config directory)"),
        }
        println!("Homepage:  {}", env!("CARGO_PKG_REPOSITORY"));
        return Ok(());
    }

    if args.help {
        for line in ui::get_help_content() {
            println!("{}", line);
        }
        return Ok(());
    }

    if args.list {
        let bookmarks = Bookmarks::new()?;
        println!("Bookmarks:");
        if bookmarks.list().is_empty() {
            println!("  No bookmarks saved yet.");
            println!("\nUsage:");
            println!("  bm -a <name> [path]    Add a bookmark (alias: -c)");
            println!("  bm -d <name>           Remove a bookmark");
            println!("  bm -l                  List all bookmarks");
        } else {
            for bookmark in bookmarks.list() {
                let name = bookmark.name.as_deref().unwrap_or("(unnamed)");
                println!(
                    "  {} -> {} ({})",
                    bookmark.key,
                    name,
                    bookmark.path.display()
                );
            }
        }
        return Ok(());
    }

    if let Some(name) = args.add {
        let mut bookmarks = Bookmarks::new()?;
        let path = if !args.args.is_empty() {
            PathBuf::from(&args.args[0])
        } else {
            std::env::current_dir()?
        };

        if !path.exists() {
            anyhow::bail!("Path does not exist: {}", path.display());
        }

        let mut path = canonicalize_and_normalize(&path)?;

        if path.is_file() {
            if let Some(parent) = path.parent() {
                path = parent.to_path_buf();
                eprintln!("Note: File provided, using parent directory instead");
            } else {
                anyhow::bail!("Cannot determine parent directory");
            }
        }

        let dir_name = path
            .file_name()
            .and_then(|n| n.to_str())
            .map(|s| s.to_string());

        bookmarks.add(name.clone(), path.clone(), dir_name)?;
        println!("Bookmark '{}' added: {}", name, path.display());
        return Ok(());
    }

    if let Some(name) = args.del {
        let mut bookmarks = Bookmarks::new()?;
        bookmarks.remove(&name)?;
        println!("Bookmark '{}' removed", name);
        return Ok(());
    }

    // If path/bookmark argument provided, resolve and output it
    if !args.args.is_empty() {
        let bookmarks = Bookmarks::new()?;
        let cwd = std::env::current_dir()?;
        let resolved = resolve_path_or_bookmark(&args.args[0], &bookmarks, &cwd)?;
        println!("{}", resolved.display());
        return Ok(());
    }

    // No arguments: launch interactive compact TUI
    let start_path = std::env::current_dir()?;
    let mut app = App::new(start_path)?;
    app.start_background_index();

    let result = {
        let mut terminal = setup_terminal_compact()?;
        run_app(&mut terminal, &mut app)
    };
    cleanup_terminal_compact()?;

    if let Some(path) = result? {
        println!("{}", path.display());
    }

    Ok(())
}

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

    fn bookmarks_in(dir: &TempDir) -> Bookmarks {
        Bookmarks::new_in_memory(dir.path().join("bookmarks.json"))
    }

    #[test]
    fn split_bookmark_prefix_splits_on_first_separator() {
        assert_eq!(
            split_bookmark_prefix("work/sub/dir"),
            Some(("work", "sub/dir"))
        );
        assert_eq!(split_bookmark_prefix("work/"), Some(("work", "")));
        // Leading separators on the tail are stripped so it can never re-root the join.
        assert_eq!(split_bookmark_prefix("work//sub"), Some(("work", "sub")));
        assert_eq!(split_bookmark_prefix("work"), None);
    }

    #[test]
    fn resolves_bookmark_with_subpath() {
        let bm_dir = TempDir::new().unwrap();
        let target = TempDir::new().unwrap();
        std::fs::create_dir_all(target.path().join("sub").join("child")).unwrap();

        let mut bookmarks = bookmarks_in(&bm_dir);
        bookmarks
            .add("work".to_string(), target.path().to_path_buf(), None)
            .unwrap();

        let base = TempDir::new().unwrap();
        let resolved = resolve_path_or_bookmark("work/sub/child", &bookmarks, base.path()).unwrap();
        assert_eq!(
            resolved,
            canonicalize_and_normalize(&target.path().join("sub").join("child")).unwrap()
        );
    }

    #[test]
    fn resolves_bare_bookmark_unchanged() {
        let bm_dir = TempDir::new().unwrap();
        let target = TempDir::new().unwrap();
        let mut bookmarks = bookmarks_in(&bm_dir);
        bookmarks
            .add("work".to_string(), target.path().to_path_buf(), None)
            .unwrap();

        let base = TempDir::new().unwrap();
        let resolved = resolve_path_or_bookmark("work", &bookmarks, base.path()).unwrap();
        assert_eq!(resolved, target.path().to_path_buf());
    }

    #[test]
    fn trailing_separator_resolves_to_the_bookmark_itself() {
        let bm_dir = TempDir::new().unwrap();
        let target = TempDir::new().unwrap();
        let mut bookmarks = bookmarks_in(&bm_dir);
        bookmarks
            .add("work".to_string(), target.path().to_path_buf(), None)
            .unwrap();

        let base = TempDir::new().unwrap();
        let resolved = resolve_path_or_bookmark("work/", &bookmarks, base.path()).unwrap();
        assert_eq!(resolved, canonicalize_and_normalize(target.path()).unwrap());
    }

    #[test]
    fn literal_relative_path_wins_over_bookmark_prefix() {
        let base = TempDir::new().unwrap();
        std::fs::create_dir_all(base.path().join("docs").join("api")).unwrap();

        let elsewhere = TempDir::new().unwrap();
        std::fs::create_dir_all(elsewhere.path().join("api")).unwrap();

        let bm_dir = TempDir::new().unwrap();
        let mut bookmarks = bookmarks_in(&bm_dir);
        bookmarks
            .add("docs".to_string(), elsewhere.path().to_path_buf(), None)
            .unwrap();

        let resolved = resolve_path_or_bookmark("docs/api", &bookmarks, base.path()).unwrap();
        assert_eq!(
            resolved,
            canonicalize_and_normalize(&base.path().join("docs").join("api")).unwrap()
        );
    }

    #[test]
    fn missing_subpath_under_bookmark_is_an_error() {
        let bm_dir = TempDir::new().unwrap();
        let target = TempDir::new().unwrap();
        let mut bookmarks = bookmarks_in(&bm_dir);
        bookmarks
            .add("work".to_string(), target.path().to_path_buf(), None)
            .unwrap();

        let base = TempDir::new().unwrap();
        let err = resolve_path_or_bookmark("work/nope", &bookmarks, base.path())
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("work"),
            "error should name the bookmark: {err}"
        );
        assert!(
            err.contains("nope"),
            "error should name the missing entry: {err}"
        );
    }

    #[test]
    fn unknown_prefix_with_separator_falls_through_to_combined_error() {
        let bm_dir = TempDir::new().unwrap();
        let bookmarks = bookmarks_in(&bm_dir);
        let base = TempDir::new().unwrap();
        let err = resolve_path_or_bookmark("nosuch/sub", &bookmarks, base.path())
            .unwrap_err()
            .to_string();
        assert!(err.contains("Neither bookmark"), "{err}");
    }

    #[test]
    fn bookmark_prefix_pointing_to_missing_dir_is_an_error() {
        let bm_dir = TempDir::new().unwrap();
        let mut bookmarks = bookmarks_in(&bm_dir);
        bookmarks
            .add(
                "ghost".to_string(),
                PathBuf::from("/no/such/place/bmrk-test-xyz"),
                None,
            )
            .unwrap();
        let base = TempDir::new().unwrap();
        let err = resolve_path_or_bookmark("ghost/sub", &bookmarks, base.path())
            .unwrap_err()
            .to_string();
        assert!(err.contains("non-existent"), "{err}");
    }
}