Skip to content

Commit

Permalink
added diff
Browse files Browse the repository at this point in the history
  • Loading branch information
rsteube committed Feb 24, 2024
1 parent e8de268 commit 4feadcb
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
44 changes: 44 additions & 0 deletions diff.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package carapace

import (
"github.com/rsteube/carapace/internal/common"
"github.com/rsteube/carapace/pkg/style"
)

// Diff compares values of two actions.
// It overrides the style to hightlight changes.
//
// red: only present in original
// dim: present in both
// green: only present in new
func Diff(original, new Action) Action {
return ActionCallback(func(c Context) Action {
invokedBatch := Batch(
original,
new,
).Invoke(c)

merged := make(map[string]common.RawValue)
for _, v := range invokedBatch[0].action.rawValues {
v.Style = style.Red
merged[v.Value] = v
}

for _, v := range invokedBatch[1].action.rawValues {
if _, ok := merged[v.Value]; ok {
v.Style = style.Dim
merged[v.Value] = v
} else {
v.Style = style.Green
merged[v.Value] = v
}
}

mergedBatch := invokedBatch.Merge()
mergedBatch.action.rawValues = make(common.RawValues, 0)
for _, v := range merged {
mergedBatch.action.rawValues = append(mergedBatch.action.rawValues, v)
}
return mergedBatch.ToA()
})
}
27 changes: 27 additions & 0 deletions diff_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package carapace

import (
"testing"

"github.com/rsteube/carapace/pkg/style"
)

func TestDiff(t *testing.T) {
original := ActionValues(
"removed",
"same",
)
new := ActionValues(
"same",
"added",
)

assertEqual(t,
Diff(original, new).Invoke(NewContext()),
ActionStyledValues(
"removed", style.Red,
"same", style.Dim,
"added", style.Green,
).Invoke(NewContext()),
)
}

0 comments on commit 4feadcb

Please sign in to comment.