You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
bog/infrastructure/memory/swampfile/repository.go

113 lines
2.1 KiB
Go

package swampfile
import (
"os"
"path"
"time"
"io/fs"
"caj-larsson/bog/dataswamp/swampfile"
"github.com/spf13/afero"
)
type SwampFile struct {
filename string
file afero.File
}
func (f SwampFile) Path() string {
return f.filename
}
func (f SwampFile) Size() int64 {
stat, _ := f.file.Stat()
return int64(stat.Size())
}
func (f SwampFile) Read(p []byte) (int, error) {
return f.file.Read(p)
}
func (f SwampFile) Write(p []byte) (int, error) {
return f.file.Write(p)
}
func (f SwampFile) Close() error {
return f.file.Close()
}
func (f SwampFile) Seek(offset int64, whence int) (int64, error) {
return f.file.Seek(offset, whence)
}
func (f SwampFile) Modified() time.Time {
stat, _ := f.file.Stat()
return stat.ModTime()
}
// The actual repository
type Repository struct {
fs afero.Fs
}
func NewRepository() swampfile.Repository {
return Repository{afero.NewMemMapFs()}
}
func (r Repository) Create(filename string, namespace_stub string) (swampfile.SwampInFile, error) {
abs_path := path.Join(namespace_stub, filename)
dir := path.Dir(abs_path)
r.fs.MkdirAll(dir, 0750)
file, err := r.fs.OpenFile(abs_path, os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
panic(err)
}
bf := SwampFile{filename, file}
return bf, nil
}
func (r Repository) Open(filename string, namespace_stub string) (swampfile.SwampOutFile, error) {
abs_path := path.Join(namespace_stub, filename)
dir := path.Dir(abs_path)
r.fs.MkdirAll(dir, 0750)
file, err := r.fs.OpenFile(abs_path, os.O_RDONLY, 0644)
if err != nil {
return nil, swampfile.ErrNotExists
}
bf := SwampFile{filename, file}
return bf, nil
}
func (r Repository) Delete(filename string, namespace_stub string) {
abs_path := path.Join(namespace_stub, filename)
r.fs.Remove(abs_path)
}
func (r Repository) DeleteOlderThan(namespace_stub string, ts time.Time) error {
err := afero.Walk(r.fs, namespace_stub, func(path string, info fs.FileInfo, err error) error {
if err != nil {
return err
}
if info.Mode().IsRegular() && ts.Before(info.ModTime()) {
r.fs.Remove(path)
return nil
}
if !info.Mode().IsDir() {
return swampfile.ErrCorrupted
}
return nil
})
return err
}