2 ==================================================================================
3 Copyright (c) 2019 AT&T Intellectual Property.
4 Copyright (c) 2019 Nokia
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
10 http://www.apache.org/licenses/LICENSE-2.0
12 Unless required by applicable law or agreed to in writing, software
13 distributed under the License is distributed on an "AS IS" BASIS,
14 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 See the License for the specific language governing permissions and
16 limitations under the License.
17 ==================================================================================
36 func NewUtils() *Utils {
37 b := Config.GetString("controls.symptomdata.baseDir")
39 b = "/tmp/symptomdata/"
47 func (u *Utils) FileExists(f string) bool {
49 return err == nil || os.IsExist(err)
52 func (u *Utils) CreateDir(path string) error {
53 if u.FileExists(path) {
56 err := os.MkdirAll(path, os.ModePerm)
60 os.Chmod(path, os.ModePerm)
64 func (u *Utils) DeleteFile(fileName string) {
68 func (u *Utils) AddFileToZip(zipWriter *zip.Writer, filePath string, filename string) error {
69 fileToZip, err := os.Open(filename)
73 defer fileToZip.Close()
75 info, err := fileToZip.Stat()
80 header, err := zip.FileInfoHeader(info)
85 if strings.HasPrefix(filename, filePath) {
86 filename = strings.TrimPrefix(filename, filePath)
88 header.Name = filename
89 header.Method = zip.Deflate
91 writer, err := zipWriter.CreateHeader(header)
96 _, err = io.Copy(writer, fileToZip)
101 func (u *Utils) ZipFiles(newZipFile *os.File, filePath string, files []string) error {
102 defer newZipFile.Close()
103 zipWriter := zip.NewWriter(newZipFile)
104 defer zipWriter.Close()
105 for _, file := range files {
106 if err := u.AddFileToZip(zipWriter, filePath, file); err != nil {
107 Logger.Error("AddFileToZip() failed: %+v", err.Error())
115 func (u *Utils) FetchFiles(filePath string, fileList []string) []string {
116 files, err := ioutil.ReadDir(filePath)
118 Logger.Error("ioutil.ReadDir failed: %+v", err)
121 for _, file := range files {
123 fileList = append(fileList, filepath.Join(filePath, file.Name()))
125 subPath := filepath.Join(filePath, file.Name())
126 subFiles, _ := ioutil.ReadDir(subPath)
127 for _, subFile := range subFiles {
128 if !subFile.IsDir() {
129 fileList = append(fileList, filepath.Join(subPath, subFile.Name()))
131 fileList = u.FetchFiles(filepath.Join(subPath, subFile.Name()), fileList)
139 func (u *Utils) WriteToFile(fileName string, data string) error {
140 f, err := os.Create(fileName)
144 Logger.Error("Unable to create file %s': %+v", fileName, err)
146 _, err := io.WriteString(f, data)
148 Logger.Error("Unable to write to file '%s': %+v", fileName, err)
149 u.DeleteFile(fileName)