-
Notifications
You must be signed in to change notification settings - Fork 23
/
filewriter.go
182 lines (160 loc) · 4.9 KB
/
filewriter.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
package collector
import (
"encoding/json"
"io/ioutil"
"os"
"path/filepath"
"strings"
except "github.com/banyanops/collector/except"
fsutil "github.com/banyanops/collector/fsutil"
blog "github.com/ccpaging/log4go"
)
type ImageMetadataAndAction struct {
Action string
ImageMetadata []ImageMetadataInfo
}
type FileWriter struct {
format string
dir string
}
func NewFileWriter(format string, dir string) Writer {
if format == "" {
format = "json"
}
// format can be overwritten, hence the &
return &FileWriter{
format: format,
dir: dir,
}
}
// WriteImageAllData writes image (pkg and other) data into file
func (f *FileWriter) WriteImageAllData(outMapMap map[string]map[string]interface{}) {
blog.Info("Writing image (pkg and other) data into file...")
for imageID, scriptMap := range outMapMap {
for scriptName, out := range scriptMap {
scriptDir := f.dir + "/" + trimExtension(scriptName)
err := fsutil.CreateDirIfNotExist(scriptDir)
if err != nil {
except.Error(err, ": Error creating script dir: ", scriptDir)
continue
}
image := string(imageID)
minLen := 12
index := strings.Index(image, ":")
if index >= 0 {
minLen += index + 1
}
if len(image) < minLen {
except.Warn("Weird...Haven't seen imageIDs so small -- possibly a test?")
} else {
image = string(imageID)[0:minLen]
}
filenamePath := scriptDir + "/" + image
if _, ok := out.([]byte); ok {
f.format = "txt"
filenamePath += "-miscdata"
} else {
// by default it is json. But f.format could get overwritten at any point
// in the for loop if the output type is []byte, hence the (re)assignment
f.format = "json"
// NOTE: If we start using json for output other than imageData, change this
filenamePath += "-pkgdata"
}
f.writeFileInFormat(filenamePath, &out)
}
}
return
}
// AppendImageMetadata appends image metadata to file
func (f *FileWriter) AppendImageMetadata(imageMetadata []ImageMetadataInfo) {
blog.Info("Appending image metadata to file...")
f.format = "json"
f.handleImageMetadata(imageMetadata, "ADD")
}
// RemoveImageMetadata removes image metadata from file
func (f *FileWriter) RemoveImageMetadata(imageMetadata []ImageMetadataInfo) {
blog.Info("Removing image metadata from file...")
f.format = "json"
f.handleImageMetadata(imageMetadata, "REMOVE")
}
func (f *FileWriter) handleImageMetadata(imageMetadata []ImageMetadataInfo, action string) {
if len(imageMetadata) == 0 {
except.Warn("No image metadata to append to file...")
return
}
// If output directory does not exist, first create it
fsutil.CreateDirIfNotExist(f.dir)
filenamePath := f.dir + "/" + "metadata"
data := ImageMetadataAndAction{action, imageMetadata}
f.appendFileInFormat(filenamePath, data)
}
func jsonifyAndWriteToFile(filenamePath string, data interface{}) (err error) {
b, err := json.MarshalIndent(data, "", "\t")
if err != nil {
except.Error(err, ": Error in marshaling json")
return err
}
err = ioutil.WriteFile(filenamePath, b, 0644)
if err != nil {
except.Error(err, ": Error in writing to file: ", filenamePath)
return err
}
return nil
}
func (f *FileWriter) writeFileInFormat(filenamePath string, data interface{}) {
blog.Info("Writing " + filenamePath + "...")
switch f.format {
case "json":
err := jsonifyAndWriteToFile(filenamePath+".json", data)
if err != nil {
except.Error(err, ": Error in writing json output into file: ", filenamePath+".json")
return
}
case "txt":
// what's passed in is ptr to interface{}. First get interface{} out of it and then
// typecast that to []byte
err := ioutil.WriteFile(filenamePath+".txt", (*(data.(*interface{}))).([]byte), 0644)
if err != nil {
except.Error(err, ": Error in writing to file: ", filenamePath)
return
}
default:
except.Warn("Currently only supporting json output to write to files")
}
}
func trimExtension(nameExt string) (name string) {
extension := filepath.Ext(nameExt)
name = nameExt[0 : len(nameExt)-len(extension)]
return
}
func jsonifyAndAppendToFile(filenamePath string, data ImageMetadataAndAction) (err error) {
b, err := json.MarshalIndent(data, "", "\t")
if err != nil {
except.Error(err, ": Error in marshaling json")
return err
}
fd, err := os.OpenFile(filenamePath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
if err != nil {
except.Error(err, ": Error in opening file: ", filenamePath)
return err
}
defer fd.Close()
_, err = fd.Write(b)
if err != nil {
except.Error(err, ": Error in writing to file: ", filenamePath)
return err
}
return nil
}
func (f *FileWriter) appendFileInFormat(filenamePath string, data ImageMetadataAndAction) {
switch f.format {
case "json":
err := jsonifyAndAppendToFile(filenamePath+".json", data)
if err != nil {
except.Error(err, ": Error in writing json output into file: ", filenamePath+".json")
return
}
default:
except.Warn("Currently only supporting json output to write to files")
}
}