Fixed diffing thinking orphaned keys were real

This commit is contained in:
Sasha Koshka 2024-08-22 20:27:22 -04:00
parent ed77634a50
commit a69c726482
2 changed files with 50 additions and 4 deletions

View File

@ -147,8 +147,12 @@ func ParseValue (str string) (Value, error) {
// ErrMalformedKey.
func (this *File) Has (key string) (bool, error) {
if !KeyValid(key) { return false, ErrMalformedKey }
_, ok := this.keys[key]
return ok, nil
if index, ok := this.keys[key]; ok {
if _, ok := this.lines[index].(entry); ok {
return true, nil
}
}
return false, nil
}
// Get gets the keyed value. If the value is unspecified, it returns nil,
@ -214,19 +218,31 @@ func (this *File) Diff (other *File) map[string] struct { } {
// - keys only we have
// - keys we both have, but are different
for key, index := range this.keys {
thisEntry, ok := this.lines[index].(entry)
if !ok { continue }
otherIndex, ok := other.keys[key]
if !ok {
diff[key] = struct { } { }
continue
}
if !this.lines[index].(entry).value.Equals(other.lines[otherIndex].(entry).value) {
otherEntry, ok := other.lines[otherIndex].(entry)
if !ok {
diff[key] = struct { } { }
continue
}
if !thisEntry.value.Equals(otherEntry.value) {
diff[key] = struct { } { }
}
}
// - keys only they have
for key := range other.keys {
if _, has := this.keys[key]; !has {
if otherHas, _ := other.Has(key); !otherHas {
continue
}
if thisHas, _ := this.Has(key); !thisHas {
diff[key] = struct { } { }
}
}

View File

@ -123,6 +123,36 @@ yetAnotherThing = 0.23498
}
}
func TestDiffReset (test *testing.T) {
file1 := parseFileString(test,
`key4=0
key1=value1
keyToDelete=true
# comment
key2=34`)
file2 := parseFileString(test,
`key1=value2
key2=34
anotherKeyToDelete=false
# comment
key3=0.2`)
file1.Reset("keyToDelete")
file2.Reset("anotherKeyToDelete")
diff := file1.Diff(file2)
correct := map[string] struct { } {
"key1": struct { } { },
"key3": struct { } { },
"key4": struct { } { },
}
if !maps.Equal(diff, correct) {
test.Error("diffs do not match")
test.Errorf("EXPECTED:\n%v", correct)
test.Errorf("GOT:\n%v", diff)
test.Fail()
}
}
func TestDiff (test *testing.T) {
file1 := parseFileString(test,
`key4=0