-
Notifications
You must be signed in to change notification settings - Fork 2
/
fs_os.go
64 lines (57 loc) · 1.18 KB
/
fs_os.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
package main
import (
"errors"
"io"
"io/fs"
"os"
"path/filepath"
"strings"
)
type OS struct {
}
func (f OS) List(dir string) (file []Info, err error) {
dir = localize(dir)
u := uri(dir)
if dir == "-" {
return []Info{{URL: &u}}, nil
}
return file, filepath.Walk(dir, func(p string, info fs.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
u := u
u.Path = p
file = append(file, Info{URL: &u, Size: int(info.Size())})
}
return nil
})
}
func (f OS) Open(file string) (io.ReadCloser, error) {
file = localize(file)
if file == "-" {
return os.Stdin, nil
}
return os.Open(file)
}
func (f OS) Create(file string) (io.WriteCloser, error) {
file = localize(file)
if file == "-" {
// Invariant: users with files named "-" will not
// ruin it for the rest of us.
return os.Stdout, nil
}
w, err := os.Create(file)
if errors.Is(err, os.ErrNotExist) {
os.MkdirAll(filepath.Dir(file), 0777)
w, err = os.Create(file)
}
return w, err
}
func (f OS) Close() error { return nil }
func localize(file string) string {
if strings.HasPrefix(file, "file://") { // rooted prefix
return strings.TrimPrefix(file, "file://")
}
return file
}