package fs import ( "io" "os" "path/filepath" "github.com/spf13/afero" "opslag.de/schobers/zntg" "opslag.de/schobers/zntg/ui" ) type aferoResources struct { dir string fs afero.Fs copy *zntg.Dir } var _ ui.Resources = &aferoResources{} // NewAferoResources provides resources from a afero file system. The prefix is used as a prefix of the temporary directory. func NewAferoResources(fs afero.Fs, prefix string) (ui.Resources, error) { return NewAferoFallbackResources("", fs, prefix) } // NewAferoFallbackResources provides resources from the directory first and uses afero file system as a fallback if the resource in the directory doesn't exist. The prefix is used as a prefix of the temporary directory. func NewAferoFallbackResources(dir string, fs afero.Fs, prefix string) (ui.Resources, error) { copy, err := zntg.NewTempDir(prefix) if err != nil { return nil, err } return &aferoResources{dir, fs, copy}, nil } func (r *aferoResources) fetchAferoResource(name string) (string, error) { path := r.copy.FilePath(name) if !zntg.FileExists(path) { src, err := r.fs.Open(name) if err != nil { return "", err } defer src.Close() err = r.copy.Write(name, src) if err != nil { return "", err } } return path, nil } func (r *aferoResources) openAferoResource(name string) (io.ReadCloser, error) { return r.fs.Open(name) } func (r *aferoResources) Destroy() error { return r.copy.Destroy() } func (r *aferoResources) FetchResource(name string) (string, error) { if r.dir == "" { return r.fetchAferoResource(name) } path := filepath.Join(r.dir, name) if zntg.FileExists(path) { return path, nil } return r.fetchAferoResource(name) } func (r *aferoResources) OpenResource(name string) (io.ReadCloser, error) { if r.dir == "" { return r.openAferoResource(name) } path := filepath.Join(r.dir, name) if zntg.FileExists(path) { return os.Open(path) } return r.openAferoResource(name) }