forked from DHowett/go-plist
/
ply.go
395 lines (366 loc) · 9.25 KB
/
ply.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
package main
import (
"bufio"
"bytes"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"reflect"
"strconv"
"strings"
"github.com/jessevdk/go-flags"
"gopkg.in/yaml.v1"
"github.com/blacktop/go-plist"
)
//import "github.com/mgutz/ansi"
const (
PrettyFormat = 100 + iota
JSONFormat
YAMLFormat
RawFormat
)
var nameFormatMap = map[string]int{
"x": plist.XMLFormat,
"xml": plist.XMLFormat,
"xml1": plist.XMLFormat,
"b": plist.BinaryFormat,
"bin": plist.BinaryFormat,
"binary": plist.BinaryFormat,
"binary1": plist.BinaryFormat,
"o": plist.OpenStepFormat,
"os": plist.OpenStepFormat,
"openstep": plist.OpenStepFormat,
"step": plist.OpenStepFormat,
"g": plist.GNUStepFormat,
"gs": plist.GNUStepFormat,
"gnustep": plist.GNUStepFormat,
"pretty": PrettyFormat,
"json": JSONFormat,
"yaml": YAMLFormat,
"r": RawFormat,
"raw": RawFormat,
}
var opts struct {
Convert string `short:"c" long:"convert" description:"convert the property list to a new format (c=list for list)" default:"pretty" value-name:"<format>"`
Keypath string `short:"k" long:"key" description:"A keypath!" default:"/" value-name:"<keypath>"`
Output string `short:"o" long:"out" description:"output filename" default:"" value-name:"<filename>"`
Indent bool `short:"I" long:"indent" description:"indent indentable output formats (xml, openstep, gnustep, json)"`
}
func main() {
parser := flags.NewParser(&opts, flags.Default)
args, err := parser.Parse()
if err != nil {
// flags.Default implies flags.PrintError; there's no reason to print it here
return
}
if opts.Convert == "list" {
formats := make([]string, len(nameFormatMap))
i := 0
for k, _ := range nameFormatMap {
formats[i] = k
i++
}
fmt.Fprintln(os.Stderr, "Supported output formats:")
fmt.Fprintln(os.Stderr, strings.Join(formats, ", "))
return
}
if len(args) < 1 {
parser.WriteHelp(os.Stderr)
return
}
filename := args[0]
keypath := opts.Keypath
if len(keypath) == 0 {
c := strings.Index(filename, ":")
if c > -1 {
keypath = filename[c+1:]
filename = filename[:c]
}
}
file, err := os.Open(filename)
if err != nil {
fmt.Fprintln(os.Stderr, err.Error())
return
}
var val interface{}
switch strings.ToLower(filepath.Ext(filename)) {
case ".json", ".yaml", ".yml":
buf := &bytes.Buffer{}
io.Copy(buf, file)
err = yaml.Unmarshal(buf.Bytes(), &val)
default:
dec := plist.NewDecoder(file)
err = dec.Decode(&val)
}
if err != nil {
fmt.Fprintln(os.Stderr, err.Error())
return
}
file.Close()
convert := strings.ToLower(opts.Convert)
format, ok := nameFormatMap[convert]
if !ok {
fmt.Fprintf(os.Stderr, "unknown output format %s\n", convert)
return
}
output := opts.Output
newline := false
var outputStream io.WriteCloser
if format < PrettyFormat && output == "" {
// Writing a plist, but no output filename. Save to original.
output = filename
} else if format >= PrettyFormat && output == "" {
// Writing a non-plist, but no output filename: Stdout
outputStream = os.Stdout
newline = true
} else if output == "-" {
// - means stdout.
outputStream = os.Stdout
newline = true
}
if outputStream == nil {
outfile, err := os.Create(output)
if err != nil {
fmt.Fprintln(os.Stderr, err.Error())
return
}
outputStream = outfile
}
keypathContext := &KeypathWalker{}
rval, err := keypathContext.WalkKeypath(reflect.ValueOf(val), keypath)
if err != nil {
fmt.Fprintln(os.Stderr, err.Error())
return
}
val = rval.Interface()
switch {
case format >= 0 && format < PrettyFormat:
enc := plist.NewEncoderForFormat(outputStream, format)
if opts.Indent {
enc.Indent("\t")
}
err := enc.Encode(val)
if err != nil {
fmt.Fprintln(os.Stderr, err.Error())
return
}
case format == PrettyFormat:
PrettyPrint(outputStream, rval.Interface())
case format == JSONFormat:
var out []byte
var err error
if opts.Indent {
out, err = json.MarshalIndent(val, "", "\t")
} else {
out, err = json.Marshal(val)
}
if err != nil {
fmt.Fprintln(os.Stderr, err.Error())
return
}
outputStream.Write(out)
case format == YAMLFormat:
out, err := yaml.Marshal(val)
if err != nil {
fmt.Fprintln(os.Stderr, err.Error())
return
}
outputStream.Write(out)
case format == RawFormat:
newline = false
switch rval.Kind() {
case reflect.String:
outputStream.Write([]byte(val.(string)))
case reflect.Slice:
if rval.Elem().Kind() == reflect.Uint8 {
outputStream.Write(val.([]byte))
}
default:
binary.Write(outputStream, binary.LittleEndian, val)
}
}
if newline {
fmt.Fprintf(outputStream, "\n")
}
outputStream.Close()
}
type KeypathWalker struct {
rootVal *reflect.Value
curVal reflect.Value
}
func (ctx *KeypathWalker) Split(data []byte, atEOF bool) (advance int, token []byte, err error) {
mode, oldmode := 0, 0
depth := 0
tok, subexpr := "", ""
// modes:
// 0: normal string, separated by /
// 1: array index (reading between [])
// 2: found $, looking for ( or nothing
// 3: found $(, reading subkey, looking for )
// 4: "escape"? unused as yet.
if len(data) == 0 && atEOF {
return 0, nil, io.EOF
}
each:
for _, v := range data {
advance++
switch {
case mode == 4:
// Completing an escape sequence.
tok += string(v)
mode = 0
continue each
case mode == 0 && v == '/':
if tok != "" {
break each
} else {
continue each
}
case mode == 0 && v == '[':
if tok != "" {
// We have encountered a [ after text, we want only the text
advance-- // We don't want to consume this character.
break each
} else {
tok += string(v)
mode = 1
}
case mode == 1 && v == ']':
mode = 0
tok += string(v)
break each
case mode == 0 && v == '!':
if tok == "" {
tok = "!"
break each
} else {
// We have encountered a ! after text, we want the text
advance-- // We don't want to consume this character.
break each
}
case (mode == 0 || mode == 1) && v == '$':
oldmode = mode
mode = 2
case mode == 2:
if v == '(' {
mode = 3
depth++
subexpr = ""
} else {
// We didn't emit the $ to begin with, so we have to do it here.
tok += "$" + string(v)
mode = 0
}
case mode == 3 && v == '(':
subexpr += string(v)
depth++
case mode == 3 && v == ')':
depth--
if depth == 0 {
newCtx := &KeypathWalker{rootVal: ctx.rootVal}
subexprVal, e := newCtx.WalkKeypath(*ctx.rootVal, subexpr)
if e != nil {
return 0, nil, errors.New("Dynamic subexpression " + subexpr + " failed: " + e.Error())
}
if subexprVal.Kind() == reflect.Interface {
subexprVal = subexprVal.Elem()
}
s := ""
if subexprVal.Kind() == reflect.String {
s = subexprVal.String()
} else if subexprVal.Kind() == reflect.Uint64 {
s = strconv.Itoa(int(subexprVal.Uint()))
} else {
return 0, nil, errors.New("Dynamic subexpression " + subexpr + " evaluated to non-string/non-int.")
}
tok += s
mode = oldmode
} else {
subexpr += string(v)
}
case mode == 3:
subexpr += string(v)
default:
tok += string(v)
}
}
return advance, []byte(tok), nil
}
func (ctx *KeypathWalker) WalkKeypath(val reflect.Value, keypath string) (reflect.Value, error) {
if keypath == "" {
return val, nil
}
if ctx.rootVal == nil {
ctx.rootVal = &val
}
ctx.curVal = val
scanner := bufio.NewScanner(strings.NewReader(keypath))
scanner.Split(ctx.Split)
for scanner.Scan() {
token := scanner.Text()
if ctx.curVal.Kind() == reflect.Interface {
ctx.curVal = ctx.curVal.Elem()
}
switch {
case len(token) == 0:
continue
case token[0] == '[': // array
s := token[1 : len(token)-1]
if ctx.curVal.Kind() != reflect.Slice && ctx.curVal.Kind() != reflect.String {
return reflect.ValueOf(nil), errors.New("keypath attempted to index non-indexable with " + s)
}
colon := strings.Index(s, ":")
if colon > -1 {
var err error
var si, sj int
is := s[:colon]
js := s[colon+1:]
if is != "" {
si, err = strconv.Atoi(is)
if err != nil {
return reflect.ValueOf(nil), err
}
}
if js != "" {
sj, err = strconv.Atoi(js)
if err != nil {
return reflect.ValueOf(nil), err
}
}
if si < 0 || sj > ctx.curVal.Len() {
return reflect.ValueOf(nil), errors.New("keypath attempted to index outside of indexable with " + s)
}
ctx.curVal = ctx.curVal.Slice(si, sj)
} else {
idx, _ := strconv.Atoi(s)
ctx.curVal = ctx.curVal.Index(idx)
}
case token[0] == '!': // subplist!
if ctx.curVal.Kind() != reflect.Slice || ctx.curVal.Type().Elem().Kind() != reflect.Uint8 {
return reflect.Value{}, errors.New("Attempted to subplist non-data.")
}
byt := ctx.curVal.Interface().([]uint8)
buf := bytes.NewReader(byt)
dec := plist.NewDecoder(buf)
var subval interface{}
dec.Decode(&subval)
ctx.curVal = reflect.ValueOf(subval)
default: // just a string
if ctx.curVal.Kind() != reflect.Map {
return reflect.ValueOf(nil), errors.New("keypath attempted to descend into non-map using key " + token)
}
if token != "" {
ctx.curVal = ctx.curVal.MapIndex(reflect.ValueOf(token))
}
}
}
err := scanner.Err()
if err != nil {
return reflect.ValueOf(nil), err
}
return ctx.curVal, nil
}