cache.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package taskfile
  2. import (
  3. "crypto/sha256"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. )
  9. type Cache struct {
  10. dir string
  11. }
  12. func NewCache(dir string) (*Cache, error) {
  13. dir = filepath.Join(dir, "remote")
  14. if err := os.MkdirAll(dir, 0o755); err != nil {
  15. return nil, err
  16. }
  17. return &Cache{
  18. dir: dir,
  19. }, nil
  20. }
  21. func checksum(b []byte) string {
  22. h := sha256.New()
  23. h.Write(b)
  24. return fmt.Sprintf("%x", h.Sum(nil))
  25. }
  26. func (c *Cache) write(node Node, b []byte) error {
  27. return os.WriteFile(c.cacheFilePath(node), b, 0o644)
  28. }
  29. func (c *Cache) read(node Node) ([]byte, error) {
  30. return os.ReadFile(c.cacheFilePath(node))
  31. }
  32. func (c *Cache) writeChecksum(node Node, checksum string) error {
  33. return os.WriteFile(c.checksumFilePath(node), []byte(checksum), 0o644)
  34. }
  35. func (c *Cache) readChecksum(node Node) string {
  36. b, _ := os.ReadFile(c.checksumFilePath(node))
  37. return string(b)
  38. }
  39. func (c *Cache) key(node Node) string {
  40. return strings.TrimRight(checksum([]byte(node.Location())), "=")
  41. }
  42. func (c *Cache) cacheFilePath(node Node) string {
  43. return c.filePath(node, "yaml")
  44. }
  45. func (c *Cache) checksumFilePath(node Node) string {
  46. return c.filePath(node, "checksum")
  47. }
  48. func (c *Cache) filePath(node Node, suffix string) string {
  49. lastDir, filename := node.FilenameAndLastDir()
  50. prefix := filename
  51. // Means it's not "", nor "." nor "/", so it's a valid directory
  52. if len(lastDir) > 1 {
  53. prefix = fmt.Sprintf("%s-%s", lastDir, filename)
  54. }
  55. return filepath.Join(c.dir, fmt.Sprintf("%s.%s.%s", prefix, c.key(node), suffix))
  56. }
  57. func (c *Cache) Clear() error {
  58. return os.RemoveAll(c.dir)
  59. }