1
0
mirror of https://github.com/go-task/task.git synced 2024-12-16 10:59:23 +02:00
task/taskfile/read/cache.go
Pete Davison 22ce67c5e5
feat: remote taskfiles (HTTP) (#1152)
* feat: remote taskfiles over http

* feat: allow insecure connections when --insecure flag is provided

* feat: better error handling for fetch errors

* fix: ensure cache directory always exists

* fix: setup logger before everything else

* feat: put remote taskfiles behind an experiment

* feat: --download and --offline flags for remote taskfiles

* feat: node.Read accepts a context

* feat: experiment docs

* chore: changelog

* chore: remove unused optional param from Node interface

* chore: tidy up and generalise NewNode function

* fix: use sha256 in remote checksum

* feat: --download by itself will not run a task

* feat: custom error if remote taskfiles experiment is not enabled

* refactor: BaseNode functional options and simplified FileNode

* fix: use hex encoding for checksum instead of b64
2023-09-12 22:42:54 +01:00

59 lines
1.2 KiB
Go

package read
import (
"crypto/sha256"
"fmt"
"os"
"path/filepath"
"strings"
)
type Cache struct {
dir string
}
func NewCache(dir string) (*Cache, error) {
dir = filepath.Join(dir, "remote")
if err := os.MkdirAll(dir, 0o755); err != nil {
return nil, err
}
return &Cache{
dir: dir,
}, nil
}
func checksum(b []byte) string {
h := sha256.New()
h.Write(b)
return fmt.Sprintf("%x", h.Sum(nil))
}
func (c *Cache) write(node Node, b []byte) error {
return os.WriteFile(c.cacheFilePath(node), b, 0o644)
}
func (c *Cache) read(node Node) ([]byte, error) {
return os.ReadFile(c.cacheFilePath(node))
}
func (c *Cache) writeChecksum(node Node, checksum string) error {
return os.WriteFile(c.checksumFilePath(node), []byte(checksum), 0o644)
}
func (c *Cache) readChecksum(node Node) string {
b, _ := os.ReadFile(c.checksumFilePath(node))
return string(b)
}
func (c *Cache) key(node Node) string {
return strings.TrimRight(checksum([]byte(node.Location())), "=")
}
func (c *Cache) cacheFilePath(node Node) string {
return filepath.Join(c.dir, fmt.Sprintf("%s.yaml", c.key(node)))
}
func (c *Cache) checksumFilePath(node Node) string {
return filepath.Join(c.dir, fmt.Sprintf("%s.checksum", c.key(node)))
}