Sander Schobers
67e73a8671
PhysicalResources derives from Resources and exposes FetchResource. Made dependency specific resource addons. Extended the available resource options (fallback, path, refactored copy). NewRenderer provides DefaultResources to the created renderer.
68 lines
1.7 KiB
Go
68 lines
1.7 KiB
Go
package ui
|
|
|
|
import (
|
|
"io"
|
|
"os"
|
|
|
|
"opslag.de/schobers/zntg"
|
|
)
|
|
|
|
var _ PhysicalResources = &CopyResources{}
|
|
|
|
// CopyResources copies the resource to a temporary directory when fetched. Optionally the resource is fetched as well before opening.
|
|
type CopyResources struct {
|
|
Source Resources
|
|
|
|
copy *zntg.Dir
|
|
|
|
mustCopyBeforeOpen bool
|
|
}
|
|
|
|
func newCopyResources(prefix string, source Resources, mustCopyBeforeOpen bool) (*CopyResources, error) {
|
|
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)
|
|
}
|
|
|
|
// 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.
|
|
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)
|
|
}
|
|
|
|
// Destroy destroy the copy of the resources.
|
|
func (r *CopyResources) Destroy() error {
|
|
return r.copy.Destroy()
|
|
}
|