Skip to content

Commit

Permalink
filesystem: add Truncate wrapper.
Browse files Browse the repository at this point in the history
Mimics `os.Truncate`, adapted for `fs`.
  • Loading branch information
djdv committed Dec 6, 2022
1 parent 599db05 commit d7de6aa
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions internal/filesystem/filesystem.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import (
"io/fs"
"os"
"time"

fserrors "github.com/djdv/go-filesystem-utils/internal/filesystem/errors"
)

type (
Expand Down Expand Up @@ -105,6 +107,19 @@ func OpenFile(fsys fs.FS, name string, flag int, perm fs.FileMode) (fs.File, err
return nil, fmt.Errorf(`open "%s": operation not supported`, name)
}

func Truncate(fsys fs.FS, name string, size int64) (err error) {
file, err := OpenFile(fsys, name, os.O_WRONLY|os.O_CREATE, 0o666)
if err != nil {
return err
}
defer func() { err = fserrors.Join(err, file.Close()) }()
truncater, ok := file.(TruncateFile)
if ok {
return truncater.Truncate(size)
}
return fmt.Errorf(`truncate "%s": operation not supported`, name)
}

func StreamDir(ctx context.Context, directory fs.ReadDirFile) <-chan StreamDirEntry {
if dirStreamer, ok := directory.(StreamDirFile); ok {
return dirStreamer.StreamDir(ctx)
Expand Down

0 comments on commit d7de6aa

Please sign in to comment.