-
Notifications
You must be signed in to change notification settings - Fork 7
/
file.go
56 lines (46 loc) · 1.48 KB
/
file.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
package utils
import (
"errors"
"github.com/PxyUp/fitter/pkg/logger"
"os"
"path"
)
var (
ErrMissingFileName = errors.New("missing file name")
)
func CreateFileWithContent(content []byte, destinationFileName string, destinationPath string, mode os.FileMode, append bool, logger logger.Logger) (string, error) {
if destinationFileName == "" {
return "", ErrMissingFileName
}
localDest := path.Join(destinationPath, destinationFileName)
logger.Debugw("storing file", "path", localDest)
if _, errDir := os.Stat(destinationPath); os.IsNotExist(errDir) {
errCreationOfDir := os.MkdirAll(destinationPath, os.ModePerm)
if errCreationOfDir != nil {
logger.Errorw("unable to create directory", "path", destinationPath, "error", errCreationOfDir.Error())
return "", errCreationOfDir
}
}
if append {
file, errFile := os.OpenFile(localDest, os.O_APPEND|os.O_WRONLY|os.O_CREATE, mode)
if errFile != nil {
logger.Errorw("unable to open local file", "dest", localDest, "error", errFile.Error())
return "", errFile
}
defer func() {
_ = file.Close()
}()
_, errWrite := file.Write(content)
if errWrite != nil {
logger.Errorw("unable to append content to local file", "dest", localDest, "error", errWrite.Error())
return "", errWrite
}
return localDest, nil
}
err := os.WriteFile(localDest, content, mode)
if err != nil {
logger.Errorw("unable to write content to local file", "dest", localDest, "error", err.Error())
return "", err
}
return localDest, nil
}