-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathp4.go
435 lines (389 loc) · 9.34 KB
/
p4.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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
/*
Package p4 wraps the Perforce Helix Core command line.
It assumes p4 or p4.exe is in the PATH.
It uses the p4 -G global option which returns Python marshalled dictionary objects.
p4 Python parsing module is based on: https://github.com/hambster/gopymarshal
*/
package p4
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"log"
"os/exec"
"regexp"
"strings"
"encoding/binary"
"errors"
"math"
)
// Parsing constants
const (
codeNone = 'N' //None
codeInt = 'i' //integer
codeInt2 = 'c' //integer2
codeFloat = 'g' //float
codeString = 's' //string
codeUnicode = 'u' //unicode string
codeTString = 't' //tstring?
codeTuple = '(' //tuple
codeList = '[' //list
codeDict = '{' //dict
codeStop = '0'
codeEnd = 0 //end of the object
dictInitSize = 64
)
// Parse error
var (
ErrParse = errors.New("invalid data")
ErrUnknownCode = errors.New("unknown code")
)
// Unmarshal data serialized by python
func Unmarshal(buffer *bytes.Buffer) (ret interface{}, retErr error) {
ret, _, retErr = Unmarshal2(buffer)
return
}
// Unmarshal2 data serialized by python, returning the unused portion.
func Unmarshal2(buffer *bytes.Buffer) (ret interface{}, remainder []byte, retErr error) {
code, err := buffer.ReadByte()
if nil != err {
retErr = err
}
ret, retErr = unmarshal(code, buffer)
remainder = buffer.Bytes()
return
}
func unmarshal(code byte, buffer *bytes.Buffer) (ret interface{}, retErr error) {
switch code {
case codeNone:
ret = nil
case codeInt:
fallthrough
case codeInt2:
ret, retErr = readInt32(buffer)
case codeFloat:
ret, retErr = readFloat64(buffer)
case codeString:
fallthrough
case codeUnicode:
fallthrough
case codeTString:
ret, retErr = readString(buffer)
case codeTuple:
fallthrough
case codeList:
ret, retErr = readList(buffer)
case codeDict:
ret, retErr = readDict(buffer)
case codeEnd:
ret, retErr = nil, nil
default:
retErr = ErrUnknownCode
}
return
}
func readInt32(buffer *bytes.Buffer) (ret int32, retErr error) {
var tmp int32
retErr = ErrParse
if retErr = binary.Read(buffer, binary.LittleEndian, &tmp); nil == retErr {
ret = tmp
}
return
}
func readFloat64(buffer *bytes.Buffer) (ret float64, retErr error) {
retErr = ErrParse
tmp := make([]byte, 8)
if num, err := buffer.Read(tmp); nil == err && 8 == num {
bits := binary.LittleEndian.Uint64(tmp)
ret = math.Float64frombits(bits)
retErr = nil
}
return
}
func readString(buffer *bytes.Buffer) (ret string, retErr error) {
var strLen int32
strLen = 0
retErr = ErrParse
if err := binary.Read(buffer, binary.LittleEndian, &strLen); nil != err {
retErr = err
return
}
retErr = nil
buf := make([]byte, strLen)
buffer.Read(buf)
ret = string(buf)
return
}
func readList(buffer *bytes.Buffer) (ret []interface{}, retErr error) {
var listSize int32
if retErr = binary.Read(buffer, binary.LittleEndian, &listSize); nil != retErr {
return
}
var code byte
var err error
var val interface{}
ret = make([]interface{}, int(listSize))
for idx := 0; idx < int(listSize); idx++ {
code, err = buffer.ReadByte()
if nil != err {
break
}
val, err = unmarshal(code, buffer)
if nil != err {
retErr = err
break
}
ret = append(ret, val)
} //end of read loop
return
}
func readDict(buffer *bytes.Buffer) (ret map[interface{}]interface{}, retErr error) {
var code byte
var err error
var key interface{}
var val interface{}
ret = make(map[interface{}]interface{})
for {
code, err = buffer.ReadByte()
if nil != err {
break
}
if code == codeStop {
break
}
key, err = unmarshal(code, buffer)
if nil != err {
retErr = err
break
}
code, err = buffer.ReadByte()
if nil != err {
break
}
val, err = unmarshal(code, buffer)
if nil != err {
retErr = err
break
}
ret[key] = val
} //end of read loop
return
}
// P4 - environment for P4
type P4 struct {
port string
user string
client string
}
// NewP4 - create and initialise properly
func NewP4() *P4 {
var p4 P4
return &p4
}
// NewP4Params - create and initialise with params
func NewP4Params(port string, user string, client string) *P4 {
var p4 P4
p4.port = port
p4.user = user
p4.client = client
return &p4
}
// RunBytes - runs p4 command and returns []byte output
func (p4 *P4) RunBytes(args []string) ([]byte, error) {
cmd := exec.Command("p4", args...)
data, err := cmd.CombinedOutput()
if err != nil {
return data, err
}
return data, nil
}
// Get options that go before the p4 command
func (p4 *P4) getOptions() []string {
opts := []string{"-G"}
if p4.port != "" {
opts = append(opts, "-p", p4.port)
}
if p4.user != "" {
opts = append(opts, "-u", p4.user)
}
if p4.client != "" {
opts = append(opts, "-c", p4.client)
}
return opts
}
// Get options that go before the p4 command
func (p4 *P4) getOptionsNonMarshal() []string {
opts := []string{}
if p4.port != "" {
opts = append(opts, "-p", p4.port)
}
if p4.user != "" {
opts = append(opts, "-u", p4.user)
}
if p4.client != "" {
opts = append(opts, "-c", p4.client)
}
return opts
}
// Runner is an interface to make testing p4 commands more easily
type Runner interface {
Run([]string) ([]map[interface{}]interface{}, error)
}
// Run - runs p4 command and returns map
func (p4 *P4) Run(args []string) ([]map[interface{}]interface{}, error) {
opts := p4.getOptions()
args = append(opts, args...)
cmd := exec.Command("p4", args...)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
mainerr := cmd.Run()
// May not be the correct place to do this
// But we are ignoring the actual error otherwise
if stderr.Len() > 0 {
return nil, errors.New(stderr.String())
}
results := make([]map[interface{}]interface{}, 0)
for {
r, err := Unmarshal(&stdout)
if err == io.EOF {
break
}
if err == nil {
if r == nil {
// End of object
break
}
results = append(results, r.(map[interface{}]interface{}))
} else {
if mainerr == nil {
mainerr = err
}
break
}
}
return results, mainerr
}
// parseError turns perforce error messages into go error's
func parseError(res map[interface{}]interface{}) error {
var err error
var e string
if v, ok := res["data"]; ok {
e = v.(string)
} else {
// I don't know if we can get in this situation
e = fmt.Sprintf("Failed to parse error %v", err)
return errors.New(e)
}
// Search for non-existent depot error
nodepot, err := regexp.Match(`must refer to client`, []byte(e))
if err != nil {
return err // Do we need to return (error, error) for real error and parsed one?
}
if nodepot {
path := strings.Split(e, " - must")[0]
return errors.New("P4Error -> No such area '" + path + "', please check your path")
}
err = fmt.Errorf("P4Error -> %s", e)
return err
}
// Assume multiline entries should be on seperate lines
func formatSpec(specContents map[string]string) string {
var output bytes.Buffer
for k, v := range specContents {
if strings.Index(v, "\n") > -1 {
output.WriteString(fmt.Sprintf("%s:", k))
lines := strings.Split(v, "\n")
for i := range lines {
if len(strings.TrimSpace(lines[i])) > 0 {
output.WriteString(fmt.Sprintf("\n %s", lines[i]))
}
}
output.WriteString("\n\n")
} else {
output.WriteString(fmt.Sprintf("%s: %s\n\n", k, v))
}
}
return output.String()
}
// Save - runs p4 -i for specified spec returns result
func (p4 *P4) Save(specName string, specContents map[string]string, args []string) ([]map[interface{}]interface{}, error) {
opts := p4.getOptions()
nargs := []string{specName, "-i"}
nargs = append(nargs, args...)
args = append(opts, nargs...)
log.Println(args)
cmd := exec.Command("p4", args...)
var stdout, stderr bytes.Buffer
stdin, err := cmd.StdinPipe()
if err != nil {
fmt.Println("An error occured: ", err)
}
cmd.Stdout = &stdout
cmd.Stderr = &stderr
mainerr := cmd.Start()
if mainerr != nil {
fmt.Println("An error occured: ", mainerr)
}
spec := formatSpec(specContents)
log.Println(spec)
io.WriteString(stdin, spec)
stdin.Close()
cmd.Wait()
results := make([]map[interface{}]interface{}, 0)
for {
r, err := Unmarshal(&stdout)
if err == io.EOF || r == nil {
break
}
if err == nil {
results = append(results, r.(map[interface{}]interface{}))
fmt.Println(r)
} else {
if mainerr == nil {
mainerr = err
}
break
}
}
return results, mainerr
}
// The Save() func doesn't work as it needs the data marshalled instead of
// map[string]string
// This is a quick fix, the real fix is writing a marshal() function or try
// using gopymarshal
func (p4 *P4) SaveTxt(specName string, specContents map[string]string, args []string) (string, error) {
opts := p4.getOptionsNonMarshal()
nargs := []string{specName, "-i"}
nargs = append(nargs, args...)
args = append(opts, nargs...)
log.Println(args)
cmd := exec.Command("p4", args...)
var stdout, stderr bytes.Buffer
stdin, err := cmd.StdinPipe()
if err != nil {
fmt.Println("An error occured: ", err)
}
cmd.Stdout = &stdout
cmd.Stderr = &stderr
mainerr := cmd.Start()
if mainerr != nil {
fmt.Println("An error occured: ", mainerr)
}
spec := formatSpec(specContents)
log.Println(spec)
io.WriteString(stdin, spec)
// Need to explicitly call this for the command to fire
stdin.Close()
cmd.Wait()
e, err := ioutil.ReadAll(&stderr)
log.Println(e)
if len(e) > 0 {
return "", errors.New(string(e))
}
x, err := ioutil.ReadAll(&stdout)
s := string(x)
log.Println(s)
return s, mainerr
}