-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile_context.go
68 lines (56 loc) · 1.68 KB
/
file_context.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
56
57
58
59
60
61
62
63
64
65
66
67
68
package main
import (
"os"
sf "github.com/JaMo42/spellcheck_comments/source_file"
"github.com/JaMo42/spellcheck_comments/tui"
)
type FileContext struct {
sf sf.SourceFile
changes map[tui.SliceIndex]bool
}
func NewFileContext(sf sf.SourceFile) FileContext {
return FileContext{
sf: sf,
changes: make(map[tui.SliceIndex]bool),
}
}
func (self *FileContext) Source() *sf.SourceFile {
return &self.sf
}
func (self *FileContext) Word(id int) *sf.Word {
return &self.sf.Words()[id]
}
// Change changes the text of a slice and adds it to the changes.
func (self *FileContext) Change(index tui.SliceIndex, text string) {
self.sf.Text().SetSliceText(index, text)
self.changes[index] = true
}
// RemoveChange removes a slice from the changes and sets its content to the
// given original.
func (self *FileContext) RemoveChange(index tui.SliceIndex, original string) {
self.sf.Text().SetSliceText(index, original)
delete(self.changes, index)
}
// SliceIsChanged returns true if the slice with the given index is already changed.
func (self *FileContext) SliceIsChanged(index tui.SliceIndex) bool {
return self.changes[index]
}
// IsChanged returns true if any changes are made to the file.
func (self *FileContext) IsChanged() bool {
return len(self.changes) != 0
}
func (self *FileContext) AddToBackup(b *Backup) {
b.SetFile(self.sf.Name())
tb := self.sf.Text()
originals := make(map[tui.SliceIndex]string)
for _, w := range self.sf.Words() {
originals[w.Index] = w.Original
}
for change := range self.changes {
b.AddLine(change.Line(), tb, originals)
}
}
func (self *FileContext) Write() error {
data := self.sf.String()
return os.WriteFile(self.sf.Name(), []byte(data), 0o644)
}