ofsht 0.6.0

Git worktree management tool
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
#![allow(clippy::missing_errors_doc)]
#![allow(clippy::must_use_candidate)]
use anyhow::{Context, Result};
use std::io::Write;
use std::path::PathBuf;
use std::process::{Command, Stdio};

use crate::domain::worktree::{
    calculate_relative_path, calculate_worktree_root_from_paths, display_path,
};

/// Item to display in fzf
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FzfItem {
    /// Text to display in fzf
    pub display: String,
    /// Actual value to return when selected
    pub value: String,
}

/// Fzf picker interface
pub trait FzfPicker {
    fn pick(&self, items: &[FzfItem], multi: bool) -> Result<Vec<String>>;
}

/// Real fzf implementation
#[derive(Debug)]
pub struct RealFzfPicker {
    extra_options: Vec<String>,
}

impl RealFzfPicker {
    pub const fn new(extra_options: Vec<String>) -> Self {
        Self { extra_options }
    }
}

impl FzfPicker for RealFzfPicker {
    fn pick(&self, items: &[FzfItem], multi: bool) -> Result<Vec<String>> {
        if items.is_empty() {
            return Ok(Vec::new());
        }

        // Build input for fzf (display strings)
        let input = items
            .iter()
            .map(|item| item.display.clone())
            .collect::<Vec<_>>()
            .join("\n");

        // Build fzf command
        let mut cmd = Command::new("fzf");

        // Add multi-select if requested
        if multi {
            cmd.arg("--multi");
        }

        // Add extra options from config
        for opt in &self.extra_options {
            cmd.arg(opt);
        }

        // Add preview command to show git log for each worktree
        // Extract the last field (path) and expand ~ to $HOME
        // Use % as placeholder to avoid conflicts with fzf's {}
        let preview_cmd =
            "echo {} | awk '{print $NF}' | sed \"s|^~|$HOME|\" | xargs -I % git -C % log --oneline -n 10 2>/dev/null";
        cmd.arg("--preview").arg(preview_cmd);

        // Add some default options for better UX
        cmd.arg("--height=50%")
            .arg("--reverse")
            .arg("--border")
            .arg("--prompt=Select worktree: ");

        // Execute fzf with stdin
        cmd.stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::inherit()); // fzf draws TUI directly to terminal

        let mut child = cmd.spawn().context("Failed to spawn fzf")?;

        // Write input to stdin
        if let Some(mut stdin) = child.stdin.take() {
            stdin
                .write_all(input.as_bytes())
                .context("Failed to write to fzf stdin")?;
            stdin.flush().context("Failed to flush fzf stdin")?;
            // stdin is dropped here and EOF is sent
        }

        let output = child.wait_with_output().context("Failed to wait for fzf")?;

        // Handle exit codes
        match output.status.code() {
            Some(0) => {
                // Success - parse selected items
                let stdout = String::from_utf8_lossy(&output.stdout);
                let selected_displays: Vec<&str> = stdout.lines().collect();

                // Map selected display strings back to values
                let mut results = Vec::new();
                for display in selected_displays {
                    if let Some(item) = items.iter().find(|item| item.display == display) {
                        results.push(item.value.clone());
                    }
                }

                Ok(results)
            }
            Some(130 | 1) => {
                // User pressed Esc or no selection - not an error
                Ok(Vec::new())
            }
            Some(code) => {
                let stderr = String::from_utf8_lossy(&output.stderr);
                anyhow::bail!("fzf exited with code {code}: {stderr}")
            }
            None => {
                anyhow::bail!("fzf was terminated by signal")
            }
        }
    }
}

/// Check if fzf is available in the system
pub fn is_fzf_available() -> bool {
    Command::new("fzf")
        .arg("--version")
        .output()
        .is_ok_and(|output| output.status.success())
}

/// Intermediate parsed worktree entry for fzf display
struct ParsedWorktree {
    path: String,
    branch: Option<String>,
}

/// Build worktree items from git worktree list --porcelain output
///
/// Display format: `{name} · {branch} · {path}`
/// - Index 0 is the main worktree (displayed as `@`)
/// - Non-main worktrees show their relative path from the worktree root
/// - Columns are padded for alignment (except the last column)
pub fn build_worktree_items(porcelain_output: &str) -> Vec<FzfItem> {
    // Pass 1: Parse porcelain output into intermediate entries
    let mut entries = Vec::new();
    let mut current_path: Option<String> = None;
    let mut current_branch: Option<String> = None;

    for line in porcelain_output.lines() {
        let line = line.trim();
        if line.is_empty() {
            if let Some(path) = current_path.take() {
                entries.push(ParsedWorktree {
                    path,
                    branch: current_branch.take(),
                });
            }
            continue;
        }

        if let Some(path) = line.strip_prefix("worktree ") {
            current_path = Some(path.to_string());
        } else if let Some(branch_ref) = line.strip_prefix("branch ") {
            if let Some(branch_name) = branch_ref.strip_prefix("refs/heads/") {
                current_branch = Some(branch_name.to_string());
            }
        } else if line == "detached" {
            current_branch = None;
        }
    }

    // Handle last entry if output doesn't end with empty line
    if let Some(path) = current_path {
        entries.push(ParsedWorktree {
            path,
            branch: current_branch,
        });
    }

    if entries.is_empty() {
        return Vec::new();
    }

    // Calculate worktree root from non-main paths
    let non_main_paths: Vec<PathBuf> = entries
        .iter()
        .skip(1)
        .map(|e| PathBuf::from(&e.path))
        .collect();
    let worktree_root = calculate_worktree_root_from_paths(&non_main_paths);

    // Build name, branch, display_path for each entry
    let display_entries: Vec<(String, String, String)> = entries
        .iter()
        .enumerate()
        .map(|(index, entry)| {
            let name = if index == 0 {
                "@".to_string()
            } else {
                worktree_root
                    .as_ref()
                    .and_then(|root| calculate_relative_path(&PathBuf::from(&entry.path), root))
                    .unwrap_or_else(|| {
                        // Fallback: use directory name
                        PathBuf::from(&entry.path)
                            .file_name()
                            .map_or_else(|| entry.path.clone(), |n| n.to_string_lossy().to_string())
                    })
            };

            let branch = if index == 0 {
                "[@]".to_string()
            } else {
                entry
                    .branch
                    .as_deref()
                    .map_or_else(|| "[detached]".to_string(), |b| format!("[{b}]"))
            };

            let path = display_path(&PathBuf::from(&entry.path));

            (name, branch, path)
        })
        .collect();

    // Pass 2: Calculate column widths and format display strings
    let max_name_width = display_entries
        .iter()
        .map(|(n, _, _)| n.len())
        .max()
        .unwrap_or(0);
    let max_branch_width = display_entries
        .iter()
        .map(|(_, b, _)| b.len())
        .max()
        .unwrap_or(0);

    display_entries
        .into_iter()
        .zip(entries.iter())
        .map(|((name, branch, path), entry)| {
            let name_padding = " ".repeat(max_name_width.saturating_sub(name.len()));
            let branch_padding = " ".repeat(max_branch_width.saturating_sub(branch.len()));

            // Last column (path) has no padding to avoid trailing whitespace
            let display = format!("{name}{name_padding} · {branch}{branch_padding} · {path}");

            FzfItem {
                display,
                value: entry.path.clone(),
            }
        })
        .collect()
}

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

    struct MockFzfPicker {
        return_values: Vec<String>,
        should_fail: bool,
    }

    impl FzfPicker for MockFzfPicker {
        fn pick(&self, _items: &[FzfItem], _multi: bool) -> Result<Vec<String>> {
            if self.should_fail {
                anyhow::bail!("Mock fzf failure");
            }
            Ok(self.return_values.clone())
        }
    }

    #[test]
    fn test_fzf_item_creation() {
        let item = FzfItem {
            display: "feature · feat/new · /path/to/worktree".to_string(),
            value: "/path/to/worktree".to_string(),
        };
        assert_eq!(item.display, "feature · feat/new · /path/to/worktree");
        assert_eq!(item.value, "/path/to/worktree");
    }

    #[test]
    fn test_mock_fzf_picker_success() {
        let picker = MockFzfPicker {
            return_values: vec!["/path/to/worktree".to_string()],
            should_fail: false,
        };
        let items = vec![FzfItem {
            display: "test".to_string(),
            value: "/path/to/worktree".to_string(),
        }];
        let result = picker.pick(&items, false);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), vec!["/path/to/worktree"]);
    }

    #[test]
    fn test_mock_fzf_picker_failure() {
        let picker = MockFzfPicker {
            return_values: Vec::new(),
            should_fail: true,
        };
        let items = vec![FzfItem {
            display: "test".to_string(),
            value: "/test".to_string(),
        }];
        let result = picker.pick(&items, false);
        assert!(result.is_err());
    }

    #[test]
    fn test_mock_fzf_picker_cancel() {
        // User pressing Esc should return empty vec
        let picker = MockFzfPicker {
            return_values: Vec::new(),
            should_fail: false,
        };
        let items = vec![FzfItem {
            display: "test".to_string(),
            value: "/test".to_string(),
        }];
        let result = picker.pick(&items, false);
        assert!(result.is_ok());
        assert!(result.unwrap().is_empty());
    }

    #[test]
    fn test_is_fzf_available() {
        // This test will pass or fail depending on whether fzf is installed
        // We're just checking that the function doesn't panic
        let _ = is_fzf_available();
    }

    #[test]
    fn test_build_worktree_items_basic() {
        let porcelain = r"worktree /path/to/main
HEAD abc123
branch refs/heads/main

worktree /path/to/feature
HEAD def456
branch refs/heads/feature-branch

";
        let items = build_worktree_items(porcelain);
        assert_eq!(items.len(), 2);

        // First item: main worktree displayed as "@" with [@] branch
        assert_eq!(items[0].value, "/path/to/main");
        assert!(items[0].display.starts_with('@'));
        assert!(items[0].display.contains(" · [@]"));
        assert!(items[0].display.contains(" · /path/to/main"));

        // Second item: feature branch with name and [branch]
        assert_eq!(items[1].value, "/path/to/feature");
        assert!(items[1].display.contains("feature"));
        assert!(items[1].display.contains(" · [feature-branch]"));
        assert!(items[1].display.contains(" · /path/to/feature"));
    }

    #[test]
    fn test_build_worktree_items_detached() {
        let porcelain = r"worktree /path/to/main
HEAD abc123
branch refs/heads/main

worktree /path/to/detached
HEAD def456
detached

";
        let items = build_worktree_items(porcelain);
        assert_eq!(items.len(), 2);
        assert_eq!(items[1].value, "/path/to/detached");
        assert!(items[1].display.contains("detached"));
        assert!(items[1].display.contains(" · [detached]"));
    }

    #[test]
    fn test_build_worktree_items_single_main_only() {
        let porcelain = r"worktree /path/to/main
HEAD abc123
branch refs/heads/main

";
        let items = build_worktree_items(porcelain);
        assert_eq!(items.len(), 1);
        assert_eq!(items[0].value, "/path/to/main");
        assert!(items[0].display.starts_with('@'));
        assert!(items[0].display.contains(" · [@]"));
    }

    #[test]
    fn test_build_worktree_items_nested_branch() {
        let porcelain = r"worktree /path/to/main
HEAD abc123
branch refs/heads/main

worktree /worktrees/feat/foo
HEAD def456
branch refs/heads/feat/foo

worktree /worktrees/fix/bar
HEAD ghi789
branch refs/heads/fix/bar

";
        let items = build_worktree_items(porcelain);
        assert_eq!(items.len(), 3);

        // Nested worktree names should use relative path from root
        assert_eq!(items[1].value, "/worktrees/feat/foo");
        assert!(items[1].display.contains("feat/foo"));
        assert!(items[1].display.contains(" · [feat/foo]"));

        assert_eq!(items[2].value, "/worktrees/fix/bar");
        assert!(items[2].display.contains(" · [fix/bar]"));
    }

    #[test]
    fn test_build_worktree_items_padding_alignment() {
        let porcelain = r"worktree /path/to/main
HEAD abc123
branch refs/heads/main

worktree /worktrees/a
HEAD def456
branch refs/heads/short

worktree /worktrees/long-name
HEAD ghi789
branch refs/heads/very-long-branch-name

";
        let items = build_worktree_items(porcelain);
        assert_eq!(items.len(), 3);

        // All "·" separators should be at the same column positions
        let first_sep_positions: Vec<usize> = items
            .iter()
            .map(|item| item.display.find(" · ").unwrap())
            .collect();
        assert!(
            first_sep_positions.windows(2).all(|w| w[0] == w[1]),
            "First separator positions should be aligned: {first_sep_positions:?}"
        );

        // Find second separator positions
        let second_sep_positions: Vec<usize> = items
            .iter()
            .map(|item| {
                let after_first = first_sep_positions[0] + 3;
                after_first + item.display[after_first..].find(" · ").unwrap()
            })
            .collect();
        assert!(
            second_sep_positions.windows(2).all(|w| w[0] == w[1]),
            "Second separator positions should be aligned: {second_sep_positions:?}"
        );
    }

    #[test]
    fn test_build_worktree_items_no_trailing_whitespace() {
        let porcelain = r"worktree /path/to/main
HEAD abc123
branch refs/heads/main

worktree /worktrees/feature
HEAD def456
branch refs/heads/feature-branch

";
        let items = build_worktree_items(porcelain);
        for item in &items {
            assert_eq!(
                item.display,
                item.display.trim_end(),
                "Display should not have trailing whitespace: {:?}",
                item.display
            );
        }
    }
}