File: checkout.go

package info (click to toggle)
gitbatch 0.5.0-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 504 kB
  • sloc: makefile: 10; sh: 1
file content (49 lines) | stat: -rw-r--r-- 1,081 bytes parent folder | download | duplicates (2)
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
package command

import (
	"os/exec"

	"github.com/isacikgoz/gitbatch/core/git"
)

// CheckoutOptions defines the rules of checkout command
type CheckoutOptions struct {
	TargetRef      string
	CreateIfAbsent bool
	CommandMode    Mode
}

// Checkout is a wrapper function for "git checkout" command.
func Checkout(r *git.Repository, o *CheckoutOptions) error {
	var branch *git.Branch
	for _, b := range r.Branches {
		if b.Name == o.TargetRef {
			branch = b
			break
		}
	}
	msg := "checkout in progress"
	if branch != nil {
		if err := r.Checkout(branch); err != nil {
			r.SetWorkStatus(git.Fail)
			msg = err.Error()
		} else {
			r.SetWorkStatus(git.Success)
			msg = "switched to " + o.TargetRef
		}
	} else if o.CreateIfAbsent {
		args := []string{"checkout", "-b", o.TargetRef}
		cmd := exec.Command("git", args...)
		cmd.Dir = r.AbsPath
		_, err := cmd.CombinedOutput()
		if err != nil {
			r.SetWorkStatus(git.Fail)
			msg = err.Error()
		} else {
			r.SetWorkStatus(git.Success)
			msg = "switched to " + o.TargetRef
		}
	}
	r.State.Message = msg
	return r.Refresh()
}