-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcache.go
More file actions
67 lines (55 loc) · 1.54 KB
/
cache.go
File metadata and controls
67 lines (55 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package main
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/ossf/gemara/layer2"
"gopkg.in/yaml.v3"
)
const cacheDir = "tmp"
// getCacheFilename generates a unique cache filename based on the URLs
func getCacheFilename(urls []string) string {
// Sort URLs to ensure consistent hashing
urlStr := strings.Join(urls, "|")
hash := sha256.Sum256([]byte(urlStr))
return filepath.Join(cacheDir, "controls-canvas-"+hex.EncodeToString(hash[:8])+".yaml")
}
// ensureCacheDir creates the cache directory if it doesn't exist
func ensureCacheDir() error {
if _, err := os.Stat(cacheDir); os.IsNotExist(err) {
return os.MkdirAll(cacheDir, 0755)
}
return nil
}
// loadFromCache attempts to load catalog data from cache
func loadFromCache(urls []string) (*layer2.Catalog, error) {
cacheFile := getCacheFilename(urls)
data, err := os.ReadFile(cacheFile)
if err != nil {
return nil, err
}
var catalog layer2.Catalog
err = yaml.Unmarshal(data, &catalog)
if err != nil {
return nil, err
}
return &catalog, nil
}
// saveToCache saves catalog data to cache
func saveToCache(urls []string, catalog *layer2.Catalog) error {
if err := ensureCacheDir(); err != nil {
return fmt.Errorf("failed to create cache directory: %w", err)
}
data, err := yaml.Marshal(catalog)
if err != nil {
return fmt.Errorf("failed to marshal catalog: %w", err)
}
cacheFile := getCacheFilename(urls)
if err := os.WriteFile(cacheFile, data, 0644); err != nil {
return fmt.Errorf("failed to write cache file: %w", err)
}
return nil
}