getWorktree gets or recreates a worktree for an existing environment. It assumes the environment branch already exists in the forkRepo and will fail if it doesn't.
(ctx context.Context, id string)
| 163 | // getWorktree gets or recreates a worktree for an existing environment. |
| 164 | // It assumes the environment branch already exists in the forkRepo and will fail if it doesn't. |
| 165 | func (r *Repository) getWorktree(ctx context.Context, id string) (string, error) { |
| 166 | worktreePath, err := r.WorktreePath(id) |
| 167 | if err != nil { |
| 168 | return "", err |
| 169 | } |
| 170 | |
| 171 | // Early return if the worktree already exists |
| 172 | if _, err := os.Stat(worktreePath); err == nil { |
| 173 | return worktreePath, nil |
| 174 | } |
| 175 | |
| 176 | slog.Info("Recreating worktree for existing environment", "repository", r.userRepoPath, "environment-id", id) |
| 177 | |
| 178 | return worktreePath, r.lockManager.WithLock(ctx, LockTypeForkRepo, func() error { |
| 179 | // In case something has changed while waiting for lock. prolly too defensive. |
| 180 | if _, err := os.Stat(worktreePath); err == nil { |
| 181 | return nil |
| 182 | } |
| 183 | |
| 184 | // Verify the environment branch exists in forkRepo before creating worktree |
| 185 | _, err := RunGitCommand(ctx, r.forkRepoPath, "rev-parse", "--verify", id) |
| 186 | if err != nil { |
| 187 | return fmt.Errorf("environment branch %s not found in fork repository: %w", id, err) |
| 188 | } |
| 189 | |
| 190 | _, err = RunGitCommand(ctx, r.forkRepoPath, "worktree", "add", worktreePath, id) |
| 191 | if err != nil { |
| 192 | return err |
| 193 | } |
| 194 | |
| 195 | _, err = RunGitCommand(ctx, r.userRepoPath, "fetch", containerUseRemote, id) |
| 196 | if err != nil { |
| 197 | return err |
| 198 | } |
| 199 | |
| 200 | return nil |
| 201 | }) |
| 202 | } |
| 203 | |
| 204 | // createInitialCommit creates an empty commit with the environment creation message - this prevents multiple environments from overwriting the container-use-state on the parent commit |
| 205 | func (r *Repository) createInitialCommit(ctx context.Context, worktreePath, id, title string) error { |
no test coverage detected