summaryrefslogtreecommitdiffstats
path: root/pkg/commands/git_commands/git_command_builder.go
blob: 4aa35be5f79eb9d3dc31dd025f2e9bfba3111f23 (plain)
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
package git_commands

import (
	"strings"
)

// convenience struct for building git commands. Especially useful when
// including conditional args
type GitCommandBuilder struct {
	// command string
	args []string
}

func NewGitCmd(command string) *GitCommandBuilder {
	return &GitCommandBuilder{args: []string{command}}
}

func (self *GitCommandBuilder) Arg(args ...string) *GitCommandBuilder {
	self.args = append(self.args, args...)

	return self
}

func (self *GitCommandBuilder) ArgIf(condition bool, ifTrue ...string) *GitCommandBuilder {
	if condition {
		self.Arg(ifTrue...)
	}

	return self
}

func (self *GitCommandBuilder) ArgIfElse(condition bool, ifTrue string, ifFalse string) *GitCommandBuilder {
	if condition {
		return self.Arg(ifTrue)
	} else {
		return self.Arg(ifFalse)
	}
}

func (self *GitCommandBuilder) Config(value string) *GitCommandBuilder {
	// config settings come before the command
	self.args = append([]string{"-c", value}, self.args...)

	return self
}

func (self *GitCommandBuilder) ConfigIf(condition bool, ifTrue string) *GitCommandBuilder {
	if condition {
		self.Config(ifTrue)
	}

	return self
}

// the -C arg will make git do a `cd` to the directory before doing anything else
func (self *GitCommandBuilder) Dir(path string) *GitCommandBuilder {
	// repo path comes before the command
	self.args = append([]string{"-C", path}, self.args...)

	return self
}

// Note, you may prefer to use the Dir method instead of this one
func (self *GitCommandBuilder) Worktree(path string) *GitCommandBuilder {
	// worktree arg comes before the command
	self.args = append([]string{"--work-tree", path}, self.args...)

	return self
}

// Note, you may prefer to use the Dir method instead of this one
func (self *GitCommandBuilder) GitDir(path string) *GitCommandBuilder {
	// git dir arg comes before the command
	self.args = append([]string{"--git-dir", path}, self.args...)

	return self
}

func (self *GitCommandBuilder) GitDirIf(condition bool, path string) *GitCommandBuilder {
	if condition {
		return self.GitDir(path)
	}

	return self
}

func (self *GitCommandBuilder) ToArgv() []string {
	return append([]string{"git"}, self.args...)
}

func (self *GitCommandBuilder) ToString() string {
	return strings.Join(self.ToArgv(), " ")
}