/
file.go
70 lines (60 loc) · 1.47 KB
/
file.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
// Copyright 2018 Shinichi MOTOKI. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"encoding/json"
"strings"
toml "github.com/pelletier/go-toml"
"github.com/pkg/errors"
"gopkg.in/yaml.v2"
)
func blobToObject(fileType string, blob []byte) (object interface{}, err error) {
switch fileType {
case "TOML":
t, e := toml.LoadBytes(blob)
if e != nil {
return nil, e
}
object = t.ToMap()
case "YAML":
m := map[string]interface{}{}
e := yaml.Unmarshal(blob, &m)
if e != nil {
return nil, e
}
object = m
case "JSON":
m := map[string]interface{}{}
e := json.Unmarshal(blob, &m)
if e != nil {
return nil, e
}
object = m
case "TEXT":
object = string(blob)
case "STRING":
object = strings.TrimSpace(string(blob))
case "RAW":
object = blob
default:
return nil, errors.Errorf("%s is unknown type", fileType)
}
return object, nil
}
func getFileObject(s string, defaultFileType string) (fileType string, filePath string, object interface{}, err error) {
f := fileArg(s)
fileType, filePath = f.parse()
blob, err := f.blob()
if err != nil {
return fileType, filePath, nil, err
}
if fileType == "" {
fileType = defaultFileType
}
object, err = blobToObject(fileType, blob)
if err != nil {
return fileType, filePath, nil, err
}
return fileType, filePath, object, err
}