-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgitexec.go
More file actions
371 lines (296 loc) · 8.95 KB
/
Copy pathgitexec.go
File metadata and controls
371 lines (296 loc) · 8.95 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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
// Package gitexec provides utilities for executing git commands.
package gitexec
import (
"errors"
"fmt"
"os/exec"
"strings"
"github.com/dansimau/yas/pkg/xexec"
"github.com/hashicorp/go-version"
)
var ErrDetachedHead = errors.New("currently in detached state")
type CloneOptions struct {
URL string
Depth int
}
func Clone(path string, options CloneOptions) error {
cmd := []string{"git", "clone", options.URL}
if options.Depth != 0 {
cmd = append(cmd, "--depth", "1", "-q")
}
cmd = append(cmd, path)
return xexec.Command(cmd...).
WithEnvVars(CleanedGitEnv()).
WithStdout(nil).Run()
}
type Repo struct {
path string
}
func WithRepo(path string) *Repo {
return &Repo{path: path}
}
func (r *Repo) run(args ...string) error {
_, err := r.output(args...)
return err
}
func (r *Repo) output(args ...string) (string, error) {
b, err := xexec.Command(args...).
WithEnvVars(CleanedGitEnv()).
WithWorkingDir(r.path).
WithStdout(nil).
Output()
if err != nil {
return "", err
}
return strings.TrimSpace(string(b)), nil
}
func (r *Repo) BranchExists(ref string) (bool, error) {
if err := r.run("git", "show-ref", "refs/heads/"+ref); err != nil {
exitErr := &exec.ExitError{}
isExitError := errors.As(err, &exitErr)
if !isExitError {
return false, err
}
// Exit code 1 means the branch doesn't exist
if exitErr.ExitCode() == 1 {
return false, nil
}
// Unrecognized exit code
return false, err
}
return true, nil
}
func (r *Repo) RemoteBranchExists(ref string) (bool, error) {
if err := r.run("git", "show-ref", "refs/remotes/origin/"+ref); err != nil {
var exitErr *exec.ExitError
if !errors.As(err, &exitErr) {
return false, err
}
// Exit code 1 means the branch doesn't exist
if exitErr.ExitCode() == 1 {
return false, nil
}
// Unrecognized exit code
return false, err
}
return true, nil
}
// DetectMainBranch attempts to automatically detect the main branch name.
// It checks for common branch names ("main", "master") in both local and remote branches,
// returning the first match found.
func (r *Repo) DetectMainBranch() (string, error) {
candidates := []string{"main", "master"}
for _, candidate := range candidates {
// Check local branch first
exists, err := r.BranchExists(candidate)
if err != nil {
return "", err
}
if exists {
return candidate, nil
}
// Check remote branch
exists, err = r.RemoteBranchExists(candidate)
if err != nil {
return "", err
}
if exists {
return candidate, nil
}
}
return "", nil
}
func (r *Repo) Checkout(ref string) error {
return r.run("git", "checkout", ref)
}
func (r *Repo) QuietCheckout(ref string) error {
return r.run("git", "-c", "core.hooksPath=/dev/null", "checkout", "-q", ref)
}
func (r *Repo) CreateBranch(branch string) error {
return r.run("git", "checkout", "-b", branch)
}
// CreateBranchFrom creates a new branch based on the given start point (e.g.
// another branch or commit) and switches to it.
func (r *Repo) CreateBranchFrom(branch string, startPoint string) error {
return r.run("git", "checkout", "-b", branch, startPoint)
}
func (r *Repo) DeleteBranch(branch string) error {
return xexec.Command("git", "branch", "-D", branch).
WithEnvVars(CleanedGitEnv()).
WithWorkingDir(r.path).
Run()
}
func (r *Repo) GetConfig(key string) (string, error) {
return r.output("git", "config", key)
}
func (r *Repo) GetCurrentBranchName() (string, error) {
s, err := r.output("git", "branch", "--show-current")
if err != nil {
return "", err
}
if s == "" {
return "", ErrDetachedHead
}
return s, nil
}
func (r *Repo) GetLocalBranchNameForCommit(ref string) (string, error) {
return r.output("git", "branch", "--points-at", ref, "--format=%(refname:lstrip=2)")
}
func (r *Repo) GetForkPoint(branchName string) (ref string, err error) {
return r.output("git", "merge-base", "--fork-point", branchName)
}
func (r *Repo) GetMergeBase(ref1, ref2 string) (string, error) {
return r.output("git", "merge-base", ref1, ref2)
}
func (r *Repo) GetCommitHash(ref string) (string, error) {
return r.output("git", "rev-parse", ref)
}
func (r *Repo) GetShortHash(ref string) (string, error) {
return r.output("git", "rev-parse", "--short", ref)
}
func (r *Repo) Push() error {
return xexec.Command("git", "push").
WithEnvVars(CleanedGitEnv()).
WithWorkingDir(r.path).
Run()
}
func (r *Repo) GetRemoteForBranch(branchNames ...string) (string, error) {
var lastErr error
for _, branchName := range branchNames {
remote, err := r.output("git", "config", fmt.Sprintf("branch.%s.remote", branchName))
if err == nil && remote != "" {
return remote, nil
}
lastErr = fmt.Errorf("no remote configured for branch %s", branchName)
}
if lastErr != nil {
return "", lastErr
}
return "", errors.New("no branch names provided")
}
func (r *Repo) ForcePushBranch(origin string, branchName string) error {
return xexec.Command("git", "push", "--force-with-lease", "-q", origin, branchName).
WithEnvVars(CleanedGitEnv()).
WithWorkingDir(r.path).
WithStdout(nil).
WithStderr(nil).
Run()
}
func (r *Repo) FetchBranch(branchName string) error {
return r.run("git", "fetch", "origin", branchName, "-q")
}
func (r *Repo) GetRemoteCommitHash(branchName string) (string, error) {
return r.output("git", "rev-parse", "origin/"+branchName)
}
func (r *Repo) GetRemoteShortHash(branchName string) (string, error) {
return r.output("git", "rev-parse", "--short", "origin/"+branchName)
}
func (r *Repo) Path() string {
return r.path
}
func (r *Repo) Rebase(upstream, branchName string) error {
return xexec.Command("git", "-c", "core.hooksPath=/dev/null", "rebase", upstream, branchName, "--update-refs").
WithEnvVars(CleanedGitEnv()).
WithWorkingDir(r.path).
Run()
}
// RebaseOntoWithBranchPoint rebases branch onto newBase, replaying commits after oldBranchPoint
// This is equivalent to: git rebase --onto <newBase> <oldBranchPoint> <branch>.
func (r *Repo) RebaseOntoWithBranchPoint(newBase, oldBranchPoint, branch string) error {
return xexec.Command("git", "-c", "core.hooksPath=/dev/null", "rebase", "--onto", newBase, oldBranchPoint, branch, "--update-refs").
WithEnvVars(CleanedGitEnv()).
WithWorkingDir(r.path).
Run()
}
func (r *Repo) Pull() error {
return xexec.Command("git", "pull", "--ff", "--ff-only").
WithEnvVars(CleanedGitEnv()).
WithWorkingDir(r.path).
Run()
}
func (r *Repo) GitPath() (path string, err error) {
path, err = r.output("which", "git")
if err != nil {
return "", err
}
return path, nil
}
func (r *Repo) GitVersion() (*version.Version, error) {
s, err := r.output("git", "--version")
if err != nil {
return nil, err
}
v := strings.SplitN(s, " ", 4)
if len(v) < 3 {
return nil, fmt.Errorf("unable to parse version from: %s", s)
}
versionStr := v[2]
version, err := version.NewVersion(versionStr)
if err != nil {
return nil, err
}
return version, nil
}
// HasStagedChanges checks if there are any staged changes in the index.
func (r *Repo) HasStagedChanges() (bool, error) {
output, err := r.output("git", "diff", "--cached", "--quiet")
if err != nil {
var exitErr *exec.ExitError
if !errors.As(err, &exitErr) {
return false, err
}
// Exit code 1 means there are differences (staged changes exist)
if exitErr.ExitCode() == 1 {
return true, nil
}
// Unrecognized exit code
return false, err
}
// Exit code 0 means no differences (no staged changes)
return output != "", nil
}
// Commit creates an interactive commit, opening an editor for the user to write the commit message.
func (r *Repo) Commit() error {
return xexec.Command("git", "commit").
WithEnvVars(CleanedGitEnv()).
WithWorkingDir(r.path).
Run()
}
// IsRebaseInProgress checks if a rebase operation is currently in progress.
func (r *Repo) IsRebaseInProgress() (bool, error) {
// Get the actual git directory (handles both regular repos and linked worktrees)
gitDir, err := r.output("git", "rev-parse", "--git-dir")
if err != nil {
return false, err
}
// Check for rebase-merge directory (interactive rebase)
if err := r.run("test", "-d", gitDir+"/rebase-merge"); err == nil {
return true, nil
}
// Check for rebase-apply directory (non-interactive rebase)
if err := r.run("test", "-d", gitDir+"/rebase-apply"); err == nil {
return true, nil
}
return false, nil
}
// RebaseContinue continues a rebase operation that was paused due to conflicts.
func (r *Repo) RebaseContinue() error {
return xexec.Command("git", "-c", "core.hooksPath=/dev/null", "-c", "core.editor=true", "rebase", "--continue").
WithEnvVars(CleanedGitEnv()).
WithWorkingDir(r.path).
Run()
}
// RebaseAbort aborts an in-progress rebase operation.
func (r *Repo) RebaseAbort() error {
return xexec.Command("git", "rebase", "--abort").
WithEnvVars(CleanedGitEnv()).
WithWorkingDir(r.path).
Run()
}
// HardReset performs a hard reset to the specified commit.
func (r *Repo) HardReset(commit string) error {
return xexec.Command("git", "reset", "--hard", commit).
WithEnvVars(CleanedGitEnv()).
WithWorkingDir(r.path).
Run()
}