-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile.go
85 lines (75 loc) · 1.42 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
package iokit
import (
"io"
"os"
"path/filepath"
"strings"
"go4ml.xyz/errstr"
)
func File(path string) StrictInputOutput {
return StrictInputOutput{file(path)}
}
type file string
func expand(path string) (string, error) {
if len(path) > 0 && path[0] == '$' {
j := strings.IndexRune(path, '/')
e := strings.ToLower(path[1:j])
found := false
for _, ev := range os.Environ() {
k := strings.IndexRune(ev, '=')
if k > 0 {
ex := strings.ToLower(ev[:k])
if ex == e {
path = ev[k+1:] + path[j:]
found = true
break
}
}
}
if !found {
return "", errstr.New("can't expand path `" + path + "`")
}
}
return path, nil
}
func (f file) Open() (io.ReadCloser, error) {
path, err := expand(string(f))
if err != nil {
return nil, err
}
return os.Open(path)
}
func (f file) Create() (Whole, error) {
path, err := expand(string(f))
if err != nil {
return nil, err
}
dir, _ := filepath.Split(path)
if dir != "" {
if err := os.MkdirAll(dir, 0755); err != nil {
return nil, err
}
}
x, err := os.Create(path)
if err != nil {
return nil, err
}
return &whole{regular{x}}, nil
}
type regular struct {
*os.File
}
func (f regular) Reset() error {
_, err := f.File.Seek(0, 0)
return err
}
func (f regular) Size() int64 {
st, _ := f.File.Stat()
return st.Size()
}
func (f regular) Fail() {
fname := f.File.Name()
_ = f.File.Truncate(0)
_ = f.File.Close()
_ = os.Remove(fname)
}