vise/resource/fs.go

73 lines
1.4 KiB
Go
Raw Normal View History

2023-03-31 11:52:04 +02:00
package resource
import (
"context"
2023-04-01 11:58:02 +02:00
"fmt"
"io/ioutil"
"log"
2023-04-01 11:58:02 +02:00
"path"
"path/filepath"
2023-04-01 11:58:02 +02:00
"strings"
2023-03-31 11:52:04 +02:00
)
type FsResource struct {
MenuResource
2023-04-01 15:47:03 +02:00
Path string
fns map[string]EntryFunc
2023-03-31 11:52:04 +02:00
}
func NewFsResource(path string) (FsResource) {
absPath, err := filepath.Abs(path)
if err != nil {
panic(err)
}
2023-03-31 11:52:04 +02:00
return FsResource{
Path: absPath,
2023-03-31 11:52:04 +02:00
}
}
func(fs FsResource) GetTemplate(sym string) (string, error) {
2023-04-01 15:47:03 +02:00
fp := path.Join(fs.Path, sym)
2023-04-01 11:58:02 +02:00
r, err := ioutil.ReadFile(fp)
s := string(r)
return strings.TrimSpace(s), err
2023-03-31 11:52:04 +02:00
}
2023-04-01 11:58:02 +02:00
func(fs FsResource) GetCode(sym string) ([]byte, error) {
fb := sym + ".bin"
fp := path.Join(fs.Path, fb)
return ioutil.ReadFile(fp)
2023-04-01 11:58:02 +02:00
}
func(fs FsResource) FuncFor(sym string) (EntryFunc, error) {
fn, ok := fs.fns[sym]
if ok {
return fn, nil
}
_, err := fs.getFuncNoCtx(sym)
if err != nil {
return nil, fmt.Errorf("unknown sym: %s", sym)
}
return fs.getFunc, nil
}
func(fs FsResource) String() string {
return fmt.Sprintf("fs resource at path: %s", fs.Path)
}
func(fs FsResource) getFunc(sym string, ctx context.Context) (string, error) {
return fs.getFuncNoCtx(sym)
2023-04-01 11:58:02 +02:00
}
func(fs FsResource) getFuncNoCtx(sym string) (string, error) {
fb := sym + ".txt"
fp := path.Join(fs.Path, fb)
log.Printf("getfunc search dir %s %s for %s", fs.Path, fp, sym)
r, err := ioutil.ReadFile(fp)
if err != nil {
return "", fmt.Errorf("failed getting data for sym '%s': %v", sym, err)
}
s := string(r)
return strings.TrimSpace(s), nil
}