limb 0.1.0

A focused CLI for git worktree management
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
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
//! TOML configuration loading.
//!
//! Two layers:
//!
//! 1. **Global** (`~/.config/limb/config.toml`). User-wide settings such
//!    as `projects.roots`, theme, shell prefix.
//! 2. **Per-repo** (`.limb.toml` at any ancestor directory). Per-workspace
//!    settings such as shared files, templates, and hooks.
//!
//! The `*File` structs are the serde-deserialise shapes; [`Global`] and
//! [`Repo`] are the resolved runtime views the rest of the crate consumes.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};

/// File name of the per-repo config: `.limb.toml`.
pub const REPO_CONFIG_FILENAME: &str = ".limb.toml";
/// Directory under `$XDG_CONFIG_HOME` holding global config: `limb`.
pub const GLOBAL_CONFIG_DIRNAME: &str = "limb";
/// File name of the global config: `config.toml`.
pub const GLOBAL_CONFIG_FILENAME: &str = "config.toml";

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GlobalConfigFile {
    #[serde(default)]
    pub projects: ProjectsFile,
    #[serde(default)]
    pub ui: UiFile,
    #[serde(default)]
    pub shell: ShellFile,
    #[serde(default)]
    pub git: GitFile,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProjectsFile {
    #[serde(default)]
    pub roots: Vec<PathBuf>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UiFile {
    pub theme: Option<String>,
    pub show_upstream: Option<bool>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ShellFile {
    pub prefix: Option<String>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GitFile {
    pub default_base: Option<String>,
    pub default_remote: Option<String>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RepoConfigFile {
    #[serde(default)]
    pub worktrees: WorktreesFile,
    #[serde(default)]
    pub templates: BTreeMap<String, TemplateFile>,
    #[serde(default)]
    pub hooks: HooksFile,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct WorktreesFile {
    #[serde(default)]
    pub shared: Vec<PathBuf>,
    pub shared_source: Option<PathBuf>,
    pub base_dir: Option<PathBuf>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TemplateFile {
    pub base_branch: Option<String>,
    pub name_pattern: Option<String>,
    #[serde(default)]
    pub hooks: HooksFile,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HooksFile {
    pub pre_add: Option<PathBuf>,
    pub post_add: Option<PathBuf>,
    pub pre_remove: Option<PathBuf>,
    pub post_remove: Option<PathBuf>,
}

/// Resolved global configuration.
///
/// Built from `~/.config/limb/config.toml` or an explicit `--config` path,
/// with defaults filled in for missing fields.
#[derive(Debug, Clone, Serialize)]
pub struct Global {
    /// Roots scanned by `--all` and the cross-repo picker, tilde-expanded.
    pub projects_roots: Vec<PathBuf>,
    /// Theme name passed to the TUI picker (`vesper`, `default`, `nord`, ...).
    pub ui_theme: String,
    /// Whether `limb status` shows the UPSTREAM column by default.
    pub ui_show_upstream: bool,
    /// Default prefix for shell wrapper functions (e.g. `gw`).
    pub shell_prefix: String,
    /// Default base branch for `limb add` when no `BASE` is given.
    pub git_default_base: Option<String>,
    /// Default remote name used by `limb update` and friends.
    pub git_default_remote: String,
    /// Path of the file this config was loaded from, or `None` for
    /// built-in defaults.
    pub source: Option<PathBuf>,
}

/// Resolved per-repo configuration (`.limb.toml`).
#[derive(Debug, Clone, Serialize)]
pub struct Repo {
    /// Files listed under `[worktrees] shared = [...]`. Symlinked into
    /// every worktree by `limb setup`.
    pub worktrees_shared: Vec<PathBuf>,
    /// Optional override for the directory holding the shared files;
    /// defaults to `.shared/` under [`Self::root`].
    pub worktrees_shared_source: Option<PathBuf>,
    /// Directory under which `limb add` places new worktrees
    /// (default: `..`, i.e. siblings of the repo).
    pub worktrees_base_dir: PathBuf,
    /// Template name → definition, ordered for stable help output.
    pub templates: BTreeMap<String, Template>,
    /// Default hooks at the repo level (may be overridden by templates).
    pub hooks: Hooks,
    /// Path of the `.limb.toml` file this config was loaded from.
    pub source: PathBuf,
    /// Directory of the repo root (directory containing `source`).
    pub root: PathBuf,
}

/// Worktree-creation template.
///
/// Templates let a user declare a `name_pattern` (e.g. `feat-{slug}`), a
/// default `base_branch`, and template-specific hooks that override the
/// repo-level defaults.
#[derive(Debug, Clone, Serialize)]
pub struct Template {
    /// Base branch for `limb add` when this template is applied.
    pub base_branch: Option<String>,
    /// Name-interpolation pattern; `{slug}` is replaced with the user's
    /// argument.
    pub name_pattern: Option<String>,
    /// Per-template hooks overriding the repo defaults.
    pub hooks: Hooks,
}

/// The four hook points a template or repo can declare.
#[derive(Debug, Clone, Default, Serialize)]
pub struct Hooks {
    /// Runs before `limb add` creates the worktree; failure aborts.
    pub pre_add: Option<PathBuf>,
    /// Runs after `limb add` creates the worktree; failure is logged.
    pub post_add: Option<PathBuf>,
    /// Runs before `limb remove` deletes the worktree; failure aborts.
    pub pre_remove: Option<PathBuf>,
    /// Runs after `limb remove` deletes the worktree; failure is logged.
    pub post_remove: Option<PathBuf>,
}

impl Global {
    /// Loads global config from `explicit` if provided, else from
    /// `$XDG_CONFIG_HOME/limb/config.toml`.
    ///
    /// A missing file is not an error. [`Global::defaults`] is returned.
    ///
    /// # Errors
    ///
    /// Returns an error if the file exists but cannot be read, parsed, or
    /// if `$HOME` / `$XDG_CONFIG_HOME` cannot be resolved.
    pub fn load(explicit: Option<&Path>) -> Result<Self> {
        let (file, source) = load_global_file(explicit)?;
        Ok(Self::resolve(file, source))
    }

    /// Returns the built-in defaults without touching the filesystem.
    #[must_use]
    pub fn defaults() -> Self {
        Self::resolve(GlobalConfigFile::default(), None)
    }

    fn resolve(file: GlobalConfigFile, source: Option<PathBuf>) -> Self {
        let roots = file.projects.roots.into_iter().map(expand_tilde).collect();
        Self {
            projects_roots: roots,
            ui_theme: file.ui.theme.unwrap_or_else(|| "vesper".into()),
            ui_show_upstream: file.ui.show_upstream.unwrap_or(true),
            shell_prefix: file.shell.prefix.unwrap_or_else(|| "gw".into()),
            git_default_base: file.git.default_base,
            git_default_remote: file.git.default_remote.unwrap_or_else(|| "origin".into()),
            source,
        }
    }
}

impl Repo {
    /// Walks ancestors of `start` looking for the first `.limb.toml`.
    ///
    /// Returns `Ok(None)` if no config is found. The repo simply has no
    /// per-repo settings, which is not an error.
    ///
    /// # Errors
    ///
    /// Returns an error if a `.limb.toml` is found but cannot be read or
    /// parsed (e.g. invalid TOML, unknown fields).
    pub fn discover(start: &Path) -> Result<Option<Self>> {
        let Some((file, source, root)) = discover_repo_file(start)? else {
            return Ok(None);
        };
        Ok(Some(Self::resolve(file, source, root)))
    }

    fn resolve(file: RepoConfigFile, source: PathBuf, root: PathBuf) -> Self {
        let templates = file
            .templates
            .into_iter()
            .map(|(k, t)| (k, resolve_template(t)))
            .collect();
        Self {
            worktrees_shared: file.worktrees.shared,
            worktrees_shared_source: file.worktrees.shared_source,
            worktrees_base_dir: file
                .worktrees
                .base_dir
                .unwrap_or_else(|| PathBuf::from("..")),
            templates,
            hooks: resolve_hooks(file.hooks),
            source,
            root,
        }
    }

    /// Returns the directory that holds the files listed under
    /// `[worktrees] shared = [...]`. Explicit override or
    /// `.shared/` under [`Self::root`].
    #[must_use]
    pub fn resolved_shared_source(&self) -> PathBuf {
        self.worktrees_shared_source
            .clone()
            .unwrap_or_else(|| self.root.join(".shared"))
    }
}

fn resolve_template(t: TemplateFile) -> Template {
    Template {
        base_branch: t.base_branch,
        name_pattern: t.name_pattern,
        hooks: resolve_hooks(t.hooks),
    }
}

fn resolve_hooks(h: HooksFile) -> Hooks {
    Hooks {
        pre_add: h.pre_add,
        post_add: h.post_add,
        pre_remove: h.pre_remove,
        post_remove: h.post_remove,
    }
}

fn load_global_file(explicit: Option<&Path>) -> Result<(GlobalConfigFile, Option<PathBuf>)> {
    let path = match explicit {
        Some(p) => p.to_path_buf(),
        None => default_global_path()?,
    };
    if !path.exists() {
        return Ok((GlobalConfigFile::default(), None));
    }
    let contents =
        std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
    let file: GlobalConfigFile =
        toml::from_str(&contents).with_context(|| format!("parse {}", path.display()))?;
    Ok((file, Some(path)))
}

fn discover_repo_file(start: &Path) -> Result<Option<(RepoConfigFile, PathBuf, PathBuf)>> {
    for dir in start.ancestors() {
        let path = dir.join(REPO_CONFIG_FILENAME);
        if path.is_file() {
            let contents = std::fs::read_to_string(&path)
                .with_context(|| format!("read {}", path.display()))?;
            let file: RepoConfigFile =
                toml::from_str(&contents).with_context(|| format!("parse {}", path.display()))?;
            return Ok(Some((file, path, dir.to_path_buf())));
        }
    }
    Ok(None)
}

fn default_global_path() -> Result<PathBuf> {
    Ok(xdg_config_home()?
        .join(GLOBAL_CONFIG_DIRNAME)
        .join(GLOBAL_CONFIG_FILENAME))
}

fn xdg_config_home() -> Result<PathBuf> {
    if let Some(xdg) = std::env::var_os("XDG_CONFIG_HOME") {
        return Ok(PathBuf::from(xdg));
    }
    dirs::home_dir()
        .map(|h| h.join(".config"))
        .context("cannot resolve home directory; set $HOME or $XDG_CONFIG_HOME")
}

fn expand_tilde(p: PathBuf) -> PathBuf {
    let s = p.to_string_lossy();
    if let Some(stripped) = s.strip_prefix("~/")
        && let Some(home) = dirs::home_dir()
    {
        return home.join(stripped);
    }
    if s == "~"
        && let Some(home) = dirs::home_dir()
    {
        return home;
    }
    p
}

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

    fn tmp() -> TempDir {
        tempfile::tempdir().expect("tempdir")
    }

    #[test]
    fn global_defaults_when_file_absent() {
        let (file, source) = load_global_file(Some(Path::new("/nonexistent/limb.toml"))).unwrap();
        assert!(source.is_none());
        let g = Global::resolve(file, source);
        assert!(g.projects_roots.is_empty());
        assert_eq!(g.ui_theme, "vesper");
        assert!(g.ui_show_upstream);
        assert_eq!(g.shell_prefix, "gw");
        assert_eq!(g.git_default_remote, "origin");
    }

    #[test]
    fn global_parses_minimal() {
        let dir = tmp();
        let p = dir.path().join("config.toml");
        std::fs::write(
            &p,
            "[projects]\nroots = [\"~/dev/work\", \"~/dev/personal\"]\n",
        )
        .unwrap();
        let g = Global::load(Some(&p)).unwrap();
        assert_eq!(g.projects_roots.len(), 2);
        let home = dirs::home_dir().unwrap();
        assert_eq!(g.projects_roots[0], home.join("dev/work"));
    }

    #[test]
    fn global_rejects_unknown_field() {
        let dir = tmp();
        let p = dir.path().join("config.toml");
        std::fs::write(&p, "[ui]\nunknown_field = true\n").unwrap();
        assert!(Global::load(Some(&p)).is_err());
    }

    #[test]
    fn repo_discover_returns_none_when_absent() {
        let dir = tmp();
        assert!(Repo::discover(dir.path()).unwrap().is_none());
    }

    #[test]
    fn repo_discovers_limb_toml() {
        let dir = tmp();
        std::fs::write(
            dir.path().join(REPO_CONFIG_FILENAME),
            "[worktrees]\nshared = [\".env\", \".mise.toml\"]\n",
        )
        .unwrap();
        let r = Repo::discover(dir.path()).unwrap().unwrap();
        assert_eq!(r.worktrees_shared.len(), 2);
        assert_eq!(r.root, dir.path());
    }

    #[test]
    fn repo_walks_ancestors() {
        let dir = tmp();
        let nested = dir.path().join("sub/deep");
        std::fs::create_dir_all(&nested).unwrap();
        std::fs::write(
            dir.path().join(REPO_CONFIG_FILENAME),
            "[worktrees]\nshared = [\".env\"]\n",
        )
        .unwrap();
        let r = Repo::discover(&nested).unwrap().unwrap();
        assert_eq!(r.root, dir.path());
    }

    #[test]
    fn repo_templates() {
        let dir = tmp();
        std::fs::write(
            dir.path().join(REPO_CONFIG_FILENAME),
            "[templates.feature]\nbase_branch = \"main\"\nname_pattern = \"feat-{slug}\"\n",
        )
        .unwrap();
        let r = Repo::discover(dir.path()).unwrap().unwrap();
        let feat = r.templates.get("feature").unwrap();
        assert_eq!(feat.base_branch.as_deref(), Some("main"));
        assert_eq!(feat.name_pattern.as_deref(), Some("feat-{slug}"));
    }

    #[test]
    fn repo_hooks() {
        let dir = tmp();
        std::fs::write(
            dir.path().join(REPO_CONFIG_FILENAME),
            "[hooks]\npost_add = \"scripts/setup.sh\"\npre_remove = \"scripts/teardown.sh\"\n",
        )
        .unwrap();
        let r = Repo::discover(dir.path()).unwrap().unwrap();
        assert_eq!(
            r.hooks.post_add.as_deref(),
            Some(Path::new("scripts/setup.sh"))
        );
        assert_eq!(
            r.hooks.pre_remove.as_deref(),
            Some(Path::new("scripts/teardown.sh"))
        );
    }

    #[test]
    fn repo_default_base_dir_is_parent() {
        let dir = tmp();
        std::fs::write(dir.path().join(REPO_CONFIG_FILENAME), "").unwrap();
        let r = Repo::discover(dir.path()).unwrap().unwrap();
        assert_eq!(r.worktrees_base_dir, PathBuf::from(".."));
    }

    #[test]
    fn repo_shared_source_defaults_to_shared_subdir() {
        let dir = tmp();
        std::fs::write(dir.path().join(REPO_CONFIG_FILENAME), "").unwrap();
        let r = Repo::discover(dir.path()).unwrap().unwrap();
        assert_eq!(r.resolved_shared_source(), dir.path().join(".shared"));
    }

    #[test]
    fn tilde_expansion() {
        let home = dirs::home_dir().unwrap();
        assert_eq!(expand_tilde(PathBuf::from("~/foo")), home.join("foo"));
        assert_eq!(expand_tilde(PathBuf::from("~")), home);
        assert_eq!(expand_tilde(PathBuf::from("/abs")), PathBuf::from("/abs"));
    }
}

#[cfg(test)]
mod proptests {
    use super::*;
    use proptest::prelude::*;

    prop_compose! {
        fn arb_path()(s in "[a-zA-Z0-9._/-]{1,16}") -> PathBuf {
            PathBuf::from(s)
        }
    }

    prop_compose! {
        fn arb_hooks_file()(
            pre_add in prop::option::of(arb_path()),
            post_add in prop::option::of(arb_path()),
            pre_remove in prop::option::of(arb_path()),
            post_remove in prop::option::of(arb_path()),
        ) -> HooksFile {
            HooksFile { pre_add, post_add, pre_remove, post_remove }
        }
    }

    prop_compose! {
        fn arb_global_file()(
            roots in prop::collection::vec(arb_path(), 0..3),
            theme in prop::option::of("[a-z]{2,8}"),
            show_upstream in prop::option::of(any::<bool>()),
            prefix in prop::option::of("[a-z]{1,4}"),
            default_base in prop::option::of("[a-z]{2,8}"),
            default_remote in prop::option::of("[a-z]{2,8}"),
        ) -> GlobalConfigFile {
            GlobalConfigFile {
                projects: ProjectsFile { roots },
                ui: UiFile { theme, show_upstream },
                shell: ShellFile { prefix },
                git: GitFile { default_base, default_remote },
            }
        }
    }

    prop_compose! {
        fn arb_template_file()(
            base_branch in prop::option::of("[a-z][a-z0-9-]{0,8}"),
            name_pattern in prop::option::of("[a-z][a-z0-9-]{0,8}"),
            hooks in arb_hooks_file(),
        ) -> TemplateFile {
            TemplateFile { base_branch, name_pattern, hooks }
        }
    }

    prop_compose! {
        fn arb_repo_file()(
            shared in prop::collection::vec(arb_path(), 0..3),
            shared_source in prop::option::of(arb_path()),
            base_dir in prop::option::of(arb_path()),
            templates in prop::collection::btree_map(
                "[a-z][a-z0-9_]{0,8}",
                arb_template_file(),
                0..3,
            ),
            hooks in arb_hooks_file(),
        ) -> RepoConfigFile {
            RepoConfigFile {
                worktrees: WorktreesFile { shared, shared_source, base_dir },
                templates,
                hooks,
            }
        }
    }

    proptest! {
        #[test]
        fn global_file_toml_round_trips(g in arb_global_file()) {
            let s = toml::to_string(&g).expect("serialize");
            let parsed: GlobalConfigFile = toml::from_str(&s).expect("parse");
            prop_assert_eq!(g, parsed);
        }

        #[test]
        fn repo_file_toml_round_trips(r in arb_repo_file()) {
            let s = toml::to_string(&r).expect("serialize");
            let parsed: RepoConfigFile = toml::from_str(&s).expect("parse");
            prop_assert_eq!(r, parsed);
        }
    }
}