Add flag to stop re-parsing the user file when we already know its

contents
This commit is contained in:
Sasha Koshka 2024-08-22 20:10:12 -04:00
parent e489a12a28
commit ed77634a50
2 changed files with 26 additions and 13 deletions

View File

@ -156,7 +156,7 @@ func (this *File) Has (key string) (bool, error) {
func (this *File) Get (key string) (Value, error) {
if !KeyValid(key) { return nil, ErrMalformedKey }
if index, ok := this.keys[key]; ok {
if lin := this.lines[index].(entry); ok {
if lin, ok := this.lines[index].(entry); ok {
return lin.value, nil
}
}
@ -166,14 +166,16 @@ func (this *File) Get (key string) (Value, error) {
// Set sets a value. If the key is invalid, it returns ErrMalformedKey.
func (this *File) Set (key string, value Value) error {
if !KeyValid(key) { return ErrMalformedKey }
ent := entry {
key: key,
value: value,
}
if index, ok := this.keys[key]; ok {
ent := this.lines[index].(entry)
ent.value = value
this.lines[index] = ent
return nil
}
this.keys[key] = len(this.lines)
this.lines = append(this.lines, value)
this.lines = append(this.lines, ent)
return nil
}

View File

@ -19,6 +19,7 @@ type config struct {
open bool
watcher *fsnotify.Watcher
lock sync.RWMutex
ignoreNextUserUpdate bool
paths struct {
user string
@ -68,10 +69,13 @@ func (this *config) lockAndProcessEvent (event fsnotify.Event) {
if _, ok := this.paths.watching[event.Name]; !ok { return }
if event.Name == this.paths.user {
if !this.ignoreNextUserUpdate {
previousUser := this.data.user
this.reloadUser()
newUser := this.data.user
this.processUserDiff(newUser.Diff(previousUser))
}
this.ignoreNextUserUpdate = false
} else {
index := slices.Index(this.paths.system, event.Name)
if index > 0 {
@ -148,6 +152,7 @@ func (this *config) saveUser () error {
defer file.Close()
_, err = this.data.user.WriteTo(file)
if err != nil { return err }
this.ignoreNextUserUpdate = true
return nil
}
@ -262,7 +267,10 @@ func (this *config) Set (key string, value Value) error {
if this.data.user == nil { this.data.user = NewFile() }
err := this.data.user.Set(key, value)
if err != nil { return err }
return this.saveUser()
err = this.saveUser()
if err != nil { return err }
this.broadcastChange(key)
return nil
}
func (this *config) Reset (key string) error {
@ -271,7 +279,10 @@ func (this *config) Reset (key string) error {
if this.data.user == nil { this.data.user = NewFile() }
err := this.data.user.Reset(key)
if err != nil { return err }
return this.saveUser()
err = this.saveUser()
if err != nil { return err }
this.broadcastChange(key)
return nil
}
func (this *config) OnChange (callback func (string)) event.Cookie {