-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
178 lines (147 loc) · 4.19 KB
/
Copy pathmain.go
File metadata and controls
178 lines (147 loc) · 4.19 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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
package main
import (
"context"
"fmt"
"log"
"log/slog"
"os"
"os/exec"
"strings"
"sync"
"time"
"github.com/alecthomas/kong"
"github.com/AlekSi/hardcache/internal/caches/local"
"github.com/AlekSi/hardcache/internal/sigterm"
"github.com/AlekSi/hardcache/internal/unit"
)
// cli represents CLI arguments and flags.
//
//nolint:vet // for readability
var cli struct {
Local struct {
Dir string `default:"${local_dir_default}" type:"path" help:"Directory to use."`
UnusedFor unit.Duration `default:"5d" help:"Always remove entries unused for this duration. Pass 0 to disable."`
MaxSize string `default:"0GB" help:"${local_max_size_help}"`
Trim struct{} `cmd:"" help:"Trim local cache."`
Trimd struct {
Interval unit.Duration `short:"i" default:"1h" help:"Interval between trimmings."`
} `cmd:"" help:"Trim local cache continuously."`
} `cmd:""`
Debug bool `help:"Enable debug logging."`
}
// GOCACHE returns the Go build cache directory.
var GOCACHE = sync.OnceValue(func() string {
// in theory, someone might not have go in the PATH
if v := os.Getenv("GOCACHE"); v != "" {
return v
}
// that handles `go env -w` and the default value
b, err := exec.Command("go", "env", "GOCACHE").Output()
if err != nil {
panic(err)
}
return strings.TrimSpace(string(b))
})
// localTrim force-trims local cache according to CLI flags.
func localTrim(l *slog.Logger) error {
if cli.Local.UnusedFor < 0 {
return fmt.Errorf("--unused-for cannot be negative: %d", cli.Local.UnusedFor)
}
var cutoff *time.Time
if cli.Local.UnusedFor > 0 {
c := time.Now().Add(-time.Duration(cli.Local.UnusedFor))
cutoff = &c
}
var b unit.Bytes
if strings.HasSuffix(cli.Local.MaxSize, "%") {
var p unit.Percentage
if err := p.UnmarshalText([]byte(cli.Local.MaxSize)); err != nil {
return err
}
total, _, err := local.DiskInfo(cli.Local.Dir)
if err != nil {
return err
}
b = unit.Bytes(total / 100 * int64(p))
l.Debug(
"Calculated max size from percentage of total disk size",
slog.Int64("disk_size_bytes", total),
slog.String("disk_size", unit.Bytes(total).String()),
slog.Int64("max_size_bytes", int64(b)),
slog.String("max_size", b.String()),
)
} else {
if err := b.UnmarshalText([]byte(cli.Local.MaxSize)); err != nil {
return err
}
l.Debug("Max size", slog.Int64("max_size_bytes", int64(b)), slog.String("max_size", b.String()))
}
if b < 0 {
return fmt.Errorf("--max-size cannot be negative: %d", b)
}
var maxSize *int64
if b > 0 {
maxSize = (*int64)(&b)
}
c, err := local.New(cli.Local.Dir, cutoff, maxSize, l)
if err != nil {
return err
}
before, freed := c.TrimForce()
l.Debug(
"Local cache trimmed",
slog.Int64("before_bytes", before), slog.Int64("freed_bytes", freed),
)
l.Info(
"Local cache trimmed",
slog.String("before", unit.Bytes(before).String()), slog.String("freed", unit.Bytes(freed).String()),
)
return nil
}
func main() {
opts := []kong.Option{
kong.Name("hardcache"),
kong.Description("Tool for managing the Go build cache."),
kong.Vars{
"local_dir_default": GOCACHE(),
"local_max_size_help": "Remove entries, starting from least recently used, " +
"if cache size is larger than this value. " +
"Supports MiB, GB, etc. suffixes, or percentage of the total disk space (e.g., 5%). " +
"Pass 0 to disable.",
},
kong.ConfigureHelp(kong.HelpOptions{
Tree: true,
WrapUpperBound: 120,
}),
}
kongCtx := kong.Parse(&cli, opts...)
log.SetPrefix("hardcache: ")
log.SetFlags(log.Lmicroseconds)
if cli.Debug {
slog.SetLogLoggerLevel(slog.LevelDebug)
}
l := slog.Default()
ctx, cancel := sigterm.Ctx(context.Background())
defer cancel()
switch kongCtx.Command() {
case "local trim":
if time.Duration(cli.Local.UnusedFor) > 5*24*time.Hour {
l.Info("Note: this command should be invoked more often than once per day to keep the cache.")
}
err := localTrim(l)
kongCtx.FatalIfErrorf(err)
case "local trimd":
for {
err := localTrim(l)
kongCtx.FatalIfErrorf(err)
select {
case <-ctx.Done():
return
case <-time.After(time.Duration(cli.Local.Trimd.Interval)):
// nothing
}
}
default:
kongCtx.Fatalf("unknown command: %q", kongCtx.Command())
}
}