forked from projectdiscovery/nuclei
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.go
More file actions
108 lines (89 loc) · 2.26 KB
/
cache.go
File metadata and controls
108 lines (89 loc) · 2.26 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package templates
import (
"os"
"time"
"github.com/projectdiscovery/utils/conversion"
mapsutil "github.com/projectdiscovery/utils/maps"
)
// Templates is a cache for caching and storing templates for reuse.
type Cache struct {
items *mapsutil.SyncLockMap[string, parsedTemplate]
}
// New returns a new templates cache
func NewCache() *Cache {
return &Cache{
items: mapsutil.NewSyncLockMap[string, parsedTemplate](),
}
}
type parsedTemplate struct {
template *Template
raw string
err error
filePath string
modTime time.Time
}
// setModTime sets the modification time of the file if it exists.
func (p *parsedTemplate) setModTime(id string) {
if stat, err := os.Stat(id); err == nil {
p.modTime = stat.ModTime()
}
}
// isValid checks if the cached template is still valid based on the file's
// modification time.
func (p *parsedTemplate) isValid(templatePath string) bool {
if p.modTime.IsZero() {
return true
}
stat, err := os.Stat(templatePath)
if err != nil {
return false
}
return stat.ModTime().Equal(p.modTime)
}
// Has returns true if the cache has a template. The template
// is returned along with any errors if found.
func (t *Cache) Has(template string) (*Template, []byte, error) {
value, ok := t.items.Get(template)
if !ok {
return nil, nil, nil
}
if !value.isValid(template) {
t.items.Delete(template)
return nil, nil, nil
}
return value.template, conversion.Bytes(value.raw), value.err
}
// Store stores a template with data and error
func (t *Cache) Store(id string, tpl *Template, raw []byte, err error) {
entry := parsedTemplate{
template: tpl,
err: err,
raw: conversion.String(raw),
filePath: id,
}
entry.setModTime(id)
_ = t.items.Set(id, entry)
}
// StoreWithoutRaw stores a template without raw data for memory efficiency
func (t *Cache) StoreWithoutRaw(id string, tpl *Template, err error) {
entry := parsedTemplate{
template: tpl,
err: err,
raw: "",
filePath: id,
}
entry.setModTime(id)
_ = t.items.Set(id, entry)
}
// Get returns only the template without raw bytes
func (t *Cache) Get(id string) (*Template, error) {
value, ok := t.items.Get(id)
if !ok {
return nil, nil
}
return value.template, value.err
}
// Purge the cache
func (t *Cache) Purge() {
t.items.Clear()
}