rft-cli 0.6.0

Zero-config Docker Compose isolation for git worktrees
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
use std::path::{Path, PathBuf};

use tokio::process::Command;

use crate::error::{Result, RftError};

#[derive(Debug, Clone)]
pub struct WorktreeInfo {
    pub path: PathBuf,
    pub branch: String,
    pub is_main: bool,
    pub index: usize,
}

impl WorktreeInfo {
    pub fn dir_name(&self) -> String {
        self.path
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_else(|| self.branch.clone())
    }

    pub fn project_label(&self, source: &crate::config::ProjectNameSource) -> String {
        match source {
            crate::config::ProjectNameSource::Directory => self.dir_name(),
            crate::config::ProjectNameSource::Branch => self.branch.clone(),
        }
    }
}

#[derive(Debug, Clone)]
pub struct RepoIdentity {
    pub working_root: PathBuf,
    pub project_name: String,
}

pub async fn resolve_repo_identity(cwd: &Path) -> Result<RepoIdentity> {
    let common_dir = get_git_common_dir(cwd).await?;
    let project_name = project_name_from_common_dir(&common_dir);

    let working_root = match try_show_toplevel(cwd).await {
        Some(root) => root,
        None => find_main_worktree_path(cwd).await?,
    };

    Ok(RepoIdentity {
        working_root,
        project_name,
    })
}

async fn get_git_common_dir(cwd: &Path) -> Result<PathBuf> {
    let output = Command::new("git")
        .args(["rev-parse", "--git-common-dir"])
        .current_dir(cwd)
        .output()
        .await?;

    if !output.status.success() {
        return Err(RftError::NotAGitRepo);
    }

    let raw = String::from_utf8_lossy(&output.stdout).trim().to_string();
    let path = PathBuf::from(&raw);

    if path.is_absolute() {
        Ok(path)
    } else {
        Ok(cwd
            .join(&path)
            .canonicalize()
            .unwrap_or_else(|_| cwd.join(&path)))
    }
}

fn project_name_from_common_dir(common_dir: &Path) -> String {
    let Some(dir_name) = common_dir.file_name() else {
        return "unknown".to_string();
    };
    let dir_name = dir_name.to_string_lossy();

    if dir_name.starts_with('.') {
        common_dir
            .parent()
            .and_then(|p| p.file_name())
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_else(|| "unknown".to_string())
    } else {
        dir_name.into_owned()
    }
}

async fn try_show_toplevel(cwd: &Path) -> Option<PathBuf> {
    let output = Command::new("git")
        .args(["rev-parse", "--show-toplevel"])
        .current_dir(cwd)
        .output()
        .await
        .ok()?;

    if !output.status.success() {
        return None;
    }

    let root = String::from_utf8_lossy(&output.stdout).trim().to_string();
    Some(PathBuf::from(root))
}

async fn find_main_worktree_path(cwd: &Path) -> Result<PathBuf> {
    let output = Command::new("git")
        .args(["worktree", "list", "--porcelain"])
        .current_dir(cwd)
        .output()
        .await?;

    if !output.status.success() {
        return Err(RftError::NotAGitRepo);
    }

    let raw = String::from_utf8_lossy(&output.stdout);
    let worktrees = parse_porcelain_output(&raw, None)?;

    worktrees
        .iter()
        .find(|wt| wt.is_main)
        .or_else(|| worktrees.first())
        .map(|wt| wt.path.clone())
        .ok_or(RftError::NoMainWorktree)
}

pub async fn get_worktrees(
    repo_root: &Path,
    main_branch: Option<&str>,
) -> Result<Vec<WorktreeInfo>> {
    let output = Command::new("git")
        .args(["worktree", "list", "--porcelain"])
        .current_dir(repo_root)
        .output()
        .await?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr).to_string();
        return Err(RftError::CommandFailed {
            cmd: "git worktree list --porcelain".to_string(),
            stderr,
        });
    }

    let raw = String::from_utf8_lossy(&output.stdout);
    parse_porcelain_output(&raw, main_branch)
}

pub async fn get_worktree_by_index(
    repo_root: &Path,
    index: usize,
    main_branch: Option<&str>,
) -> Result<WorktreeInfo> {
    let worktrees = get_worktrees(repo_root, main_branch).await?;
    worktrees
        .into_iter()
        .find(|wt| !wt.is_main && wt.index == index)
        .ok_or(RftError::WorktreeNotFound { index })
}

const MAIN_BRANCH_NAMES: &[&str] = &["main", "master"];

fn parse_porcelain_output(raw: &str, main_branch: Option<&str>) -> Result<Vec<WorktreeInfo>> {
    let mut worktrees = Vec::new();
    let blocks = raw.split("\n\n").filter(|block| !block.trim().is_empty());
    let mut non_main_counter = 0usize;

    for block in blocks {
        let mut path: Option<PathBuf> = None;
        let mut branch = String::from("detached");
        let mut is_bare = false;

        for line in block.lines() {
            if let Some(worktree_path) = line.strip_prefix("worktree ") {
                path = Some(PathBuf::from(worktree_path));
            } else if let Some(branch_ref) = line.strip_prefix("branch ") {
                branch = branch_ref
                    .strip_prefix("refs/heads/")
                    .unwrap_or(branch_ref)
                    .to_string();
            } else if line.trim() == "bare" {
                is_bare = true;
            }
        }

        if is_bare {
            continue;
        }

        let is_main = match main_branch {
            Some(name) => branch == name,
            None => MAIN_BRANCH_NAMES.contains(&branch.as_str()),
        };

        if let Some(path) = path {
            let index = if is_main {
                0
            } else {
                non_main_counter += 1;
                non_main_counter
            };

            worktrees.push(WorktreeInfo {
                path,
                branch,
                is_main,
                index,
            });
        }
    }

    Ok(worktrees)
}

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

    const PORCELAIN_TWO_WORKTREES: &str = "\
worktree /home/user/project
HEAD abc123def456
branch refs/heads/main

worktree /home/user/project-feature
HEAD 789def012abc
branch refs/heads/feature/login
";

    const PORCELAIN_WITH_DETACHED: &str = "\
worktree /home/user/project
HEAD abc123def456
branch refs/heads/main

worktree /home/user/project-detached
HEAD 789def012abc
detached
";

    const PORCELAIN_SINGLE: &str = "\
worktree /home/user/project
HEAD abc123def456
branch refs/heads/main
";

    const PORCELAIN_BARE_REPO: &str = "\
worktree /home/user/project/.bare
bare

worktree /home/user/project/main
HEAD abc123def456
branch refs/heads/main

worktree /home/user/project/feature-auth
HEAD 789def012abc
branch refs/heads/feature/auth
";

    const PORCELAIN_MASTER_BRANCH: &str = "\
worktree /home/user/project
HEAD abc123def456
branch refs/heads/master

worktree /home/user/project-feature
HEAD 789def012abc
branch refs/heads/feature/login
";

    #[test]
    fn parse_two_worktrees() {
        let worktrees = parse_porcelain_output(PORCELAIN_TWO_WORKTREES, None).unwrap();

        assert_eq!(worktrees.len(), 2);

        assert_eq!(worktrees[0].path, PathBuf::from("/home/user/project"));
        assert_eq!(worktrees[0].branch, "main");
        assert!(worktrees[0].is_main);
        assert_eq!(worktrees[0].index, 0);

        assert_eq!(
            worktrees[1].path,
            PathBuf::from("/home/user/project-feature")
        );
        assert_eq!(worktrees[1].branch, "feature/login");
        assert!(!worktrees[1].is_main);
        assert_eq!(
            worktrees[1].index, 1,
            "first non-main worktree should be 1-indexed"
        );
    }

    #[test]
    fn parse_detached_head() {
        let worktrees = parse_porcelain_output(PORCELAIN_WITH_DETACHED, None).unwrap();

        assert_eq!(worktrees.len(), 2);
        assert_eq!(worktrees[1].branch, "detached");
        assert!(!worktrees[1].is_main);
        assert_eq!(
            worktrees[1].index, 1,
            "detached non-main worktree is 1-indexed"
        );
    }

    #[test]
    fn parse_single_worktree() {
        let worktrees = parse_porcelain_output(PORCELAIN_SINGLE, None).unwrap();

        assert_eq!(worktrees.len(), 1);
        assert!(worktrees[0].is_main);
        assert_eq!(worktrees[0].branch, "main");
    }

    #[test]
    fn parse_empty_output() {
        let worktrees = parse_porcelain_output("", None).unwrap();
        assert!(worktrees.is_empty());
    }

    #[test]
    fn parse_bare_repo_skips_bare_entry() {
        let worktrees = parse_porcelain_output(PORCELAIN_BARE_REPO, None).unwrap();

        assert_eq!(worktrees.len(), 2, "bare entry should be skipped");
        assert_eq!(worktrees[0].branch, "main");
        assert!(worktrees[0].is_main);
        assert_eq!(worktrees[0].index, 0);

        assert_eq!(worktrees[1].branch, "feature/auth");
        assert!(!worktrees[1].is_main);
        assert_eq!(worktrees[1].index, 1);
    }

    #[test]
    fn parse_master_branch_is_main() {
        let worktrees = parse_porcelain_output(PORCELAIN_MASTER_BRANCH, None).unwrap();

        assert_eq!(worktrees.len(), 2);
        assert!(worktrees[0].is_main, "master should be detected as main");
        assert_eq!(worktrees[0].index, 0);
        assert!(!worktrees[1].is_main);
        assert_eq!(worktrees[1].index, 1);
    }

    #[test]
    fn custom_main_branch_from_config() {
        let porcelain = "\
worktree /home/user/project
HEAD abc123def456
branch refs/heads/develop

worktree /home/user/project-feature
HEAD 789def012abc
branch refs/heads/feature/login
";
        let worktrees = parse_porcelain_output(porcelain, Some("develop")).unwrap();

        assert_eq!(worktrees.len(), 2);
        assert!(
            worktrees[0].is_main,
            "develop should be main when configured"
        );
        assert_eq!(worktrees[0].index, 0);
        assert!(!worktrees[1].is_main);
    }

    #[test]
    fn custom_main_branch_does_not_match_default() {
        let worktrees = parse_porcelain_output(PORCELAIN_TWO_WORKTREES, Some("develop")).unwrap();

        assert!(
            !worktrees[0].is_main,
            "main branch should not match when config says develop"
        );
    }

    #[test]
    fn project_name_from_dot_git() {
        let name = project_name_from_common_dir(Path::new("/home/user/myapp/.git"));
        assert_eq!(name, "myapp");
    }

    #[test]
    fn project_name_from_dot_bare() {
        let name = project_name_from_common_dir(Path::new("/home/user/myapp/.bare"));
        assert_eq!(name, "myapp");
    }

    #[test]
    fn project_name_from_plain_bare() {
        let name = project_name_from_common_dir(Path::new("/home/user/boss"));
        assert_eq!(name, "boss");
    }

    #[test]
    fn project_name_from_root_path() {
        let name = project_name_from_common_dir(Path::new("/"));
        assert_eq!(name, "unknown");
    }

    #[test]
    fn project_name_from_dot_hidden_custom() {
        let name = project_name_from_common_dir(Path::new("/projects/myapp/.gitdata"));
        assert_eq!(name, "myapp");
    }
}