-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadd.go
More file actions
260 lines (226 loc) · 7.6 KB
/
Copy pathadd.go
File metadata and controls
260 lines (226 loc) · 7.6 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
package main
import (
"bufio"
"errors"
"fmt"
"os"
"strings"
"github.com/amaya382/baretree/internal/repository"
"github.com/amaya382/baretree/internal/worktree"
"github.com/spf13/cobra"
)
var (
addNewBranch bool
addBaseBranch string
addDetach bool
addForce bool
addNoFetch bool
)
var addCmd = &cobra.Command{
Use: "add <branch-name>",
Short: "Create a worktree for a branch (creates branch with -b)",
Long: `Create a new worktree for a branch.
When remotes are configured, fetches from all remotes before adding the worktree
(use --no-fetch to skip).
Supports multiple modes:
1. Create new branch: bt add -b feature/new
2. Existing local branch: bt add existing-branch
3. Remote branch: bt add feature/remote (auto-detects origin/feature/remote)
4. Explicit remote: bt add upstream/feature/foo
The worktree path is automatically determined from the branch name.
Branch names with slashes create hierarchical directories.
Branch resolution order:
1. Local branch exists -> use it
2. origin/<branch> exists -> create tracking branch
3. <remote>/<branch> format -> use specified remote
Examples:
bt add -b feature/auth # Creates new branch and worktree
bt add existing-local-branch # Uses existing local branch
bt add feature/remote # Auto-detects and tracks origin/feature/remote
bt add upstream/feature/test # Tracks upstream/feature/test
bt add --no-fetch feature/new # Skip auto-fetch from remotes`,
Args: cobra.ExactArgs(1),
RunE: runAdd,
}
func init() {
addCmd.Flags().BoolVarP(&addNewBranch, "branch", "b", false, "Create new branch")
addCmd.Flags().StringVar(&addBaseBranch, "base", "", "Base branch for new branch (default: HEAD)")
addCmd.Flags().BoolVar(&addDetach, "detach", false, "Create detached HEAD worktree")
addCmd.Flags().BoolVar(&addForce, "force", false, "Force creation even if worktree exists")
addCmd.Flags().BoolVar(&addNoFetch, "no-fetch", false, "Skip auto-fetch from remotes")
}
func runAdd(cmd *cobra.Command, args []string) error {
branchSpec := args[0]
// Find repository root
cwd, err := os.Getwd()
if err != nil {
return fmt.Errorf("failed to get current directory: %w", err)
}
repoRoot, err := repository.FindRoot(cwd)
if err != nil {
return fmt.Errorf("not in a baretree repository: %w", err)
}
// Get bare repository path
bareDir, err := repository.GetBareRepoPath(repoRoot)
if err != nil {
return err
}
// Load config
mgr, err := repository.NewManager(repoRoot)
if err != nil {
return err
}
// Create worktree manager
wtMgr := worktree.NewManager(repoRoot, bareDir, mgr.Config)
// Auto-fetch unless --no-fetch is specified or no remotes configured
if !addNoFetch && wtMgr.Executor.HasRemotes() {
fmt.Println("Fetching from remotes...")
if err := wtMgr.Fetch(""); err != nil {
return fmt.Errorf("failed to fetch: %w", err)
}
}
// Resolve base branch if specified
var resolvedBaseBranch string
var baseDisplayInfo string
var baseIsLocal bool
if addBaseBranch != "" {
baseInfo, err := wtMgr.ResolveBranch(addBaseBranch)
if err != nil {
return fmt.Errorf("failed to resolve base branch '%s': %w", addBaseBranch, err)
}
if baseInfo.IsLocal {
resolvedBaseBranch = baseInfo.Name
baseDisplayInfo = baseInfo.Name + " (local)"
baseIsLocal = true
} else if baseInfo.IsRemote {
resolvedBaseBranch = baseInfo.RemoteRef
baseDisplayInfo = baseInfo.RemoteRef + " (remote)"
} else {
return fmt.Errorf("base branch '%s' not found locally or on any remote", addBaseBranch)
}
}
// Build add options
opts := worktree.AddOptions{
NewBranch: addNewBranch,
BaseBranch: resolvedBaseBranch,
}
var branchName string
var resolvedBranchIsLocal bool
if addNewBranch {
// Creating a new branch - use spec as-is
branchName = branchSpec
} else {
// Resolve the branch specification
branchInfo, err := wtMgr.ResolveBranch(branchSpec)
if err != nil {
return fmt.Errorf("failed to resolve branch: %w", err)
}
if branchInfo.IsLocal {
// Local branch exists
branchName = branchInfo.Name
resolvedBranchIsLocal = true
} else if branchInfo.IsRemote {
// Remote branch found - create tracking branch
branchName = branchInfo.Name
opts.TrackRef = branchInfo.RemoteRef
fmt.Printf("Tracking remote branch '%s'...\n", branchInfo.RemoteRef)
} else {
// Branch not found anywhere
return fmt.Errorf("branch '%s' not found locally or on any remote\nUse 'bt add -b %s' to create a new branch", branchSpec, branchSpec)
}
}
// Upstream behind detection
if !addForce {
var branchToCheck string
if addNewBranch {
if addBaseBranch != "" && baseIsLocal {
// --base was specified and resolved to a local branch
branchToCheck = resolvedBaseBranch
} else if addBaseBranch == "" {
// No --base: check the default branch
branchToCheck = mgr.Config.Repository.DefaultBranch
if branchToCheck == "" {
branchToCheck = "main"
}
}
} else if resolvedBranchIsLocal {
// Not -b mode: local branch resolved, check it
branchToCheck = branchName
}
if branchToCheck != "" {
behindCount, _ := wtMgr.Executor.GetUpstreamBehindCount(branchToCheck)
if behindCount > 0 {
if isTerminal() {
fmt.Printf("Warning: '%s' is %d commit(s) behind its upstream.\n", branchToCheck, behindCount)
fmt.Printf("Continue anyway? [y/N]: ")
reader := bufio.NewReader(os.Stdin)
response, _ := reader.ReadString('\n')
response = strings.TrimSpace(strings.ToLower(response))
if response != "y" && response != "yes" {
return fmt.Errorf("aborted: '%s' is behind upstream", branchToCheck)
}
} else {
// Non-TTY: warn but proceed
fmt.Printf("Warning: '%s' is %d commit(s) behind its upstream (non-interactive, proceeding).\n", branchToCheck, behindCount)
}
}
}
}
// Display base information
if addNewBranch {
if baseDisplayInfo != "" {
fmt.Printf("Based on '%s'\n", baseDisplayInfo)
} else {
headBranch := wtMgr.Executor.ResolveHEAD()
if headBranch != "" {
fmt.Printf("Based on HEAD (%s)\n", headBranch)
} else {
fmt.Println("Based on HEAD")
}
}
}
fmt.Printf("Creating worktree for branch '%s'...\n", branchName)
// Add worktree (pass os.Stdout for real-time output including "Worktree created" message)
_, postCreateResult, err := wtMgr.AddWithOptions(branchName, opts, os.Stdout)
if err != nil {
var existsErr *worktree.ErrWorktreeAlreadyExists
if errors.As(err, &existsErr) {
fmt.Printf("Worktree for branch '%s' already exists at:\n", existsErr.BranchName)
fmt.Printf(" %s\n\n", existsErr.WorktreePath)
fmt.Printf("To switch to this worktree, use:\n")
fmt.Printf(" bt cd %s\n", existsErr.BranchName)
return nil
}
var refConflictErr *worktree.ErrRefConflict
if errors.As(err, &refConflictErr) {
return refConflictErr
}
return fmt.Errorf("failed to add worktree: %w", err)
}
// "Worktree created" message and post-create output are already printed by AddWithOptions
// Just check if any commands failed and show warning
if postCreateResult != nil && len(postCreateResult.CommandResults) > 0 {
hasErrors := false
for _, result := range postCreateResult.CommandResults {
if !result.Success {
hasErrors = true
break
}
}
if hasErrors {
fmt.Println("\nWarning: Some post-create commands failed")
}
}
fmt.Printf("\nNext steps:\n")
fmt.Printf(" bt cd %s\n", branchName)
fmt.Printf(" # Start working on %s\n", branchName)
return nil
}
// isTerminal checks if stdin is connected to a terminal
func isTerminal() bool {
stat, err := os.Stdin.Stat()
if err != nil {
return false
}
return (stat.Mode() & os.ModeCharDevice) != 0
}