-
Notifications
You must be signed in to change notification settings - Fork 1
/
file.go
53 lines (44 loc) · 976 Bytes
/
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
package commit
import (
"errors"
"fmt"
"io"
"io/fs"
"os"
"path"
"strings"
)
func FileOpen() func(string) (io.Reader, error) {
return func(file string) (io.Reader, error) {
var pathError *fs.PathError
fh, err := os.Open(os.ExpandEnv(file))
switch {
case err == nil:
case errors.As(err, &pathError):
return strings.NewReader(""), nil
default:
return nil, fmt.Errorf("unable to open file: %w", err)
}
return fh, nil
}
}
func FileCreate() func(string) (io.WriteCloser, error) {
return func(file string) (io.WriteCloser, error) {
err := os.MkdirAll(path.Dir(os.ExpandEnv(file)), 0o755)
switch {
case err == nil:
case os.IsExist(err):
default:
return nil, err
}
fh, err := os.Create(os.ExpandEnv(file))
if err != nil {
return nil, fmt.Errorf("unable to create file: %w", err)
}
return fh, nil
}
}
func FileExists(file string) bool {
_, err := os.Stat(os.ExpandEnv(file))
return !errors.Is(err, os.ErrNotExist)
}