/
svn.go
380 lines (347 loc) · 9.28 KB
/
svn.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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
// RAINBOND, Application Management Platform
// Copyright (C) 2014-2017 Goodrain Co., Ltd.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. For any non-GPL usage of Rainbond,
// one or multiple Commercial Licenses authorized by Goodrain Co., Ltd.
// must be obtained first.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with c program. If not, see <http://www.gnu.org/licenses/>.
package sources
import (
"bytes"
"encoding/xml"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path"
"strings"
"time"
"github.com/Sirupsen/logrus"
"github.com/goodrain/rainbond/event"
"github.com/goodrain/rainbond/util"
)
//SVNClient svn svnclient
type SVNClient interface {
Checkout() (*Info, error)
Update(childpath string) (*Info, error)
UpdateOrCheckout(childpath string) (*Info, error)
}
type svnclient struct {
username string
password string
svnURL string
svnDir string
Env []string
logger event.Logger
csi CodeSourceInfo
}
// NewClient new svn svnclient
func NewClient(csi CodeSourceInfo, codeHome string, logger event.Logger) SVNClient {
return &svnclient{csi: csi, username: csi.User, password: csi.Password, svnURL: csi.RepositoryURL, svnDir: codeHome, logger: logger}
}
// NewClientWithEnv ...
func NewClientWithEnv(username, password, url, sourceDir string, env []string) SVNClient {
util.CheckAndCreateDir(sourceDir)
return &svnclient{username: username, password: password, svnURL: url, Env: env, svnDir: sourceDir}
}
// Diff ...
func (c *svnclient) Diff(start, end int) (string, error) {
r := fmt.Sprintf("%d:%d", start, end)
out, err := c.run("diff", "-r", r, c.svnURL)
if err != nil {
return "", err
}
return string(out), nil
}
// Cat ...
func (c *svnclient) Cat(file string) (string, error) {
out, err := c.run("cat", c.svnURL+"/"+file)
if err != nil {
return "", err
}
return string(out), nil
}
// Export ...
func (c *svnclient) Export(dir string) error {
_, err := c.run("export", c.svnURL, dir)
if err != nil {
return err
}
return nil
}
// Log ...
func (c *svnclient) Log() (*Logs, error) {
out, err := c.run("log", "--xml", "-v")
if err != nil {
return nil, err
}
l := new(Logs)
err = xml.Unmarshal(out, l)
if err != nil {
return nil, err
}
return l, nil
}
// list ...
func (c *svnclient) List() (*lists, error) {
cmd := []string{"list", c.svnURL, "--xml"}
out, err := c.run(cmd...)
if err != nil {
return nil, err
}
l := new(lists)
err = xml.Unmarshal(out, l)
if err != nil {
return nil, err
}
return l, nil
}
func getBranchPath(branch, url string) string {
if strings.HasPrefix(branch, "trunk") {
return fmt.Sprintf("%s/%s", url, branch)
}
if strings.HasPrefix(branch, "tag:") {
return fmt.Sprintf("%s/tags/%s", url, branch[4:])
}
return fmt.Sprintf("%s/branches/%s", url, branch)
}
// Checkout
func (c *svnclient) Checkout() (*Info, error) {
//handle branch or tags
if c.csi.Branch != "" {
c.svnURL = getBranchPath(c.csi.Branch, c.svnURL)
}
if !util.DirIsEmpty(c.svnDir) {
os.RemoveAll(c.svnDir)
}
if err := os.MkdirAll(c.svnDir, 0755); err != nil {
return nil, err
}
cmd := []string{"checkout", c.svnURL}
if c.svnDir != "" {
cmd = append(cmd, c.svnDir)
}
_, err := c.runWithLogger(cmd...)
if err != nil {
//if trunk will change url retry
if strings.Contains(err.Error(), "svn:E170000") && c.csi.Branch == "trunk" {
c.svnURL = c.svnURL[:len(c.svnURL)-6]
cmd := []string{"checkout", c.svnURL}
if c.svnDir != "" {
cmd = append(cmd, c.svnDir)
}
_, err = c.runWithLogger(cmd...)
if err != nil {
return nil, err
}
} else {
return nil, err
}
}
return c.Info()
}
// Update
func (c *svnclient) Update(childpath string) (*Info, error) {
cmd := []string{"update", path.Join(c.svnDir, childpath)}
_, err := c.runWithLogger(cmd...)
if err != nil {
return nil, err
}
return c.Info()
}
func (c *svnclient) UpdateOrCheckout(childpath string) (*Info, error) {
var rs *Info
var err error
if ok := util.DirIsEmpty(c.svnDir); !ok {
//update BuildPath
rs, err = c.Update(childpath)
if err != nil {
logrus.Errorf("update svn code error: %s", err.Error())
c.logger.Error(fmt.Sprintf("Update svn code failed, please make sure the code can be downloaded properly"), map[string]string{"step": "builder-exector", "status": "failure"})
} else {
return rs, nil
}
}
rs, err = c.Checkout()
if err != nil {
logrus.Errorf("checkout svn code error: %s", err.Error())
c.logger.Error(fmt.Sprintf("Checkout svn code failed, please make sure the code can be downloaded properly"), map[string]string{"step": "builder-exector", "status": "failure"})
return nil, err
}
return rs, nil
}
// svnclient Checkout from specific revision
func (c *svnclient) CheckoutWithRevision(revision string) (string, error) {
cmd := []string{"checkout", c.svnURL}
if c.svnDir != "" {
cmd = append(cmd, c.svnDir)
}
cmd = append(cmd, "-r", revision)
out, err := c.run(cmd...)
if err != nil {
return "", err
}
return string(out), nil
}
// info ...
func (c *svnclient) Info() (*Info, error) {
start := time.Now()
cmd := []string{"info", "--xml"}
out, err := c.run(cmd...)
if err != nil {
return nil, err
}
info := new(Info)
err = xml.Unmarshal(out, info)
if err != nil {
return nil, err
}
log, err := c.Log()
if err == nil {
info.Logs = log
}
fmt.Println(time.Now().Sub(start).String())
info.Branchs = c.readBranchs()
info.Tags = c.readTags()
return info, nil
}
func (c *svnclient) readBranchs() []string {
re := []string{""}
exist, _ := util.FileExists(path.Join(c.svnDir, "Branches"))
if exist {
list, err := ioutil.ReadDir(path.Join(c.svnDir, "Branches"))
if err != nil {
return re
}
for _, f := range list {
re = append(re, f.Name())
}
return re
}
exist, _ = util.FileExists(path.Join(c.svnDir, "branches"))
if exist {
list, err := ioutil.ReadDir(path.Join(c.svnDir, "Branches"))
if err != nil {
return re
}
for _, f := range list {
re = append(re, f.Name())
}
return re
}
return re
}
func (c *svnclient) readTags() []string {
re := []string{}
exist, _ := util.FileExists(path.Join(c.svnDir, "Tags"))
if exist {
list, err := ioutil.ReadDir(path.Join(c.svnDir, "Tags"))
if err != nil {
return re
}
for _, f := range list {
re = append(re, f.Name())
}
return re
}
exist, _ = util.FileExists(path.Join(c.svnDir, "tags"))
if exist {
list, err := ioutil.ReadDir(path.Join(c.svnDir, "tags"))
if err != nil {
return re
}
for _, f := range list {
re = append(re, f.Name())
}
return re
}
return re
}
// run 运行命令
func (c *svnclient) runWithLogger(args ...string) ([]byte, error) {
ops := []string{"--username", c.username, "--password", c.password, "--non-interactive", "--trust-server-cert"}
args = append(args, ops...)
cmd := exec.Command("svn", args...)
if len(c.Env) > 0 {
cmd.Env = append(os.Environ(), c.Env...)
}
cmd.Dir = c.svnDir
writer := c.logger.GetWriter("progress", "debug")
writer.SetFormat(`{"progress":"%s","id":"SVN:"}`)
cmd.Stdout = writer
errorWriter := bytes.NewBuffer(nil)
cmd.Stderr = errorWriter
err := cmd.Run()
if err != nil {
if strings.Contains(errorWriter.String(), "doesn't exist") {
return nil, fmt.Errorf("svn:E170000")
}
return nil, fmt.Errorf("svn error:%s", errorWriter.String())
}
return nil, nil
}
// run 运行命令
func (c *svnclient) run(args ...string) ([]byte, error) {
ops := []string{"--username", c.username, "--password", c.password, "--non-interactive", "--trust-server-cert"}
args = append(args, ops...)
cmd := exec.Command("svn", args...)
if len(c.Env) > 0 {
cmd.Env = append(os.Environ(), c.Env...)
}
cmd.Dir = c.svnDir
return cmd.Output()
}
//Logs commit logs
type Logs struct {
XMLName xml.Name `xml:"log"`
CommitEntrys []Commit `xml:"logentry"`
}
type paths struct {
Path string `xml:",innerxml"`
Action string `xml:"action,attr"`
PropMods string `xml:"prop-mods,attr"`
TextMods string `xml:"text-mods,attr"`
Kind string `xml:"kind,attr"`
}
//Info Info
type Info struct {
XMLName xml.Name `xml:"info"`
URL string `xml:"entry>url"`
RelativeURL string `xml:"entry>relative-url"`
Root string `xml:"entry>repository>root"`
UUID string `xml:"entry>repository>uuid"`
WcrootAbspath string `xml:"entry>wc-info>wcroot-abspath"`
Schedule string `xml:"entry>wc-info>schedule"`
Depth string `xml:"entry>wc-info>depth"`
Logs *Logs
Branchs []string
Tags []string
}
//Commit Commit
type Commit struct {
Revision string `xml:"revision,attr"`
Author string `xml:"author"`
Msg string `xml:"msg"`
Date string `xml:"date"`
}
type lists struct {
XMLName xml.Name `xml:"lists"`
List list `xml:"list"`
}
type list struct {
Path string `xml:"path,attr"`
Entry []entry `xml:"entry"`
}
type entry struct {
Kind string `xml:"kind,attr"`
Name string `xml:"name"`
Size string `xml:"size"`
Commit Commit `xml:"commit"`
}