This repository has been archived by the owner on Jan 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
file_util.go
61 lines (53 loc) · 1.28 KB
/
file_util.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
package main
import (
"fmt"
"io"
"os"
"path/filepath"
"github.com/rs/zerolog/log"
)
// Exists is a basic file util that says if a dir or file exists
func Exists(path string) bool {
_, err := os.Stat(path)
return !os.IsNotExist(err)
}
// EnsureDir checks if a dir exists and creates it if it does not exsits
func EnsureDir(dir string) error {
if !Exists(dir) {
err := os.Mkdir(dir, 0750)
if err != nil {
return fmt.Errorf("error creating directory %v : %w", dir, err)
}
}
return nil
}
// CopyFile copies filename src to dst
func CopyFile(src, dst string) error {
filePath := filepath.Clean(src)
in, err := os.Open(filePath)
if err != nil {
return fmt.Errorf("error opening file: %v : %w", src, err)
}
defer func() {
err := in.Close()
if err != nil {
log.Error().Err(err).Str("filename", filePath).Msg("error closing the file")
}
}()
// DST FILE
filePath = filepath.Clean(dst)
out, err := os.Create(filePath)
if err != nil {
return fmt.Errorf("error creating file: %v : %w", src, err)
}
defer func() {
err := out.Close()
if err != nil {
log.Error().Err(err).Str("filename", filePath).Msg("error closing the file")
}
}()
if _, err = io.Copy(out, in); err != nil {
return fmt.Errorf("error copying %v to %v : %w", src, dst, err)
}
return nil
}