-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathworktree_path.go
More file actions
266 lines (226 loc) · 6.11 KB
/
worktree_path.go
File metadata and controls
266 lines (226 loc) · 6.11 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
package cmd
import (
"bytes"
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
"text/template"
)
func buildWorktreePath(info repoInfo, branch string) (string, error) {
rendered, err := renderWorktreePath(info, branch)
if err != nil {
return "", err
}
parent := filepath.Dir(rendered)
infoStat, err := os.Stat(parent)
switch {
case err == nil:
if !infoStat.IsDir() {
return "", fmt.Errorf("worktree path %s is not a directory", parent)
}
case os.IsNotExist(err):
if err := os.MkdirAll(parent, 0o755); err != nil {
return "", fmt.Errorf("failed to create worktree directory %s: %w", parent, err)
}
default:
return "", fmt.Errorf("failed to access worktree directory %s: %w", parent, err)
}
return rendered, nil
}
func renderWorktreePath(info repoInfo, branch string) (string, error) {
pattern, err := resolveWorktreePattern()
if err != nil {
return "", err
}
sep := worktreeSeparator
transformValue := func(s string) string {
return strings.ReplaceAll(strings.ReplaceAll(s, "/", sep), "\\", sep)
}
envMap := map[string]string{}
for _, e := range os.Environ() {
parts := strings.SplitN(e, "=", 2)
if len(parts) == 2 {
envMap[parts[0]] = transformValue(parts[1])
}
}
context := map[string]any{
"repo": repoInfo{
Main: info.Main,
Host: info.Host,
Owner: transformValue(info.Owner),
Name: info.Name,
},
"branch": strings.TrimSpace(transformValue(branch)),
"worktreeRoot": worktreeRoot,
"env": envMap,
}
if pattern == "" {
return "", fmt.Errorf("worktree pattern cannot be empty")
}
tpl, err := template.New("worktreePattern").
Delims("{", "}").
Option("missingkey=error").
Parse(pattern)
if err != nil {
return "", fmt.Errorf("invalid worktree pattern: %w", err)
}
var renderedBuf bytes.Buffer
if err := tpl.Execute(&renderedBuf, context); err != nil {
return "", fmt.Errorf("pattern variables missing values: %w", err)
}
rendered := renderedBuf.String()
rendered = filepath.FromSlash(rendered)
if !filepath.IsAbs(rendered) {
rendered = filepath.Join(worktreeRoot, rendered)
}
rendered = filepath.Clean(rendered)
return rendered, nil
}
func cleanupWorktreePath(worktreePath string) error {
if worktreePath == "" {
return nil
}
if err := os.RemoveAll(worktreePath); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("failed to remove worktree directory %s: %w", worktreePath, err)
}
absRoot, err := filepath.Abs(worktreeRoot)
if err != nil {
return nil
}
absWorktreePath, err := filepath.Abs(worktreePath)
if err != nil {
return nil
}
repoDir := filepath.Dir(absWorktreePath)
if strings.HasPrefix(repoDir, absRoot) {
if empty, err := isDirEmpty(repoDir); err == nil && empty {
_ = os.Remove(repoDir)
}
}
return nil
}
func warnIfCaseInsensitivePathCollision(worktreePath string) {
if isJSONOutput() || !filesystemCaseInsensitive(worktreePath) {
return
}
if existingPath, ok := findCaseInsensitivePathCollision(worktreePath); ok {
fmt.Fprintf(os.Stderr, "Warning: worktree path %s collides with existing path %s on this case-insensitive filesystem. Consider setting separator = \"-\" in your wt config or avoiding case-only branch names.\n", worktreePath, existingPath)
}
}
func findCaseInsensitivePathCollision(path string) (string, bool) {
path = filepath.Clean(path)
volume := filepath.VolumeName(path)
rest := strings.TrimPrefix(path, volume)
current := volume
if filepath.IsAbs(path) {
current += string(os.PathSeparator)
rest = strings.TrimPrefix(rest, string(os.PathSeparator))
} else if current == "" {
current = "."
}
for _, part := range strings.Split(rest, string(os.PathSeparator)) {
if part == "" || part == "." {
continue
}
entries, err := os.ReadDir(current)
if err != nil {
return "", false
}
exactPath := filepath.Join(current, part)
foundExact := false
for _, entry := range entries {
name := entry.Name()
if name == part {
foundExact = true
break
}
if strings.EqualFold(name, part) {
return filepath.Join(current, name), true
}
}
if !foundExact {
return "", false
}
current = exactPath
}
return "", false
}
func filesystemCaseInsensitive(path string) bool {
if runtime.GOOS != "darwin" && runtime.GOOS != "windows" {
return false
}
dir := nearestExistingDir(path)
if dir == "" {
return runtime.GOOS == "windows"
}
file, err := os.CreateTemp(dir, ".wt-case-test-")
if err != nil {
return runtime.GOOS == "windows"
}
name := file.Name()
_ = file.Close()
defer func() { _ = os.Remove(name) }()
altName := filepath.Join(dir, strings.ToUpper(filepath.Base(name)))
if altName == name {
altName = filepath.Join(dir, strings.ToLower(filepath.Base(name)))
}
if altName == name {
return false
}
_, err = os.Stat(altName)
return err == nil
}
func nearestExistingDir(path string) string {
if path == "" {
path = "."
}
path = filepath.Clean(path)
if info, err := os.Stat(path); err == nil {
if info.IsDir() {
return path
}
return filepath.Dir(path)
}
for {
parent := filepath.Dir(path)
if parent == path {
return ""
}
if info, err := os.Stat(parent); err == nil && info.IsDir() {
return parent
}
path = parent
}
}
func resolveWorktreePattern() (string, error) {
if worktreePattern != "" {
return worktreePattern, nil
}
if worktreeStrategy == "custom" {
return "", fmt.Errorf("WORKTREE_PATTERN is required when WORKTREE_STRATEGY is 'custom'")
}
switch worktreeStrategy {
case "global":
return "{.worktreeRoot}/{.repo.Name}/{.branch}", nil
case "sibling-repo", "sibling":
return "{.repo.Main}/../{.repo.Name}-{.branch}", nil
case "parent-worktrees", "parent-centered":
return "{.repo.Main}/../{.repo.Name}.worktrees/{.branch}", nil
case "parent-branches", "repo-root":
return "{.repo.Main}/../{.branch}", nil
case "parent-dotdir", "local-root":
return "{.repo.Main}/../.worktrees/{.branch}", nil
case "inside-dotdir", "nested-local":
return "{.repo.Main}/.worktrees/{.branch}", nil
default:
return "", fmt.Errorf("unsupported WORKTREE_STRATEGY: %s", worktreeStrategy)
}
}
func printCDMarker(path string) {
if isJSONOutput() {
return
}
fmt.Printf("wt navigating to: %s\n", path)
}