aboutsummaryrefslogtreecommitdiffstats
path: root/utils/fs/os.go
blob: 40942baf3b289d42eabfb1b4ceb2eb23deb90d7e (plain) (blame)
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
package fs

import (
	"io/ioutil"
	"os"
	"path"
	"path/filepath"
)

// NewOS returns a new OS.
func NewOS() Filesystem {
	return &OSClient{}
}

// OSClient a filesystem based on OSClient
type OSClient struct {
	RootDir string
}

// NewOSClient returns a new OSClient
func NewOSClient(rootDir string) *OSClient {
	return &OSClient{
		RootDir: rootDir,
	}
}

// Create creates a new GlusterFSFile
func (c *OSClient) Create(filename string) (File, error) {
	fullpath := path.Join(c.RootDir, filename)

	dir := filepath.Dir(fullpath)
	if dir != "." {
		if err := os.MkdirAll(dir, 0755); err != nil {
			return nil, err
		}
	}

	f, err := os.Create(fullpath)
	if err != nil {
		return nil, err
	}

	return &OSFile{
		BaseFile: BaseFile{filename: fullpath},
		file:     f,
	}, nil
}

// ReadDir returns the filesystem info for all the archives under the specified
// path.
func (c *OSClient) ReadDir(path string) ([]FileInfo, error) {
	fullpath := c.Join(c.RootDir, path)

	l, err := ioutil.ReadDir(fullpath)
	if err != nil {
		return nil, err
	}

	var s = make([]FileInfo, len(l))
	for i, f := range l {
		s[i] = f
	}

	return s, nil
}

func (c *OSClient) Rename(from, to string) error {
	if !filepath.IsAbs(from) {
		from = c.Join(c.RootDir, from)
	}

	if !filepath.IsAbs(to) {
		to = c.Join(c.RootDir, to)
	}

	return os.Rename(from, to)
}

func (c *OSClient) Open(filename string) (File, error) {
	fullpath := c.Join(c.RootDir, filename)

	f, err := os.Open(fullpath)
	if err != nil {
		return nil, err
	}

	return &OSFile{
		BaseFile: BaseFile{filename: fullpath},
		file:     f,
	}, nil
}

func (c *OSClient) Stat(filename string) (FileInfo, error) {
	fullpath := c.Join(c.RootDir, filename)
	return os.Stat(fullpath)
}

// Join joins the specified elements using the filesystem separator.
func (c *OSClient) Join(elem ...string) string {
	return filepath.Join(elem...)
}

func (c *OSClient) Dir(path string) Filesystem {
	return NewOSClient(c.Join(c.RootDir, path))
}

func (c *OSClient) Base() string {
	return c.RootDir
}

type OSFile struct {
	file *os.File
	BaseFile
}

func (f *OSFile) Read(p []byte) (int, error) {
	return f.file.Read(p)
}

func (f *OSFile) Seek(offset int64, whence int) (int64, error) {
	return f.file.Seek(offset, whence)
}

func (f *OSFile) Write(p []byte) (int, error) {
	return f.file.Write(p)
}

func (f *OSFile) Close() error {
	f.closed = true

	return f.file.Close()
}