-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit.go
More file actions
312 lines (287 loc) · 9.7 KB
/
Copy pathgit.go
File metadata and controls
312 lines (287 loc) · 9.7 KB
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
package main
import (
"bytes"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
)
// gitIsDirty returns true if the worktree has uncommitted changes.
func gitIsDirty(worktree string) bool {
cmd := exec.Command("git", "status", "--porcelain")
cmd.Dir = worktree
out, err := cmd.Output()
return err == nil && len(bytes.TrimSpace(out)) > 0
}
// gitListRecentBranches returns recently-active branches (remote + local), sorted by
// committer date and deduplicated. Returns an empty slice on error. HEAD is stripped.
func gitListRecentBranches(repoRoot string) ([]string, map[string]bool) {
cmd := exec.Command(
"git",
"for-each-ref",
"--sort=-committerdate",
"--format=%(refname:short) %(refname)",
"refs/remotes/origin/",
"refs/heads/",
)
cmd.Dir = repoRoot
out, err := cmd.Output()
if err != nil {
return []string{}, map[string]bool{}
}
seen := map[string]bool{}
local := map[string]bool{}
var branches []string
for _, l := range strings.Split(strings.TrimSpace(string(out)), "\n") {
l = strings.TrimSpace(l)
if l == "" {
continue
}
// short name is the first field; full refname is the second
parts := strings.SplitN(l, " ", 2)
short := parts[0]
fullref := ""
if len(parts) == 2 {
fullref = parts[1]
}
// strip "origin/" prefix for remote refs so local and remote names match
name := strings.TrimPrefix(short, "origin/")
if name == "HEAD" {
continue
}
if strings.HasPrefix(fullref, "refs/heads/") {
local[name] = true
}
// skip remote refs that have a local counterpart (already or will be added)
if strings.HasPrefix(fullref, "refs/remotes/") && seen[name] {
continue
}
if !seen[name] {
seen[name] = true
branches = append(branches, name)
}
}
return branches, local
}
// gitBranchExistsLocally returns true if the given branch exists as a local ref.
func gitBranchExistsLocally(repoRoot, branch string) bool {
cmd := exec.Command("git", "show-ref", "--verify", "--quiet", "refs/heads/"+branch)
cmd.Dir = repoRoot
return cmd.Run() == nil
}
// gitBranchExistsRemotely returns true if origin/<branch> exists as a remote ref.
func gitBranchExistsRemotely(repoRoot, branch string) bool {
cmd := exec.Command("git", "show-ref", "--verify", "--quiet", "refs/remotes/origin/"+branch)
cmd.Dir = repoRoot
return cmd.Run() == nil
}
// BranchExistsError is returned when trying to create a new branch that already exists locally.
type BranchExistsError struct{ Branch string }
func (e BranchExistsError) Error() string {
return fmt.Sprintf("branch %q already exists", e.Branch)
}
// StaleWorktreeError is returned when a branch is "already checked out" at a
// path that no longer exists on disk — the worktree entry is stale.
type StaleWorktreeError struct{ Branch string }
func (e StaleWorktreeError) Error() string {
return fmt.Sprintf("stale worktree entry for %q — prune and retry?", e.Branch)
}
// stalePath extracts the conflicting path from a "already checked out at '/path'"
// error message and returns it if that path does not exist on disk.
func stalePath(errOutput []byte) string {
s := string(errOutput)
const marker = "already checked out at '"
idx := strings.Index(s, marker)
if idx == -1 {
return ""
}
rest := s[idx+len(marker):]
end := strings.IndexByte(rest, '\'')
if end == -1 {
return ""
}
p := rest[:end]
if _, err := os.Stat(p); os.IsNotExist(err) {
return p
}
return ""
}
// gitCreateWorktree creates a git worktree at worktreePath for the given branch.
// If the branch exists locally it checks it out directly; otherwise it creates a new branch.
// Returns StaleWorktreeError when the branch is registered in a now-missing path.
func gitCreateWorktree(repoRoot, branch, worktreePath string) error {
var args []string
if gitBranchExistsLocally(repoRoot, branch) {
args = []string{"worktree", "add", worktreePath, branch}
} else {
args = []string{"worktree", "add", "-b", branch, worktreePath}
}
cmd := exec.Command("git", args...)
cmd.Dir = repoRoot
out, err := cmd.CombinedOutput()
if err != nil {
if bytes.Contains(out, []byte("already checked out")) {
if stalePath(out) != "" {
return StaleWorktreeError{Branch: branch}
}
return fmt.Errorf("branch %q is already checked out in another worktree", branch)
}
return fmt.Errorf("git worktree add failed: %s", strings.TrimSpace(string(out)))
}
return nil
}
// gitPruneWorktrees removes stale worktree administrative files.
func gitPruneWorktrees(repoRoot string) error {
cmd := exec.Command("git", "worktree", "prune")
cmd.Dir = repoRoot
out, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("git worktree prune failed: %s", strings.TrimSpace(string(out)))
}
return nil
}
// gitCreateWorktreeFromBase creates a new branch off baseBranch and adds a worktree for it.
func gitCreateWorktreeFromBase(repoRoot, branch, worktreePath, baseBranch string) error {
// Remove orphaned directory left by a previous failed attempt.
_ = os.RemoveAll(worktreePath)
args := []string{"worktree", "add", "-b", branch, worktreePath, baseBranch}
cmd := exec.Command("git", args...)
cmd.Dir = repoRoot
out, err := cmd.CombinedOutput()
if err != nil {
if bytes.Contains(out, []byte("already checked out")) {
if stalePath(out) != "" {
return StaleWorktreeError{Branch: branch}
}
return fmt.Errorf("branch %q is already checked out in another worktree", branch)
}
if bytes.Contains(out, []byte("A branch named")) && bytes.Contains(out, []byte("already exists")) {
return BranchExistsError{Branch: branch}
}
return fmt.Errorf("git worktree add failed: %s", strings.TrimSpace(string(out)))
}
return nil
}
// gitRemoveWorktree forcibly removes a git worktree at the given path.
// If git doesn't know about the path (orphaned directory), falls back to os.RemoveAll.
func gitRemoveWorktree(repoRoot, worktreePath string) error {
cmd := exec.Command("git", "worktree", "remove", "--force", worktreePath)
cmd.Dir = repoRoot
if _, err := cmd.CombinedOutput(); err != nil {
return os.RemoveAll(worktreePath)
}
return nil
}
// gitEnsureExclude adds .tulip/ and .claude/ to .git/info/exclude if they're not already there.
func gitEnsureExclude(repoRoot string) {
excludePath := filepath.Join(repoRoot, ".git", "info", "exclude")
data, err := os.ReadFile(excludePath)
if err != nil {
// if the file doesn't exist, try to create the directory and file
_ = os.MkdirAll(filepath.Dir(excludePath), 0o755)
data = []byte{}
}
content := string(data)
var additions []string
if !strings.Contains(content, ".tulip/") {
additions = append(additions, ".tulip/")
}
if !strings.Contains(content, ".claude/") {
additions = append(additions, ".claude/")
}
if !strings.Contains(content, "dist") {
additions = append(additions, "dist")
}
if len(additions) == 0 {
return
}
if len(content) > 0 && !strings.HasSuffix(content, "\n") {
content += "\n"
}
for _, a := range additions {
content += a + "\n"
}
_ = os.WriteFile(excludePath, []byte(content), 0o644)
}
// graftSymlinkDist replaces <repoRoot>/dist with a symlink pointing at <worktree>/dist,
// so Graft always serves the active worktree's build output.
// If dist exists and is a real directory (not a symlink), it refuses to touch it.
func graftSymlinkDist(repoRoot, worktree string) error {
dst := filepath.Join(repoRoot, "dist")
src := filepath.Join(worktree, "dist")
fi, err := os.Lstat(dst)
if err == nil {
if fi.Mode()&os.ModeSymlink == 0 {
if err := os.RemoveAll(dst); err != nil {
return fmt.Errorf("could not remove %s: %w", dst, err)
}
} else {
if err := os.Remove(dst); err != nil {
return fmt.Errorf("could not remove existing symlink: %w", err)
}
}
} else if !os.IsNotExist(err) {
return err
}
gitEnsureExclude(repoRoot)
return os.Symlink(src, dst)
}
// gitStageAndCommit stages all changes in the worktree and creates a signed commit with the given message.
func gitStageAndCommit(worktree, message string) error {
addCmd := exec.Command("git", "add", "-A")
addCmd.Dir = worktree
if out, err := addCmd.CombinedOutput(); err != nil {
return fmt.Errorf("git add failed: %s", strings.TrimSpace(string(out)))
}
commitCmd := exec.Command("git", "commit", "-sm", message)
commitCmd.Dir = worktree
if out, err := commitCmd.CombinedOutput(); err != nil {
return fmt.Errorf("git commit failed: %s", strings.TrimSpace(string(out)))
}
return nil
}
// gitFetch fetches and prunes remote refs from origin.
func gitFetch(repoRoot string) error {
cmd := exec.Command("git", "fetch", "--prune", "origin")
cmd.Dir = repoRoot
out, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("git fetch failed: %s", strings.TrimSpace(string(out)))
}
return nil
}
// gitDefaultRemoteBranch returns the remote's default branch (e.g. "origin/main").
// It reads the symbolic ref set by git fetch/clone. Falls back to origin/main then origin/master.
func gitDefaultRemoteBranch(repoRoot string) string {
cmd := exec.Command("git", "symbolic-ref", "refs/remotes/origin/HEAD")
cmd.Dir = repoRoot
out, err := cmd.Output()
if err == nil {
// output is like "refs/remotes/origin/main\n"
ref := strings.TrimSpace(string(out))
ref = strings.TrimPrefix(ref, "refs/remotes/")
if ref != "" {
return ref
}
}
// Fall back: check if origin/main or origin/master exist.
for _, b := range []string{"origin/main", "origin/master"} {
check := exec.Command("git", "rev-parse", "--verify", b)
check.Dir = repoRoot
if check.Run() == nil {
return b
}
}
return "origin/main"
}
// gitPush pushes the given branch to origin, setting the upstream tracking ref.
func gitPush(worktree, branch string) error {
cmd := exec.Command("git", "push", "-u", "origin", branch)
cmd.Dir = worktree
out, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("git push failed: %s", strings.TrimSpace(string(out)))
}
return nil
}