/
filesys.go
85 lines (66 loc) · 1.63 KB
/
filesys.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
package filesys
import (
"fmt"
"go/format"
"os"
"path/filepath"
"strings"
)
// FormatAndSaveGoFile saves go file at folder dir, with name fileName and contents text.
func FormatAndSaveGoFile(dirPath, fileName string, text []byte) error {
newGoFilePath := filepath.Join(dirPath, fileName)
if !strings.HasSuffix(newGoFilePath, ".go") {
newGoFilePath += ".go"
}
file, err := os.Create(newGoFilePath)
if err != nil {
return err
}
defer file.Close()
p, err := format.Source(text)
// if there is a format error we will write unformulated text for debug purposes
if err != nil {
file.Write(text)
return fmt.Errorf("failed to format '%s', check '%s' for syntax errors: %w", fileName, newGoFilePath, err)
}
_, err = file.Write(p)
if err != nil {
return fmt.Errorf("failed to save '%s' file: %w", newGoFilePath, err)
}
return nil
}
// EnsureDirPathExist ensures dir path exists. If path does not exist, creates new path.
func EnsureDirPathExist(dirPath string) error {
if _, err := os.Stat(dirPath); os.IsNotExist(err) {
err := os.MkdirAll(dirPath, os.ModePerm)
if err != nil {
return fmt.Errorf("can't create directory - %s: %w", dirPath, err)
}
}
return nil
}
// RemoveDir deletes everything at folder dir.
func RemoveDir(dir string) error {
exist, err := DirExists(dir)
if err != nil {
return err
}
if exist {
err := os.RemoveAll(dir)
if err != nil {
return err
}
}
return nil
}
// DirExists checks if folder at path exist.
func DirExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return true, err
}