forked from sourcegraph/rwvfs
/
os.go
50 lines (42 loc) · 1.15 KB
/
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
package rwvfs
import (
"code.google.com/p/go.tools/godoc/vfs"
"fmt"
"os"
pathpkg "path"
"path/filepath"
)
// OS returns an implementation of FileSystem reading from the tree rooted at
// root.
func OS(root string) FileSystem {
return osFS{root, vfs.OS(root)}
}
type osFS struct {
root string
vfs.FileSystem
}
// resolve is from code.google.com/p/go.tools/godoc/vfs.
func (fs osFS) resolve(path string) string {
// Clean the path so that it cannot possibly begin with ../.
// If it did, the result of filepath.Join would be outside the
// tree rooted at root. We probably won't ever see a path
// with .. in it, but be safe anyway.
path = pathpkg.Clean("/" + path)
return filepath.Join(string(fs.root), path)
}
// OpenFile opens the file at path for writing, creating the file if it doesn't
// exist and truncating it otherwise.
func (fs osFS) OpenFile(path string, flag int) (ReadWriteSeekCloser, error) {
f, err := os.OpenFile(fs.resolve(path), flag, 0644)
if err != nil {
return nil, err
}
fi, err := f.Stat()
if err != nil {
return nil, err
}
if fi.IsDir() {
return nil, fmt.Errorf("Open: %s is a directory", path)
}
return f, nil
}