kono-wt 1.8.0

A single-binary CLI + TUI for managing Git worktrees and their GitHub pull requests.
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
//! Post-create and pre-remove hooks (spec ยง8), and the `--start` command
//! (issue #89). All three run via `sh -c` (Unix) or `cmd /C` (Windows) with the
//! worktree as the working directory and the `WT_*` variables in the environment.
//!
//! Execution policy differs per caller: a failed `post_create` is a non-fatal
//! warning; a failed `pre_remove` aborts the removal unless `--force` (then it is
//! a warning); a failed `--start` command propagates its exit code, since it is
//! the user's foreground command rather than a side effect of `wt`'s own work.

use std::path::PathBuf;
use std::process::Command;

use crate::cx::Cx;
use crate::error::{Error, Result};

/// The context passed to a hook as `WT_*` environment variables.
#[derive(Debug, Clone)]
pub struct HookContext {
    /// `WT_WORKTREE_PATH` and the working directory for the hook.
    pub worktree_path: PathBuf,
    /// `WT_BRANCH`.
    pub branch: String,
    /// `WT_REPO_ROOT`.
    pub repo_root: PathBuf,
    /// `WT_BASE_REF` (set only when known).
    pub base_ref: Option<String>,
    /// `WT_PR_NUMBER` (set only for PR-originated worktrees).
    pub pr_number: Option<u64>,
}

/// Runs hook commands. Abstracted so tests can inject a fake.
pub trait HookRunner {
    /// Runs `command` with the hook context, returning its exit code.
    fn run(&self, command: &str, ctx: &HookContext) -> Result<i32>;
}

/// Builds the shell [`Command`] for a hook: `sh -c` (Unix) / `cmd /C` (Windows),
/// run in the worktree directory with the `WT_*` variables set. Shared by both
/// runners so they differ only in how the child's stdio is handled.
fn build_hook_command(command: &str, ctx: &HookContext) -> Command {
    let mut cmd = if cfg!(windows) {
        let mut c = Command::new("cmd");
        c.args(["/C", command]);
        c
    } else {
        let mut c = Command::new("sh");
        c.args(["-c", command]);
        c
    };
    cmd.current_dir(&ctx.worktree_path);
    cmd.env("WT_WORKTREE_PATH", &ctx.worktree_path);
    cmd.env("WT_BRANCH", &ctx.branch);
    cmd.env("WT_REPO_ROOT", &ctx.repo_root);
    if let Some(base) = &ctx.base_ref {
        cmd.env("WT_BASE_REF", base);
    }
    if let Some(pr) = ctx.pr_number {
        cmd.env("WT_PR_NUMBER", pr.to_string());
    }
    cmd
}

/// The production [`HookRunner`] that spawns a shell and lets the hook inherit
/// the terminal's stdio (so output is visible to the user on the CLI paths,
/// which suspend the TUI first).
#[derive(Debug, Clone, Copy, Default)]
pub struct RealHookRunner;

impl HookRunner for RealHookRunner {
    fn run(&self, command: &str, ctx: &HookContext) -> Result<i32> {
        let status = build_hook_command(command, ctx)
            .status()
            .map_err(|e| Error::operation(format!("failed to run hook: {e}")))?;
        Ok(status.code().unwrap_or(-1))
    }
}

/// A [`HookRunner`] that captures the hook's stdout/stderr instead of inheriting
/// the terminal. Used by the TUI's background jobs (issue #46), which keep the
/// alternate screen up and animate a spinner โ€” inherited hook output would
/// otherwise paint over the rendered UI. Behaviorally identical to
/// [`RealHookRunner`] except the captured output is discarded.
#[derive(Debug, Clone, Copy, Default)]
pub struct CapturingHookRunner;

impl HookRunner for CapturingHookRunner {
    fn run(&self, command: &str, ctx: &HookContext) -> Result<i32> {
        let output = build_hook_command(command, ctx)
            .output()
            .map_err(|e| Error::operation(format!("failed to run hook: {e}")))?;
        Ok(output.status.code().unwrap_or(-1))
    }
}

/// Runs the `post_create` hook (spec ยง8). A non-zero exit (or run failure) is a
/// non-fatal warning. `no_hooks` or an absent command is a no-op.
pub fn run_post_create(
    runner: &dyn HookRunner,
    cx: &mut Cx,
    command: Option<&str>,
    ctx: &HookContext,
    no_hooks: bool,
) -> Result<()> {
    if no_hooks {
        return Ok(());
    }
    let Some(command) = command else {
        return Ok(());
    };
    match runner.run(command, ctx) {
        Ok(0) => Ok(()),
        Ok(code) => {
            cx.err.line(&format!(
                "warning: post_create hook exited with status {code}"
            ))?;
            Ok(())
        }
        Err(e) => {
            cx.err
                .line(&format!("warning: post_create hook failed: {e}"))?;
            Ok(())
        }
    }
}

/// Runs the `--start` command in `ctx.worktree_path`, returning its exit status
/// as a process exit code (issue #89).
///
/// Unlike [`run_post_create`], the status is propagated rather than downgraded to
/// a warning: `--start` is the user's own foreground command, so `wt` exits with
/// whatever it exited with, the way `sh -c` does. A status that does not fit in a
/// `u8` โ€” notably death by signal, which [`HookRunner::run`] reports as `-1` โ€”
/// becomes `1`.
pub fn run_start(runner: &dyn HookRunner, command: &str, ctx: &HookContext) -> Result<u8> {
    let code = runner.run(command, ctx)?;
    Ok(u8::try_from(code).unwrap_or(1))
}

/// Runs the `pre_remove` hook (spec ยง8). A non-zero exit aborts the removal
/// unless `force` is set, in which case it is reported as a warning and removal
/// proceeds. `no_hooks` or an absent command is a no-op.
pub fn run_pre_remove(
    runner: &dyn HookRunner,
    cx: &mut Cx,
    command: Option<&str>,
    ctx: &HookContext,
    no_hooks: bool,
    force: bool,
) -> Result<()> {
    if no_hooks {
        return Ok(());
    }
    let Some(command) = command else {
        return Ok(());
    };
    match runner.run(command, ctx) {
        Ok(0) => Ok(()),
        Ok(code) if force => {
            cx.err.line(&format!(
                "warning: pre_remove hook exited with status {code}; proceeding due to --force"
            ))?;
            Ok(())
        }
        Ok(code) => Err(Error::operation(format!(
            "pre_remove hook exited with status {code}; aborting (use --force to override)"
        ))),
        Err(e) if force => {
            cx.err.line(&format!(
                "warning: pre_remove hook failed: {e}; proceeding due to --force"
            ))?;
            Ok(())
        }
        Err(e) => Err(e),
    }
}

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

    fn ctx(dir: &std::path::Path) -> HookContext {
        HookContext {
            worktree_path: dir.to_path_buf(),
            branch: "feature/x".into(),
            repo_root: dir.to_path_buf(),
            base_ref: Some("main".into()),
            pr_number: None,
        }
    }

    /// A fake runner returning a fixed code and recording the command.
    struct FakeRunner {
        code: i32,
        last: Mutex<Option<String>>,
    }
    impl HookRunner for FakeRunner {
        fn run(&self, command: &str, _ctx: &HookContext) -> Result<i32> {
            *self.last.lock().unwrap() = Some(command.to_string());
            Ok(self.code)
        }
    }

    /// `--start` runs in the worktree with the `WT_*` variables set, exactly like
    /// a hook, and its exit code becomes `wt`'s.
    #[test]
    fn run_start_executes_in_the_worktree_and_propagates_the_exit_code() {
        let dir = tempfile::tempdir().unwrap();
        let code = run_start(
            &RealHookRunner,
            "pwd > where.txt && printf '%s' \"$WT_BRANCH\" > branch.txt",
            &ctx(dir.path()),
        )
        .unwrap();
        assert_eq!(code, 0);
        assert_eq!(
            std::fs::read_to_string(dir.path().join("branch.txt")).unwrap(),
            "feature/x"
        );
        let where_ran = std::fs::read_to_string(dir.path().join("where.txt")).unwrap();
        // `pwd` may resolve /var -> /private/var on macOS; compare canonical forms.
        assert_eq!(
            std::fs::canonicalize(where_ran.trim()).unwrap(),
            std::fs::canonicalize(dir.path()).unwrap()
        );

        assert_eq!(
            run_start(&RealHookRunner, "exit 3", &ctx(dir.path())).unwrap(),
            3
        );
    }

    /// A signal death is reported as `-1`, which cannot be an exit code.
    #[test]
    fn run_start_maps_an_unrepresentable_status_to_one() {
        let runner = FakeRunner {
            code: -1,
            last: Mutex::new(None),
        };
        let dir = tempfile::tempdir().unwrap();
        assert_eq!(run_start(&runner, "whatever", &ctx(dir.path())).unwrap(), 1);
    }

    #[test]
    fn real_runner_sets_wt_env_and_returns_code() {
        let dir = tempfile::tempdir().unwrap();
        // post_create-style: write the environment to a file.
        let code = RealHookRunner
            .run("env | grep '^WT_' > wt_env.txt", &ctx(dir.path()))
            .unwrap();
        assert_eq!(code, 0);
        let env = std::fs::read_to_string(dir.path().join("wt_env.txt")).unwrap();
        assert!(env.contains("WT_BRANCH=feature/x"));
        assert!(env.contains("WT_REPO_ROOT="));
        assert!(env.contains("WT_BASE_REF=main"));
        assert!(env.contains("WT_WORKTREE_PATH="));
        // WT_PR_NUMBER is unset when there is no PR.
        assert!(!env.contains("WT_PR_NUMBER"));
    }

    #[test]
    fn capturing_runner_sets_wt_env_and_returns_code() {
        let dir = tempfile::tempdir().unwrap();
        let code = CapturingHookRunner
            .run("env | grep '^WT_' > wt_env.txt", &ctx(dir.path()))
            .unwrap();
        assert_eq!(code, 0);
        let env = std::fs::read_to_string(dir.path().join("wt_env.txt")).unwrap();
        assert!(env.contains("WT_BRANCH=feature/x"));
        assert!(env.contains("WT_REPO_ROOT="));
        assert!(env.contains("WT_BASE_REF=main"));
        assert!(env.contains("WT_WORKTREE_PATH="));
    }

    #[test]
    fn capturing_runner_captures_output_and_propagates_exit() {
        let dir = tempfile::tempdir().unwrap();
        // The hook writes to stdout (captured, not inherited) and exits non-zero;
        // the captured output is discarded but the exit code is returned.
        let code = CapturingHookRunner
            .run("echo noise; exit 4", &ctx(dir.path()))
            .unwrap();
        assert_eq!(code, 4);
    }

    #[test]
    fn real_runner_sets_pr_number_when_present() {
        let dir = tempfile::tempdir().unwrap();
        let mut c = ctx(dir.path());
        c.pr_number = Some(123);
        RealHookRunner
            .run("printenv WT_PR_NUMBER > pr.txt", &c)
            .unwrap();
        assert_eq!(
            std::fs::read_to_string(dir.path().join("pr.txt"))
                .unwrap()
                .trim(),
            "123"
        );
    }

    #[test]
    fn real_runner_propagates_nonzero_exit() {
        let dir = tempfile::tempdir().unwrap();
        assert_eq!(RealHookRunner.run("exit 3", &ctx(dir.path())).unwrap(), 3);
    }

    #[test]
    fn post_create_failure_is_a_warning() {
        let dir = tempfile::tempdir().unwrap();
        let runner = FakeRunner {
            code: 1,
            last: Mutex::new(None),
        };
        let mut t = crate::testutil::test_cx(&[], "/tmp");
        run_post_create(
            &runner,
            &mut t.cx,
            Some("do-thing"),
            &ctx(dir.path()),
            false,
        )
        .unwrap();
        assert!(
            t.err
                .contents()
                .contains("warning: post_create hook exited with status 1")
        );
    }

    #[test]
    fn post_create_skipped_when_no_hooks_or_absent() {
        let dir = tempfile::tempdir().unwrap();
        let runner = FakeRunner {
            code: 1,
            last: Mutex::new(None),
        };
        let mut t = crate::testutil::test_cx(&[], "/tmp");
        run_post_create(&runner, &mut t.cx, Some("x"), &ctx(dir.path()), true).unwrap();
        run_post_create(&runner, &mut t.cx, None, &ctx(dir.path()), false).unwrap();
        assert!(runner.last.lock().unwrap().is_none());
        assert!(t.err.contents().is_empty());
    }

    #[test]
    fn pre_remove_failure_aborts_without_force() {
        let dir = tempfile::tempdir().unwrap();
        let runner = FakeRunner {
            code: 2,
            last: Mutex::new(None),
        };
        let mut t = crate::testutil::test_cx(&[], "/tmp");
        let err = run_pre_remove(
            &runner,
            &mut t.cx,
            Some("guard"),
            &ctx(dir.path()),
            false,
            false,
        )
        .unwrap_err();
        assert_eq!(err.exit_code(), 1);
    }

    #[test]
    fn pre_remove_failure_warns_and_proceeds_with_force() {
        let dir = tempfile::tempdir().unwrap();
        let runner = FakeRunner {
            code: 2,
            last: Mutex::new(None),
        };
        let mut t = crate::testutil::test_cx(&[], "/tmp");
        run_pre_remove(
            &runner,
            &mut t.cx,
            Some("guard"),
            &ctx(dir.path()),
            false,
            true,
        )
        .unwrap();
        assert!(t.err.contents().contains("proceeding due to --force"));
    }

    #[test]
    fn pre_remove_success_proceeds() {
        let dir = tempfile::tempdir().unwrap();
        let runner = FakeRunner {
            code: 0,
            last: Mutex::new(None),
        };
        let mut t = crate::testutil::test_cx(&[], "/tmp");
        run_pre_remove(
            &runner,
            &mut t.cx,
            Some("guard"),
            &ctx(dir.path()),
            false,
            false,
        )
        .unwrap();
        assert_eq!(runner.last.lock().unwrap().as_deref(), Some("guard"));
    }
}