-
Notifications
You must be signed in to change notification settings - Fork 5
/
file.go
147 lines (130 loc) · 2.39 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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
package main
import (
"bytes"
"errors"
"fmt"
"io"
"os"
"strconv"
"time"
)
// Turn Go types into files
type fakefile struct {
v interface{}
offset int64
set func(s string)
}
func (f *fakefile) ReadAt(p []byte, off int64) (int, error) {
var s string
if v, ok := f.v.(fmt.Stringer); ok {
s = v.String()
} else {
s = fmt.Sprint(f.v)
}
if off > int64(len(s)) {
return 0, io.EOF
}
n := copy(p, s)
return n, nil
}
func (f *fakefile) WriteAt(p []byte, off int64) (int, error) {
buf, ok := f.v.(*bytes.Buffer)
if !ok {
return 0, errors.New("not supported")
}
if off != f.offset {
return 0, errors.New("no seeking")
}
n, err := buf.Write(p)
f.offset += int64(n)
return n, err
}
func (f *fakefile) Close() error {
if f.set != nil {
f.set(fmt.Sprint(f.v))
}
return nil
}
func (f *fakefile) size() int64 {
switch f.v.(type) {
case map[string]interface{}, []interface{}:
return 0
}
return int64(len(fmt.Sprint(f.v)))
}
type stat struct {
name string
file *fakefile
}
func (s *stat) Name() string { return s.name }
func (s *stat) Sys() interface{} { return s.file }
func (s *stat) ModTime() time.Time {
return time.Now().Truncate(time.Hour)
}
func (s *stat) IsDir() bool {
return s.Mode().IsDir()
}
func (s *stat) Mode() os.FileMode {
switch s.file.v.(type) {
case map[string]interface{}:
return os.ModeDir | 0755
case []interface{}:
return os.ModeDir | 0755
}
return 0644
}
func (s *stat) Size() int64 {
return s.file.size()
}
type dir struct {
c chan stat
done chan struct{}
}
func mkdir(val interface{}) *dir {
c := make(chan stat, 10)
done := make(chan struct{})
go func() {
if m, ok := val.(map[string]interface{}); ok {
LoopMap:
for name, v := range m {
select {
case c <- stat{name: name, file: &fakefile{v: v}}:
case <-done:
break LoopMap
}
}
} else if a, ok := val.([]interface{}); ok {
LoopArray:
for i, v := range a {
name := strconv.Itoa(i)
select {
case c <- stat{name: name, file: &fakefile{v: v}}:
case <-done:
break LoopArray
}
}
}
close(c)
}()
return &dir{
c: c,
done: done,
}
}
func (d *dir) Readdir(n int) ([]os.FileInfo, error) {
var err error
fi := make([]os.FileInfo, 0, 10)
for i := 0; i < n; i++ {
s, ok := <-d.c
if !ok {
err = io.EOF
break
}
fi = append(fi, &s)
}
return fi, err
}
func (d *dir) Close() error {
close(d.done)
return nil
}