This repository has been archived by the owner on Aug 21, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlocal.go
99 lines (86 loc) · 2.27 KB
/
local.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
package storage
import (
"fmt";
"os";
"io";
"io/ioutil";
"path/filepath"
)
type localStorage struct {}
func NewLocal() Storage {
return &localStorage{}
}
func (s *localStorage) Exists(path string) (bool, error) {
if isWildcard(path) {
files, err := ioutil.ReadDir(filepath.Dir(path))
if err != nil {
return false, err
}
pattern := filepath.Base(path)
for _, file := range files {
match, err := filepath.Match(pattern, file.Name())
if err != nil {
return false, err
}
if match {
return true, nil
}
}
return false, nil
}
_, err := os.Stat(path)
return err == nil, nil
}
func (s *localStorage) ListFiles(path string) ([]string, error) {
exists, err := s.Exists(path)
if err != nil {
return nil, err
}
if !exists {
return nil, fmt.Errorf("Path `%s` does not exist", path)
}
if isWildcard(path) {
dirPath := filepath.Dir(path)
files, err := ioutil.ReadDir(dirPath)
if err != nil {
return nil, err
}
pattern := filepath.Base(path)
result := make([]string, 0)
for _, file := range files {
match, err := filepath.Match(pattern, file.Name())
if err != nil {
panic(err)
}
if match {
result = append(result, filepath.Join(dirPath, file.Name()))
}
}
return result, nil
}
fileInfo, err := os.Stat(path)
if err != nil {
return nil, err
}
if !fileInfo.IsDir() {
return []string{path}, nil
}
files, err := ioutil.ReadDir(path)
if err != nil {
return nil, err
}
result := make([]string, 0)
for _, file := range files {
result = append(result, filepath.Join(path, file.Name()))
}
return result,nil
}
func (s *localStorage) Reader(path string) (io.ReadCloser, error) {
return os.Open(path)
}
func (s *localStorage) Writer(path string) (io.WriteCloser, error) {
if err := os.MkdirAll(filepath.Dir(path), os.ModeDir); err != nil {
return nil, err
}
return os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0755)
}