summaryrefslogtreecommitdiff
path: root/cache/cache.go
blob: 328b1e9bdb1a23f742c77f4c48ca435f3722c926 (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
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
package cache

import (
	"bufio"
	"errors"
	"io"
	"io/fs"
	"os"
	"path"
	"pik/model"
	"pik/paths"
	"strings"
)

type Cache struct {
	Entries []Entry
}

// Merge combines two caches and filters duplicate keys
func (c Cache) Merge(other Cache) Cache {
	mp := make(map[string]string)
	for _, e := range append(c.Entries, other.Entries...) {
		mp[e.Path] = e.Label
	}
	result := Cache{}
	for p, l := range mp {
		result.Entries = append(result.Entries, Entry{Label: l, Path: p})
	}
	return result
}

type Entry struct {
	Path  string
	Label string
}

var Empty = Cache{}

// Path is the file path to the "contexts" cache file
var Path = path.Join(paths.Cache, "contexts")

// FsPath is the Path with the leading slash removed, to be opened from fs.FS
var FsPath = Path[1:]

var UnexpectedEntryError = errors.New("unexpected cache entry")

// LoadFile creates a Cache from a file or an empty one if the file does not exist
// this handles opening a reader for Unmarshal
func LoadFile(root fs.FS, path string) (Cache, error) {
	fd, err := root.Open(path)
	if errors.Is(err, fs.ErrNotExist) {
		return Cache{}, nil
	} else if err != nil {
		return Cache{}, err
	}
	if fd != nil {
		defer fd.Close()
	}
	return Unmarshal(fd)
}

// Unmarshal attempts to create a Cache from reader content
func Unmarshal(r io.Reader) (Cache, error) {
	c := Cache{}
	scanner := bufio.NewScanner(r)
	for scanner.Scan() {
		line := strings.TrimSpace(scanner.Text())
		if line == "" || line[0] == '#' || line[0:2] == "//" {
			continue
		}

		entry := &Entry{}
		parts := strings.SplitN(line, "#", 2)
		switch len(parts) {
		case 2:
			entry.Label = strings.TrimSpace(parts[1])
			fallthrough
		case 1:
			entry.Path = strings.TrimSpace(parts[0])
		default:
			return c, UnexpectedEntryError
		}
		c.Entries = append(c.Entries, *entry)
	}
	return c, nil
}

// Marshal returns the file representation of the Cache
func (c Cache) Marshal() []byte {
	b := strings.Builder{}
	for _, e := range c.Entries {
		b.WriteString(e.Path)
		b.WriteString(" # ")
		b.WriteString(e.Label)
		b.WriteString("\n")
	}
	return []byte(b.String())
}

func (c Cache) String() string {
	return string(c.Marshal())
}

// New creates a new Cache from a model.State
func New(st *model.State) Cache {
	c := &Cache{}
	for _, s := range st.Sources {
		c.Entries = append(c.Entries, Entry{
			Path:  s.Path,
			Label: s.Label(),
		})
	}
	return *c
}

// SaveFile helps you use Save with a file path instead of a reader
func SaveFile(path string, s *model.State, loaded Cache) error {
	fd, err := os.Create(path)
	if err != nil {
		return err
	}
	if fd != nil {
		defer fd.Close()
	}
	return Save(s, fd, loaded)
}

// Save writes the cache combined with the "loaded" cache to the writer.
func Save(s *model.State, w io.Writer, loaded Cache) error {
	result := New(s).Merge(loaded)
	_, err := w.Write([]byte(result.Marshal()))
	return err

}

// LoadState creates a state with model.NewState based on cache content
func LoadState(f fs.FS, cache Cache, indexers []model.Indexer, runners []model.Runner) (*model.State, []error) {
	var locs []string
	for _, e := range cache.Entries {
		locs = append(locs, e.Path)
	}
	return model.NewState(f, locs, indexers, runners)
}

// Strip removes the needle's entries from the receiver's entries when they have matching paths.
// used to skip already indexed locations when auto-all-ing
func (c Cache) Strip(needle Cache) Cache {
	var result []Entry
outer:
	for _, e := range c.Entries {
		for _, t := range needle.Entries {
			if t.Path == e.Path {
				continue outer
			}
		}
		result = append(result, e)
	}
	return Cache{
		Entries: result,
	}
}