Commit 19fa5c7f authored by Matt Bell's avatar Matt Bell

commands/files: Added SizeFile interface

parent 9d5257b4
...@@ -38,8 +38,14 @@ type StatFile interface { ...@@ -38,8 +38,14 @@ type StatFile interface {
} }
type PeekFile interface { type PeekFile interface {
File SizeFile
Peek(n int) File Peek(n int) File
Length() int Length() int
} }
type SizeFile interface {
File
Size() (int64, error)
}
package files package files
import ( import (
"errors"
"io" "io"
"os" "os"
) )
...@@ -40,3 +41,10 @@ func (f *ReaderFile) Close() error { ...@@ -40,3 +41,10 @@ func (f *ReaderFile) Close() error {
func (f *ReaderFile) Stat() os.FileInfo { func (f *ReaderFile) Stat() os.FileInfo {
return f.stat return f.stat
} }
func (f *ReaderFile) Size() (int64, error) {
if f.stat == nil {
return 0, errors.New("File size unknown")
}
return f.stat.Size(), nil
}
...@@ -118,3 +118,33 @@ func (f *serialFile) Close() error { ...@@ -118,3 +118,33 @@ func (f *serialFile) Close() error {
func (f *serialFile) Stat() os.FileInfo { func (f *serialFile) Stat() os.FileInfo {
return f.stat return f.stat
} }
func (f *serialFile) Size() (int64, error) {
return size(f.stat, f.FileName())
}
func size(stat os.FileInfo, filename string) (int64, error) {
if !stat.IsDir() {
return stat.Size(), nil
}
file, err := os.Open(filename)
if err != nil {
return 0, err
}
files, err := file.Readdir(0)
if err != nil {
return 0, err
}
file.Close()
var output int64
for _, child := range files {
s, err := size(child, fp.Join(filename, child.Name()))
if err != nil {
return 0, err
}
output += s
}
return output, nil
}
package files package files
import "io" import (
"errors"
"io"
)
// SliceFile implements File, and provides simple directory handling. // SliceFile implements File, and provides simple directory handling.
// It contains children files, and is created from a `[]File`. // It contains children files, and is created from a `[]File`.
...@@ -47,3 +50,22 @@ func (f *SliceFile) Peek(n int) File { ...@@ -47,3 +50,22 @@ func (f *SliceFile) Peek(n int) File {
func (f *SliceFile) Length() int { func (f *SliceFile) Length() int {
return len(f.files) return len(f.files)
} }
func (f *SliceFile) Size() (int64, error) {
var size int64
for _, file := range f.files {
sizeFile, ok := file.(SizeFile)
if !ok {
return 0, errors.New("Could not get size of child file")
}
s, err := sizeFile.Size()
if err != nil {
return 0, err
}
size += s
}
return size, nil
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment