git-worktree-manager 0.1.15

Lean git worktree manager with AI coding-assistant integration
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
//! Arrow-key TUI selector for interactive worktree selection.
//!

use std::io::{IsTerminal, Write};

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// Arrow-key selector that renders on stderr and returns selected value.
///
/// # Arguments
/// * `items` - List of (label, value) tuples
/// * `title` - Title shown above the list
/// * `default_index` - Initially highlighted item
///
/// # Returns
/// The value of the selected item, or None if cancelled.
pub fn arrow_select(
    items: &[(String, String)],
    title: &str,
    default_index: usize,
) -> Option<String> {
    if items.is_empty() {
        return None;
    }

    if !std::io::stderr().is_terminal() {
        return None;
    }

    let default_index = default_index.min(items.len() - 1);

    // Try Unix raw-mode selector first
    #[cfg(unix)]
    {
        if let Some(result) = arrow_select_unix(items, title, default_index) {
            return result;
        }
    }

    // Fallback to numbered input
    arrow_select_fallback(items, title, default_index)
}

// ---------------------------------------------------------------------------
// Terminal helpers
// ---------------------------------------------------------------------------

/// Get terminal width from stderr, defaulting to 80.
#[cfg(unix)]
pub(crate) fn get_terminal_width() -> usize {
    console::Term::stderr().size().1 as usize
}

/// Write raw bytes to stderr (unbuffered).
#[cfg(unix)]
pub(crate) fn write_stderr(s: &str) {
    let stderr = std::io::stderr();
    let mut handle = stderr.lock();
    let _ = handle.write_all(s.as_bytes());
    let _ = handle.flush();
}

/// Strip ANSI escape sequences and return the visible display width.
///
/// Iterates over Unicode characters so that multi-byte chars are counted as
/// one unit each (consistent with `truncate`). ANSI CSI sequences of the form
/// `ESC [ ... m` are skipped in their entirety.
#[cfg(any(unix, test))]
pub(crate) fn visible_len(text: &str) -> usize {
    let mut len = 0;
    let mut chars = text.chars().peekable();
    while let Some(ch) = chars.next() {
        if ch == '\x1b' {
            // Skip CSI sequence: ESC [ ... m
            if chars.peek() == Some(&'[') {
                chars.next(); // consume '['
                for c in chars.by_ref() {
                    if c == 'm' {
                        break;
                    }
                }
            }
        } else {
            len += 1;
        }
    }
    len
}

/// Truncate text to fit within `width` visible characters, preserving ANSI codes.
///
/// Uses character (not byte) boundaries so multi-byte Unicode chars count as
/// one visible unit each.
#[cfg(any(unix, test))]
pub(crate) fn truncate(text: &str, width: usize) -> String {
    if visible_len(text) <= width {
        return text.to_string();
    }

    let target = width.saturating_sub(1);
    let mut vis_pos = 0;
    let mut result = String::new();
    let mut chars = text.chars().peekable();

    while let Some(ch) = chars.next() {
        if ch == '\x1b' {
            // Capture and re-emit the CSI sequence verbatim.
            let mut seq = String::from('\x1b');
            if chars.peek() == Some(&'[') {
                seq.push(chars.next().unwrap()); // '['
                for c in chars.by_ref() {
                    seq.push(c);
                    if c == 'm' {
                        break;
                    }
                }
            }
            result.push_str(&seq);
        } else {
            if vis_pos >= target {
                break;
            }
            result.push(ch);
            vis_pos += 1;
        }
    }

    result.push_str("\x1b[0m");
    result
}

// ---------------------------------------------------------------------------
// Rendering
// ---------------------------------------------------------------------------

/// Render the selector list on stderr using ANSI escape codes.
#[cfg(unix)]
fn render(
    items: &[(String, String)],
    title: &str,
    selected: usize,
    _total_lines: usize,
    first_render: bool,
) {
    let width = get_terminal_width();

    if !first_render {
        // Restore cursor to saved position
        write_stderr("\x1b[u");
    }

    // Save cursor position at the start of our render area
    write_stderr("\x1b[s");

    // Title
    let line = format!("  \x1b[1m{title}\x1b[0m");
    write_stderr(&format!("\x1b[2K{}\r\n", truncate(&line, width)));
    // Blank line
    write_stderr("\x1b[2K\r\n");

    for (i, (label, value)) in items.iter().enumerate() {
        write_stderr("\x1b[2K"); // clear line
        let line = if i == selected {
            format!("  \x1b[1;7m > {label} \x1b[0m  \x1b[2m{value}\x1b[0m")
        } else {
            format!("    {label}  \x1b[2m{value}\x1b[0m")
        };
        write_stderr(&format!("{}\r\n", truncate(&line, width)));
    }

    // Clear any leftover lines below
    for _ in 0..2 {
        write_stderr("\x1b[2K\r\n");
    }
    // Move back up to just after our items
    write_stderr("\x1b[2A");
}

/// Erase the rendered selector from stderr.
#[cfg(unix)]
pub(crate) fn cleanup(total_lines: usize) {
    // Restore to saved position
    write_stderr("\x1b[u");
    for _ in 0..total_lines + 2 {
        write_stderr("\x1b[2K\r\n");
    }
    write_stderr("\x1b[u");
}

// ---------------------------------------------------------------------------
// Key reading
// ---------------------------------------------------------------------------

/// Recognized key events.
#[cfg(unix)]
#[derive(Debug, PartialEq)]
pub(crate) enum Key {
    Up,
    Down,
    Enter,
    Escape,
    CtrlC,
    Quit,
    Space,
    Number(u8),
    Unknown,
}

/// Read a single keypress from the given file descriptor (Unix).
#[cfg(unix)]
pub(crate) fn read_key(fd: std::os::unix::io::RawFd) -> Result<Key, std::io::Error> {
    let mut buf = [0u8; 1];
    let n = unsafe { libc::read(fd, buf.as_mut_ptr() as *mut libc::c_void, 1) };
    if n <= 0 {
        return Err(std::io::Error::new(
            std::io::ErrorKind::UnexpectedEof,
            "EOF on stdin",
        ));
    }

    match buf[0] {
        b'\x1b' => {
            // Could be escape sequence -- peek with a short timeout using select/poll
            let mut pollfd = libc::pollfd {
                fd,
                events: libc::POLLIN,
                revents: 0,
            };
            let ready = unsafe { libc::poll(&mut pollfd as *mut libc::pollfd, 1, 50) };
            if ready <= 0 {
                // Bare Escape key
                return Ok(Key::Escape);
            }
            let mut seq1 = [0u8; 1];
            let n = unsafe { libc::read(fd, seq1.as_mut_ptr() as *mut libc::c_void, 1) };
            if n <= 0 {
                return Ok(Key::Escape);
            }
            if seq1[0] == b'[' {
                let mut seq2 = [0u8; 1];
                let n = unsafe { libc::read(fd, seq2.as_mut_ptr() as *mut libc::c_void, 1) };
                if n <= 0 {
                    return Ok(Key::Unknown);
                }
                match seq2[0] {
                    b'A' => Ok(Key::Up),
                    b'B' => Ok(Key::Down),
                    _ => Ok(Key::Unknown),
                }
            } else {
                Ok(Key::Unknown)
            }
        }
        b'\r' | b'\n' => Ok(Key::Enter),
        0x03 => Ok(Key::CtrlC),
        b'q' => Ok(Key::Quit),
        b' ' => Ok(Key::Space),
        c @ b'1'..=b'9' => Ok(Key::Number(c - b'0')),
        _ => Ok(Key::Unknown),
    }
}

// ---------------------------------------------------------------------------
// Unix raw-mode selector
// ---------------------------------------------------------------------------

#[cfg(unix)]
fn arrow_select_unix(
    items: &[(String, String)],
    title: &str,
    default_index: usize,
) -> Option<Option<String>> {
    use std::os::unix::io::AsRawFd;

    let stdin = std::io::stdin();
    let fd = stdin.as_raw_fd();

    let _guard = super::raw_mode::RawModeGuard::enter(fd, true)?;

    let mut selected = default_index;
    let total_lines = items.len() + 2; // title + blank + items

    render(items, title, selected, total_lines, true);

    let result: Option<String> = loop {
        let key = match read_key(fd) {
            Ok(k) => k,
            Err(_) => break None,
        };

        match key {
            Key::Enter => break Some(items[selected].1.clone()),
            Key::CtrlC | Key::Quit | Key::Escape => break None,
            Key::Up => {
                selected = if selected == 0 {
                    items.len() - 1
                } else {
                    selected - 1
                };
                render(items, title, selected, total_lines, false);
            }
            Key::Down => {
                selected = (selected + 1) % items.len();
                render(items, title, selected, total_lines, false);
            }
            Key::Number(n) => {
                let idx = (n as usize) - 1;
                if idx < items.len() {
                    break Some(items[idx].1.clone());
                }
            }
            _ => {}
        }
    };

    // Clear our drawn lines; terminal mode is restored by `_guard` on drop.
    cleanup(total_lines);

    Some(result)
}

// ---------------------------------------------------------------------------
// Fallback: numbered list
// ---------------------------------------------------------------------------

/// Fallback numbered list with text input.
fn arrow_select_fallback(
    items: &[(String, String)],
    title: &str,
    default_index: usize,
) -> Option<String> {
    let stderr = std::io::stderr();
    let mut out = stderr.lock();

    let _ = writeln!(out, "\n  {title}\n");
    for (i, (label, value)) in items.iter().enumerate() {
        let marker = if i == default_index { ">" } else { " " };
        let _ = writeln!(out, "  {marker} [{num}] {label}  {value}", num = i + 1);
    }
    let _ = writeln!(out);
    let _ = write!(out, "Select [1-{}]: ", items.len());
    let _ = out.flush();

    let mut input = String::new();
    match std::io::stdin().read_line(&mut input) {
        Ok(_) => {
            let input = input.trim();
            if input.is_empty() {
                return Some(items[default_index].1.clone());
            }
            if let Ok(n) = input.parse::<usize>() {
                let idx = n.wrapping_sub(1);
                if idx < items.len() {
                    return Some(items[idx].1.clone());
                }
            }
            None
        }
        Err(_) => None,
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn test_visible_len_plain_text() {
        assert_eq!(visible_len("hello"), 5);
        assert_eq!(visible_len(""), 0);
        assert_eq!(visible_len("abc def"), 7);
    }

    #[test]
    fn test_visible_len_with_ansi() {
        assert_eq!(visible_len("\x1b[1mhello\x1b[0m"), 5);
        assert_eq!(
            visible_len("\x1b[1;7m > foo \x1b[0m  \x1b[2mbar\x1b[0m"),
            12
        );
        assert_eq!(visible_len("\x1b[32m\x1b[0m"), 0);
    }

    #[test]
    fn test_truncate_no_truncation_needed() {
        let text = "short";
        assert_eq!(truncate(text, 80), "short");
    }

    #[test]
    fn test_truncate_plain_text() {
        let text = "hello world this is a long string";
        let result = truncate(text, 10);
        // Should be at most 9 visible chars + reset
        assert!(visible_len(&result) <= 10);
        assert!(result.ends_with("\x1b[0m"));
    }

    #[test]
    fn test_truncate_with_ansi() {
        let text = "\x1b[1mhello world long text\x1b[0m";
        let result = truncate(text, 10);
        assert!(visible_len(&result) <= 10);
        assert!(result.ends_with("\x1b[0m"));
    }

    #[test]
    fn test_truncate_width_one() {
        let result = truncate("hello", 1);
        // With width=1, saturating_sub(1) = 0, so no visible chars
        assert!(result.ends_with("\x1b[0m"));
    }

    #[test]
    fn test_arrow_select_empty_items() {
        assert_eq!(arrow_select(&[], "title", 0), None);
    }

    #[cfg(unix)]
    #[test]
    fn test_key_enum_equality() {
        assert_eq!(Key::Up, Key::Up);
        assert_eq!(Key::Number(3), Key::Number(3));
        assert_ne!(Key::Up, Key::Down);
    }

    #[test]
    fn test_fallback_default_index_clamped() {
        let items = [
            ("a".to_string(), "val_a".to_string()),
            ("b".to_string(), "val_b".to_string()),
        ];
        let clamped = 10usize.min(items.len() - 1);
        assert_eq!(clamped, 1);
    }
}