commands/files: Added SizeFile interface
Matt Bell committed
Jan 21, 2015 at 18:38 UTC
c73c4ae55d90a007ceb3b73d5d9ab747dbe631a5
4 files changed
+68
-2
commands/files/file.go
+7
-1
@@ -38,8 +38,14 @@ type StatFile interface {
38
}
39
40
type PeekFile interface {
41
- File
41
+ SizeFile
42
43
Peek(n int) File
44
Length() int
45
}
46
+
47
+type SizeFile interface {
48
+ File
49
+
50
+ Size() (int64, error)
51
+}
commands/files/readerfile.go
+8
@@ -1,6 +1,7 @@
1
package files
2
3
import (
4
+ "errors"
5
"io"
6
"os"
7
)
@@ -40,3 +41,10 @@ func (f *ReaderFile) Close() error {
41
func (f *ReaderFile) Stat() os.FileInfo {
42
return f.stat
43
}
44
+
45
+func (f *ReaderFile) Size() (int64, error) {
46
+ if f.stat == nil {
47
+ return 0, errors.New("File size unknown")
48
+ }
49
+ return f.stat.Size(), nil
50
+}
commands/files/serialfile.go
+30
@@ -118,3 +118,33 @@ func (f *serialFile) Close() error {
118
func (f *serialFile) Stat() os.FileInfo {
119
return f.stat
120
}
121
+
122
+func (f *serialFile) Size() (int64, error) {
123
+ return size(f.stat, f.FileName())
124
+}
125
+
126
+func size(stat os.FileInfo, filename string) (int64, error) {
127
+ if !stat.IsDir() {
128
+ return stat.Size(), nil
129
+ }
130
+
131
+ file, err := os.Open(filename)
132
+ if err != nil {
133
+ return 0, err
134
+ }
135
+ files, err := file.Readdir(0)
136
+ if err != nil {
137
+ return 0, err
138
+ }
139
+ file.Close()
140
+
141
+ var output int64
142
+ for _, child := range files {
143
+ s, err := size(child, fp.Join(filename, child.Name()))
144
+ if err != nil {
145
+ return 0, err
146
+ }
147
+ output += s
148
+ }
149
+ return output, nil
150
+}
commands/files/slicefile.go
+23
-1
@@ -1,6 +1,9 @@
1
package files
2
3
-import "io"
3
+import (
4
+ "errors"
5
+ "io"
6
+)
7
8
// SliceFile implements File, and provides simple directory handling.
9
// It contains children files, and is created from a `[]File`.
@@ -47,3 +50,22 @@ func (f *SliceFile) Peek(n int) File {
50
func (f *SliceFile) Length() int {
51
return len(f.files)
52
}
53
+
54
+func (f *SliceFile) Size() (int64, error) {
55
+ var size int64
56
+
57
+ for _, file := range f.files {
58
+ sizeFile, ok := file.(SizeFile)
59
+ if !ok {
60
+ return 0, errors.New("Could not get size of child file")
61
+ }
62
+
63
+ s, err := sizeFile.Size()
64
+ if err != nil {
65
+ return 0, err
66
+ }
67
+ size += s
68
+ }
69
+
70
+ return size, nil
71
+}