-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
104 lines (88 loc) · 1.95 KB
/
main.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
package main
import (
"bufio"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
)
const (
Prefix = ".json"
Info = "info"
Item = "item"
Event = "event"
Script = "script"
ScriptID = "id"
PostmanID = "_postman_id"
CollectionDir = "POSTMAN_COLLECTION_DIR"
)
func main() {
fileDir := os.Getenv(CollectionDir)
if fileDir == "" {
err := fmt.Errorf(`ERROR: no environment variables are set "%s"`, CollectionDir)
panic(err)
}
files, err := ioutil.ReadDir(fileDir)
if err != nil {
panic(err)
}
for _, file := range files {
if ex := filepath.Ext(file.Name()); ex == Prefix {
if err := formatPostManFile(filepath.Join(fileDir, file.Name())); err != nil {
panic(err)
}
}
}
}
func formatPostManFile(filePath string) error {
// read json file
bytes, err := ioutil.ReadFile(filePath)
if err != nil {
return err
}
// decode to json
var decodeData map[string]interface{}
if err := json.Unmarshal(bytes, &decodeData); err != nil {
return err
}
// delete _postman_id
if info, ok := decodeData[Info]; ok {
delete(info.(map[string]interface{}), PostmanID)
}
// delete script id
deleteScriptIDFromItem(decodeData)
// convert json to byte
b, err := json.MarshalIndent(decodeData, "", "\t")
if err != nil {
return err
}
// write json file
fp, err := os.Create(filePath)
if err != nil {
return err
}
defer fp.Close()
writer := bufio.NewWriter(fp)
if _, err := writer.Write(b); err != nil {
return err
}
if err := writer.Flush(); err != nil {
return err
}
return nil
}
func deleteScriptIDFromItem(data map[string]interface{}) {
if event, ok := data[Event]; ok {
for _, e := range event.([]interface{}) {
if script, ok := e.(map[string]interface{})[Script]; ok {
delete(script.(map[string]interface{}), ScriptID)
}
}
}
if item, ok := data[Item]; ok {
for _, i := range item.([]interface{}) {
deleteScriptIDFromItem(i.(map[string]interface{}))
}
}
}