vuln-list-update/utils/fs.go

34 lines
732 B
Go
Raw Normal View History

2019-11-03 21:28:28 +03:00
package utils
import (
"encoding/json"
"os"
"path/filepath"
2019-11-03 21:28:28 +03:00
"github.com/spf13/afero"
"golang.org/x/xerrors"
2019-11-03 21:28:28 +03:00
)
func WriteJSON(fs afero.Fs, dir, fileName string, data interface{}) error {
if err := fs.MkdirAll(dir, os.ModePerm); err != nil {
return xerrors.Errorf("unable to create a directory: %w", err)
}
2019-11-03 21:28:28 +03:00
filePath := filepath.Join(dir, fileName)
f, err := fs.Create(filePath)
2019-11-03 21:28:28 +03:00
if err != nil {
return xerrors.Errorf("unable to open %s: %w", filePath, err)
2019-11-03 21:28:28 +03:00
}
defer f.Close()
b, err := json.MarshalIndent(data, "", " ")
if err != nil {
return xerrors.Errorf("failed to marshal JSON: %w", err)
}
if _, err = f.Write(b); err != nil {
return xerrors.Errorf("failed to save a file: %w", err)
}
return nil
}