/
fs.go
116 lines (91 loc) · 2.33 KB
/
fs.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
package fs
import (
"io"
"net/http"
"os"
"strings"
)
//MetaData returned by File.Stat
type MetaData os.FileInfo
//Index is an index into a list returned by Node.List
type Index struct {
Path Path
Int int
String string
}
//Child is a node's child.
type Child interface {
//Get the current child's index.
Index() Index
//Return the current child as a node, nil if the current child is not a node.
Node() Node
//Return the current child as data, nil if the current child is not data.
Data() Data
}
//Data is the lowlevel interface required for Files.
type Data interface {
io.ReaderFrom
io.WriterTo
http.Handler
//Return the path to this data.
Path() Path
//Stat returns info about the data.
Stat() (os.FileInfo, error)
//Deletes the data.
Delete() error
}
//File contains Data
type File struct {
Data
}
//SetString sets the contents of the file to the given string.
func (f File) SetString(contents string) error {
_, err := f.ReadFrom(strings.NewReader(contents))
return err
}
//String returns the contents of the file as a string.
func (f File) String() string {
var builder strings.Builder
f.WriteTo(&builder)
return builder.String()
}
//Node is the lowlevel interface required for Directories.
//A node is a location within a tree, it doesn't have to exist.
type Node interface {
//Create this node and all parent nodes required for this node to exist.
Create() error
//Delete this node and all children nodes and data.
Delete() error
//Return the node at the relative path.
Goto(relative Path) Node
//Return the data of this node at the relative path.
Data(name string) Data
//Return the path of this node.
Path() Path
//Stat returns info about the directory.
Stat() (os.FileInfo, error)
//Slice returns a slice of children.
Slice(offset Index, length int) ([]Child, error)
}
//Directory can contain files or other directories.
type Directory struct {
Node
}
//File returns the file inside the given directory with the given name.
func (d Directory) File(name string) File {
return File{d.Data(name)}
}
//Goto goes to the given path.
func (d Directory) Goto(path Path) Directory {
return Directory{d.Node.Goto(path)}
}
//Root is a file-system root.
type Root struct {
Directory
}
//NewRoot returns a new Root from a given Node.
func NewRoot(node Node) Root {
var root Root
root.Node = node
return root
}