/
action_git.go
265 lines (220 loc) · 6.06 KB
/
action_git.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
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
package action
import (
"bufio"
"context"
"fmt"
"github.com/hamster-shared/aline-engine/logger"
model2 "github.com/hamster-shared/aline-engine/model"
"github.com/hamster-shared/aline-engine/output"
"github.com/hamster-shared/aline-engine/utils"
"os"
"os/exec"
"strings"
)
// GitAction git clone
type GitAction struct {
repository string
branch string
workdir string
output *output.Output
ctx context.Context
}
func NewGitAction(step model2.Step, ctx context.Context, output *output.Output) *GitAction {
stack := ctx.Value(STACK).(map[string]interface{})
params := stack["parameter"].(map[string]string)
return &GitAction{
repository: utils.ReplaceWithParam(step.With["url"], params),
branch: utils.ReplaceWithParam(step.With["branch"], params),
ctx: ctx,
output: output,
}
}
func (a *GitAction) Pre() error {
// a.output.NewStep("git")
stack := a.ctx.Value(STACK).(map[string]interface{})
a.workdir = stack["workdir"].(string)
_, err := os.Stat(a.workdir)
if err != nil {
err = os.MkdirAll(a.workdir, os.ModePerm)
if err != nil {
return err
}
command := "git init " + a.workdir
_, err = a.ExecuteStringCommand(command)
if err != nil {
return err
}
}
//TODO ... 检验 git 命令是否存在
return nil
}
func (a *GitAction) Hook() (*model2.ActionResult, error) {
stack := a.ctx.Value(STACK).(map[string]interface{})
logger.Infof("git stack: %v", stack)
// before
//commands := []string{"git", "clone", "--progress", a.repository, "-b", a.branch, pipelineName}
//err := a.ExecuteCommand(commands)
//if err != nil {
// return nil, err
//}
command := "git rev-parse --is-inside-work-tree"
_, err := a.ExecuteStringCommand(command)
if err != nil {
command = "git init"
_, err = a.ExecuteStringCommand(command)
if err != nil {
return nil, err
}
}
command = "git config remote.origin.url " + a.repository
_, err = a.ExecuteStringCommand(command)
if err != nil {
return nil, err
}
command = "git config --add remote.origin.fetch +refs/heads/*:refs/remotes/origin/*"
_, err = a.ExecuteStringCommand(command)
if err != nil {
return nil, err
}
command = "git config remote.origin.url " + a.repository
_, err = a.ExecuteStringCommand(command)
if err != nil {
return nil, err
}
command = "git fetch --tags --progress " + a.repository + " +refs/heads/*:refs/remotes/origin/*"
_, err = a.ExecuteStringCommand(command)
if err != nil {
return nil, err
}
command = fmt.Sprintf("git rev-parse refs/remotes/origin/%s^{commit}", a.branch)
commitId, err := a.ExecuteCommandDirect(strings.Fields(command))
if err != nil {
return nil, err
}
command = "git config core.sparsecheckout "
_, _ = a.ExecuteStringCommand(command)
command = fmt.Sprintf("git checkout -f %s", commitId)
_, err = a.ExecuteStringCommand(command)
if err != nil {
return nil, err
}
command = "git branch -a -v --no-abbrev"
out, err := a.ExecuteCommandDirect(strings.Fields(command))
if err != nil {
return nil, err
}
if containsBranch(out, a.branch) {
command = fmt.Sprintf("git branch -D %s", a.branch)
out, err = a.ExecuteStringCommand(command)
logger.Debug(out)
if err != nil {
return nil, err
}
}
command = fmt.Sprintf("git checkout -b %s %s", a.branch, commitId)
out, err = a.ExecuteStringCommand(command)
a.output.WriteLine(out)
if err != nil {
return nil, err
}
stack["workdir"] = a.workdir
return &model2.ActionResult{
CodeInfo: fmt.Sprintf("%s | %s", a.branch, commitId[0:6]),
}, nil
}
func (a *GitAction) Post() error {
//return os.Remove(a.workdir)
return nil
}
func (a *GitAction) ExecuteStringCommand(command string) (string, error) {
commands := strings.Fields(command)
return a.ExecuteCommand(commands)
}
func (a *GitAction) ExecuteCommand(commands []string) (string, error) {
c := exec.CommandContext(a.ctx, commands[0], commands[1:]...) // mac linux
c.Dir = a.workdir
logger.Debugf("execute git clone command: %s", strings.Join(commands, " "))
a.output.WriteCommandLine(strings.Join(commands, " "))
stdout, err := c.StdoutPipe()
if err != nil {
logger.Errorf("stdout error: %v", err)
return "nil", err
}
stderr, err := c.StderrPipe()
if err != nil {
logger.Errorf("stderr error: %v", err)
return "nil", err
}
go func() {
for {
// 检测到 ctx.Done() 之后停止读取
<-a.ctx.Done()
if a.ctx.Err() != nil {
logger.Errorf("shell command error: %v", a.ctx.Err())
return
} else {
p := c.Process
if p == nil {
return
}
// Kill by negative PID to kill the process group, which includes
// the top-level process we spawned as well as any subprocesses
// it spawned.
//_ = syscall.Kill(-p.Pid, syscall.SIGKILL)
logger.Info("shell command killed")
return
}
}
}()
stdoutScanner := bufio.NewScanner(stdout)
stderrScanner := bufio.NewScanner(stderr)
go func() {
for stdoutScanner.Scan() {
fmt.Println(stdoutScanner.Text())
a.output.WriteLine(stdoutScanner.Text())
}
}()
go func() {
for stderrScanner.Scan() {
fmt.Println(stderrScanner.Text())
a.output.WriteLine(stderrScanner.Text())
}
}()
err = c.Start()
if err != nil {
logger.Errorf("shell command start error: %v", err)
return "nil", err
}
err = c.Wait()
if err != nil {
logger.Errorf("shell command wait error: %v", err)
return "nil", err
}
defer stdout.Close()
defer stderr.Close()
return "", err
}
func (a *GitAction) ExecuteCommandDirect(commands []string) (string, error) {
c := exec.CommandContext(a.ctx, commands[0], commands[1:]...) // mac linux
c.Dir = a.workdir
logger.Debugf("execute git clone command: %s", strings.Join(commands, " "))
a.output.WriteCommandLine(strings.Join(commands, " "))
out, err := c.CombinedOutput()
a.output.WriteCommandLine(string(out))
if err != nil {
a.output.WriteLine(err.Error())
}
return string(out), err
}
func containsBranch(branchOutput, branch string) bool {
array := strings.Split(branchOutput, "\n")
for _, s := range array {
if len(strings.Fields(s)) == 0 {
continue
}
if strings.EqualFold(strings.Fields(s)[0], branch) {
return true
}
}
return false
}