zntg/ui/copyresources.go

68 lines
1.7 KiB
Go
Raw Normal View History

2020-05-15 12:20:07 +00:00
package ui
import (
"io"
"os"
"opslag.de/schobers/zntg"
)
var _ PhysicalResources = &CopyResources{}
2020-05-15 12:20:07 +00:00
// CopyResources copies the resource to a temporary directory when fetched. Optionally the resource is fetched as well before opening.
2020-05-15 12:20:07 +00:00
type CopyResources struct {
Source Resources
copy *zntg.Dir
mustCopyBeforeOpen bool
2020-05-15 12:20:07 +00:00
}
func newCopyResources(prefix string, source Resources, mustCopyBeforeOpen bool) (*CopyResources, error) {
2020-05-15 12:20:07 +00:00
copy, err := zntg.NewTempDir(prefix)
if nil != err {
return nil, err
}
return &CopyResources{source, copy, mustCopyBeforeOpen}, nil
}
// NewCopyResources creates a proxy that copies resources first to disk. Copy on OpenResource only happens when mustCopyBeforeOpen is set to true.
func NewCopyResources(prefix string, source Resources, mustCopyBeforeOpen bool) (*CopyResources, error) {
return newCopyResources(prefix, source, false)
2020-05-15 12:20:07 +00:00
}
// FetchResource copies the file from the source to disk and returns the path to it.
func (r *CopyResources) FetchResource(name string) (string, error) {
path := r.copy.FilePath(name)
if !zntg.FileExists(path) {
src, err := r.Source.OpenResource(name)
if err != nil {
return "", err
}
defer src.Close()
err = r.copy.Write(name, src)
if nil != err {
return "", err
}
}
return path, nil
}
// OpenResource opens the (optionally copied) resource.
2020-05-15 12:20:07 +00:00
func (r *CopyResources) OpenResource(name string) (io.ReadCloser, error) {
if r.mustCopyBeforeOpen {
path, err := r.FetchResource(name)
if err != nil {
return nil, err
}
return os.Open(path)
}
return r.Source.OpenResource(name)
2020-05-15 12:20:07 +00:00
}
// Destroy destroy the copy of the resources.
func (r *CopyResources) Destroy() error {
return r.copy.Destroy()
}