-
Notifications
You must be signed in to change notification settings - Fork 1
/
file.go
executable file
·88 lines (76 loc) · 1.66 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
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
86
87
88
package gomvc
import (
"bufio"
"fmt"
"io"
"log"
"os"
"github.com/pkg/errors"
)
// CreateFileFromString takes a filepath as the destination of the file
// to be created as well as the contents to be written to this file.
func CreateFileFromString(filepath string, contents string) error {
f, err := os.Create(filepath)
if err != nil {
return errors.Wrap(err, "CreateFileFromString: os.Create error")
}
w := bufio.NewWriter(f)
_, err = w.WriteString(contents)
w.Flush()
if err != nil {
return errors.Wrap(err, "CreateFileFromString: write string error")
}
return nil
}
func createStringFromFile(filePath string) string {
content, err := os.ReadFile(filePath)
if err != nil {
log.Fatal(err)
}
return string(content)
}
// Copy the src file to dst. Any existing file will be overwritten and will not
// copy file attributes.
// https://stackoverflow.com/questions/21060945/simple-way-to-copy-a-file-in-golang
func Copy(src, dst string) error {
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
out, err := os.Create(dst)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, in)
if err != nil {
return err
}
return out.Close()
}
func createDirIfNotExists(dir string) {
if !dirExists(dir) {
if err := os.Mkdir(dir, os.ModePerm); err != nil {
panic(err)
}
log.Printf("created %s\n", dir)
}
}
func dirExists(path string) bool {
i, err := os.Stat(path)
if os.IsNotExist(err) {
return false
}
return i.IsDir()
}
func fileExists(path string) bool {
i, err := os.Stat(path)
if os.IsNotExist(err) {
return false
}
return !i.IsDir()
}
func addGoExt(s string) string {
return fmt.Sprintf("%s.go", s)
}