Debian Codegraph @

internal/command/checkout.go

raw symbols SCIP
1 package command
2
3 import (
4 "os/exec"
5
6 "github.com/isacikgoz/gitbatch/internal/git"
7 )
8
9 // CheckoutOptions defines the rules of checkout command
10 type CheckoutOptions struct {
11 TargetRef string
12 CreateIfAbsent bool
13 CommandMode Mode
14 }
15
16 // Checkout is a wrapper function for "git checkout" command.
17 func Checkout(r *git.Repository, o *CheckoutOptions) error {
18 var branch *git.Branch
19 for _, b := range r.Branches {
20 if b.Name == o.TargetRef {
21 branch = b
22 break
23 }
24 }
25 msg := "checkout in progress"
26 if branch != nil {
27 if err := r.Checkout(branch); err != nil {
28 r.SetWorkStatus(git.Fail)
29 msg = err.Error()
30 } else {
31 r.SetWorkStatus(git.Success)
32 msg = "switched to " + o.TargetRef
33 }
34 } else if o.CreateIfAbsent {
35 args := []string{"checkout", "-b", o.TargetRef}
36 cmd := exec.Command("git", args...)
37 cmd.Dir = r.AbsPath
38 _, err := cmd.CombinedOutput()
39 if err != nil {
40 r.SetWorkStatus(git.Fail)
41 msg = err.Error()
42 } else {
43 r.SetWorkStatus(git.Success)
44 msg = "switched to " + o.TargetRef
45 }
46 }
47 r.State.Message = msg
48 return r.Refresh()
49 }