mirror of
https://github.com/ipfs/kubo.git
synced 2026-02-21 10:27:46 +08:00
commands/files: Added SizeFile interface
This commit is contained in:
parent
4a6aec645e
commit
c73c4ae55d
@ -38,8 +38,14 @@ type StatFile interface {
|
||||
}
|
||||
|
||||
type PeekFile interface {
|
||||
File
|
||||
SizeFile
|
||||
|
||||
Peek(n int) File
|
||||
Length() int
|
||||
}
|
||||
|
||||
type SizeFile interface {
|
||||
File
|
||||
|
||||
Size() (int64, error)
|
||||
}
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
package files
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
@ -40,3 +41,10 @@ func (f *ReaderFile) Close() error {
|
||||
func (f *ReaderFile) Stat() os.FileInfo {
|
||||
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 {
|
||||
func (f *serialFile) Stat() os.FileInfo {
|
||||
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
|
||||
}
|
||||
|
||||
@ -1,6 +1,9 @@
|
||||
package files
|
||||
|
||||
import "io"
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
)
|
||||
|
||||
// SliceFile implements File, and provides simple directory handling.
|
||||
// It contains children files, and is created from a `[]File`.
|
||||
@ -47,3 +50,22 @@ func (f *SliceFile) Peek(n int) File {
|
||||
func (f *SliceFile) Length() int {
|
||||
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
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user