-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
file.go
113 lines (96 loc) · 2.15 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package main
import (
"encoding/csv"
"fmt"
"io"
"io/fs"
"os"
"github.com/gocarina/gocsv"
)
// load CSV into target data structure. target is modified
func loadCSV(fileName string, target interface{}) error {
file, err := os.OpenFile(fileName, os.O_RDONLY, 0644)
if err != nil {
return err
}
defer file.Close()
return gocsv.UnmarshalFile(file, target)
}
func saveCSV(filename string, data interface{}) error {
file, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return err
}
defer file.Close()
return gocsv.MarshalFile(data, file)
}
// findDir recursively searches the directory tree for a directory name. This skips soft links.
func findDir(name string) (string, error) {
retPath := ""
// WalkDir does not follown symbolic links
err := fs.WalkDir(os.DirFS("./"), ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
if name == d.Name() {
// found it
retPath = path
}
}
return nil
})
if err != nil {
return "", err
}
if retPath == "" {
return retPath, fmt.Errorf("Dir not found: %v", name)
}
return retPath, nil
}
// findFile recursively searches the directory tree to find a file and returns the path
func findFile(name string) (string, error) {
retPath := ""
// WalkDir does not follown symbolic links
err := fs.WalkDir(os.DirFS("./"), ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if !d.IsDir() {
if name == d.Name() {
// found it
retPath = path
}
}
return nil
})
if err != nil {
return "", err
}
if retPath == "" {
return retPath, fmt.Errorf("File not found: %v", name)
}
return retPath, nil
}
func initCSV() {
gocsv.SetCSVReader(func(in io.Reader) gocsv.CSVReader {
r := csv.NewReader(in)
r.Comma = ';'
return r
})
gocsv.SetCSVWriter(func(out io.Writer) *gocsv.SafeCSVWriter {
writer := csv.NewWriter(out)
writer.Comma = ';'
return gocsv.NewSafeCSVWriter(writer)
})
}
func exists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}