| 32 | } |
| 33 | return filepath.Clean(stringTrimSpace(out)) |
| 34 | } |
| 35 | |
| 36 | func CreateWorktree(ctx context.Context, repoRoot, baseRef, agentType, worktreesDir string) (WorktreeResult, error) { |
| 37 | if baseRef == "" { |
| 38 | baseRef = "HEAD" |
| 39 | } |
| 40 | if worktreesDir == "" { |
| 41 | worktreesDir = filepath.Join(apppaths.ProjectLocalDirName, apppaths.ProjectWorktreesDirName) |
| 42 | } |
| 43 | result := WorktreeResult{RepoRoot: repoRoot, BaseRef: baseRef} |
| 44 | if !filepath.IsAbs(worktreesDir) { |
| 45 | worktreesDir = filepath.Join(repoRoot, worktreesDir) |
| 46 | } |
| 47 | if err := os.MkdirAll(worktreesDir, 0o755); err != nil { |
| 48 | return result, nil |
| 49 | } |
| 50 | suffix := uuid.NewString()[:8] |
| 51 | path := filepath.Join(worktreesDir, agentType+"-"+suffix) |
| 52 | cmdCtx, cancel := context.WithTimeout(ctx, 30*time.Second) |
| 53 | defer cancel() |
| 54 | cmd := exec.CommandContext(cmdCtx, "git", "worktree", "add", path, baseRef) |
| 55 | cmd.Dir = repoRoot |
| 56 | if out, err := cmd.CombinedOutput(); err != nil { |
| 57 | _ = removeDirIfEmpty(path) |
| 58 | _ = out |
| 59 | return result, nil |
| 60 | } |
| 61 | result.WorktreePath = path |
| 62 | return result, nil |
| 63 | } |
| 64 | |