forked from fujiwara/lambroll
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
51 lines (45 loc) · 1.09 KB
/
utils.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
package lambroll
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"strings"
"github.com/Songmu/prompter"
"github.com/aws/aws-sdk-go/private/protocol/json/jsonutil"
)
func (app *App) saveFile(path string, b []byte, mode os.FileMode) error {
if _, err := os.Stat(path); err == nil {
ok := prompter.YN(fmt.Sprintf("Overwrite existing file %s?", path), false)
if !ok {
return nil
}
}
return ioutil.WriteFile(path, b, mode)
}
func marshalJSON(s interface{}) ([]byte, error) {
var buf bytes.Buffer
b, err := jsonutil.BuildJSON(s)
if err != nil {
return nil, err
}
json.Indent(&buf, b, "", " ")
buf.WriteString("\n")
return buf.Bytes(), nil
}
func unmarshalJSON(src []byte, v interface{}, path string) error {
strict := json.NewDecoder(bytes.NewReader(src))
strict.DisallowUnknownFields()
if err := strict.Decode(&v); err != nil {
if !strings.Contains(err.Error(), "unknown field") {
return err
}
log.Printf("[warn] %s in %s", err, path)
// unknown field -> try lax decoder
lax := json.NewDecoder(bytes.NewReader(src))
return lax.Decode(&v)
}
return nil
}