all repos

anpi @ main

yaml to anki importer

anpi/cache.go (view raw)

Olexandr Smirnov Olexandr Smirnov
olexsmir@gmail.com
repurpose of the tool, 8 days ago
1
package main
2
3
import (
4
	"encoding/json"
5
	"errors"
6
	"os"
7
	"path/filepath"
8
)
9
10
var ErrNotFound = errors.New("word not found")
11
12
type Cache struct {
13
	dir string
14
}
15
16
func NewCache() (*Cache, error) {
17
	home, err := os.UserHomeDir()
18
	if err != nil {
19
		return nil, err
20
	}
21
	dir := filepath.Join(home, ".cache", "anpi")
22
	if err := os.MkdirAll(dir, 0o755); err != nil {
23
		return nil, err
24
	}
25
	return &Cache{dir: dir}, nil
26
}
27
28
func (c *Cache) path(word string) string {
29
	return filepath.Join(c.dir, word+".json")
30
}
31
32
func (c *Cache) notfoundPath(word string) string {
33
	return filepath.Join(c.dir, word+".notfound")
34
}
35
36
func (c *Cache) Read(word string) (*Entry, error) {
37
	if _, err := os.Stat(c.notfoundPath(word)); err == nil {
38
		return nil, ErrNotFound
39
	}
40
	p := c.path(word)
41
	f, err := os.Open(p)
42
	if err != nil {
43
		return nil, err
44
	}
45
	defer f.Close() //nolint:errcheck
46
	var e Entry
47
	if err := json.NewDecoder(f).Decode(&e); err != nil {
48
		return nil, err
49
	}
50
	return &e, nil
51
}
52
53
func (c *Cache) Write(word string, e *Entry, found bool) error {
54
	if !found {
55
		f, err := os.Create(c.notfoundPath(word))
56
		if err != nil {
57
			return err
58
		}
59
		return f.Close()
60
	}
61
	p := c.path(word)
62
	f, err := os.Create(p)
63
	if err != nil {
64
		return err
65
	}
66
	defer f.Close() //nolint:errcheck
67
	return json.NewEncoder(f).Encode(e)
68
}
69
70
func (c *Cache) Clear(word string) error {
71
	_ = os.Remove(c.notfoundPath(word))
72
	return os.Remove(c.path(word))
73
}