forked from ldez/go-git-cmd-wrapper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
types.go
74 lines (61 loc) · 1.53 KB
/
types.go
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
package types
import (
"context"
"log"
"os"
"os/exec"
"strings"
)
type logger interface {
Fatal(args ...interface{})
Fatalf(format string, args ...interface{})
Print(args ...interface{})
Println(args ...interface{})
Printf(format string, args ...interface{})
}
// Executor The Git command call function.
type Executor func(ctx context.Context, name string, debug bool, args ...string) (string, error)
// NewCmd Creates a new Cmd.
func NewCmd(name string) *Cmd {
g := &Cmd{
Debug: false,
Base: "git",
Options: []string{name},
Logger: log.New(os.Stdout, "", 0),
}
g.Executor = defaultExecutor(g)
return g
}
// Cmd Command.
type Cmd struct {
Debug bool
Base string
Options []string
Logger logger
Executor Executor
}
// Option Command option.
type Option func(g *Cmd)
// AddOptions Add one command option.
func (g *Cmd) AddOptions(option string) {
g.Options = append(g.Options, option)
}
// ApplyOptions Apply command options.
func (g *Cmd) ApplyOptions(options ...Option) {
for _, opt := range options {
opt(g)
}
}
// Exec Execute the Git command call.
func (g *Cmd) Exec(ctx context.Context, name string, debug bool, args ...string) (string, error) {
return g.Executor(ctx, name, debug, args...)
}
func defaultExecutor(g *Cmd) Executor {
return func(ctx context.Context, name string, debug bool, args ...string) (string, error) {
if debug {
g.Logger.Println(name, strings.Join(args, " "))
}
output, err := exec.CommandContext(ctx, name, args...).CombinedOutput()
return string(output), err
}
}