-
Notifications
You must be signed in to change notification settings - Fork 3k
/
disk.go
55 lines (48 loc) · 1.37 KB
/
disk.go
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
package game
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/ethereum/go-ethereum/common"
"golang.org/x/exp/slices"
)
const gameDirPrefix = "game-"
// diskManager coordinates the storage of game data on disk.
type diskManager struct {
datadir string
}
func newDiskManager(dir string) *diskManager {
return &diskManager{datadir: dir}
}
func (d *diskManager) DirForGame(addr common.Address) string {
return filepath.Join(d.datadir, gameDirPrefix+addr.Hex())
}
func (d *diskManager) RemoveAllExcept(keep []common.Address) error {
entries, err := os.ReadDir(d.datadir)
if err != nil {
return fmt.Errorf("failed to list directory: %w", err)
}
var errs []error
for _, entry := range entries {
if !entry.IsDir() || !strings.HasPrefix(entry.Name(), gameDirPrefix) {
// Skip files and directories that don't have the game directory prefix.
// While random content shouldn't be in our datadir, we want to avoid
// deleting things like OS generated files.
continue
}
name := entry.Name()[len(gameDirPrefix):]
addr := common.HexToAddress(name)
if addr == (common.Address{}) {
// Ignore directories with non-address names.
continue
}
if slices.Contains(keep, addr) {
// Preserve data for games we should keep.
continue
}
errs = append(errs, os.RemoveAll(filepath.Join(d.datadir, entry.Name())))
}
return errors.Join(errs...)
}