From 6716491d6be1cc3a3c0467cb745d3b679ceacc36 Mon Sep 17 00:00:00 2001 From: Keith Gaughan Date: Sat, 26 Oct 2024 03:40:24 +0100 Subject: [PATCH] Add cache directory tagging support See: https://bford.info/cachedir/ This is a small tweak to make sure that the cache directory can be identified as such. --- cmd/mercury/main.go | 2 +- internal/utils/paths.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/cmd/mercury/main.go b/cmd/mercury/main.go index 132444b..0333ccf 100644 --- a/cmd/mercury/main.go +++ b/cmd/mercury/main.go @@ -49,7 +49,7 @@ func main() { log.Fatal(err) } - utils.EnsureDir(config.Cache) + utils.EnsureCache(config.Cache) if !*flags.NoBuild { utils.EnsureDir(config.Output) diff --git a/internal/utils/paths.go b/internal/utils/paths.go index 88b7d08..555eaa0 100644 --- a/internal/utils/paths.go +++ b/internal/utils/paths.go @@ -1,10 +1,14 @@ package utils import ( + "bytes" "log" "os" + "path/filepath" ) +const cacheTagMarker = "Signature: 8a477f597d28d172789f06886806bc55\n" + func EnsureDir(path string) { if fileInfo, err := os.Stat(path); os.IsNotExist(err) { if err := os.MkdirAll(path, 0o755); err != nil { @@ -14,3 +18,27 @@ func EnsureDir(path string) { log.Fatalf("%s must be a directory\n", path) } } + +func writeCacheTag(path string) error { + return os.WriteFile(path, []byte(cacheTagMarker), 0o600) +} + +func EnsureCache(path string) { + EnsureDir(path) + cacheTag := filepath.Join(path, "CACHE.TAG") + if _, err := os.Stat(cacheTag); os.IsNotExist(err) { + if err = writeCacheTag(cacheTag); err != nil { + log.Fatal(err) + } + } else { + contents, err := os.ReadFile(cacheTag) + if err != nil { + log.Fatal(err) + } + if !bytes.HasPrefix(contents, []byte(cacheTagMarker)) { + if err = writeCacheTag(cacheTag); err != nil { + log.Fatal(err) + } + } + } +}