aboutsummaryrefslogtreecommitdiff
path: root/internal/thumbnail/init.go
blob: 42349602daf271a8e12629c55a889f5aba45d7e2 (plain)
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
package thumbnail

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"
)

// initializeCache prepares the thumbnail cache directory.
//
// It creates the current cache generation and removes obsolete cache
// generations left behind by previous versions.
func (g *Generator) initializeCache() error {
	thumbsDir := filepath.Join(g.cacheDir, "thumbs")

	if err := os.MkdirAll(
		filepath.Join(thumbsDir, cacheVersion()),
		0o775,
	); err != nil {
		return fmt.Errorf("create cache directory: %w", err)
	}

	entries, err := os.ReadDir(thumbsDir)
	if err != nil {
		return fmt.Errorf("read cache directory: %w", err)
	}

	current := cacheVersion()

	for _, entry := range entries {
		if !entry.IsDir() {
			continue
		}

		name := entry.Name()

		if !strings.HasPrefix(name, "v") {
			continue
		}

		if name == current {
			continue
		}

		if err := os.RemoveAll(filepath.Join(thumbsDir, name)); err != nil {
			return fmt.Errorf(
				"remove obsolete cache %q: %w",
				name,
				err,
			)
		}
	}

	return nil
}