-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
file.go
126 lines (106 loc) · 2.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
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
114
115
116
117
118
119
120
121
122
123
124
125
126
package packd
import (
"bytes"
"fmt"
"io"
"os"
"time"
)
var _ File = &virtualFile{}
var _ io.Reader = &virtualFile{}
var _ io.Writer = &virtualFile{}
var _ fmt.Stringer = &virtualFile{}
type virtualFile struct {
io.Reader
name string
info fileInfo
original []byte
}
func (f virtualFile) Name() string {
return f.name
}
func (f *virtualFile) Seek(offset int64, whence int) (int64, error) {
return f.Reader.(*bytes.Reader).Seek(offset, whence)
}
func (f virtualFile) FileInfo() (os.FileInfo, error) {
return f.info, nil
}
func (f *virtualFile) Close() error {
return nil
}
func (f virtualFile) Readdir(count int) ([]os.FileInfo, error) {
return []os.FileInfo{f.info}, nil
}
func (f virtualFile) Stat() (os.FileInfo, error) {
return f.info, nil
}
func (f virtualFile) String() string {
return string(f.original)
}
// Read reads the next len(p) bytes from the virtualFile and
// rewind read offset to 0 when it met EOF.
func (f *virtualFile) Read(p []byte) (int, error) {
i, err := f.Reader.Read(p)
if i == 0 || err == io.EOF {
f.Seek(0, io.SeekStart)
}
return i, err
}
// Write copies byte slice p to content of virtualFile.
func (f *virtualFile) Write(p []byte) (int, error) {
return f.write(p)
}
// write copies byte slice or data from io.Reader to content of the
// virtualFile and update related information of the virtualFile.
func (f *virtualFile) write(d interface{}) (c int, err error) {
bb := &bytes.Buffer{}
switch d.(type) {
case []byte:
c, err = bb.Write(d.([]byte))
case io.Reader:
if d != nil {
i64, e := io.Copy(bb, d.(io.Reader))
c = int(i64)
err = e
}
default:
err = fmt.Errorf("unknown type of argument")
}
if err != nil {
return c, err
}
f.info.size = int64(c)
f.info.modTime = time.Now()
f.original = bb.Bytes()
f.Reader = bytes.NewReader(f.original)
return c, nil
}
// NewFile returns a new "virtual" file
func NewFile(name string, r io.Reader) (File, error) {
return buildFile(name, r)
}
// NewDir returns a new "virtual" directory
func NewDir(name string) (File, error) {
v, err := buildFile(name, nil)
if err != nil {
return v, err
}
v.info.isDir = true
return v, nil
}
func buildFile(name string, r io.Reader) (*virtualFile, error) {
vf := &virtualFile{
name: name,
info: fileInfo{
Path: name,
modTime: time.Now(),
},
}
var err error
if r != nil {
_, err = vf.write(r)
} else {
_, err = vf.write([]byte{}) // for safety
}
return vf, err
}