Skip to content

Commit

Permalink
Merge pull request #664 from rsteube/rawvalues-unique
Browse files Browse the repository at this point in the history
rawvalues: added unique
  • Loading branch information
rsteube authored Jan 4, 2023
2 parents 05222f9 + d47a9f6 commit a1a3382
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 18 deletions.
4 changes: 2 additions & 2 deletions action.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ import (

// Action indicates how to complete a flag or positional argument.
type Action struct {
rawValues []common.RawValue
callback CompletionCallback
meta common.Meta
rawValues common.RawValues
callback CompletionCallback
}

// ActionMap maps Actions to an identifier.
Expand Down
14 changes: 14 additions & 0 deletions internal/common/value.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,20 @@ func RawValuesFrom(values ...string) RawValues {
return rawValues
}

func (r RawValues) Unique() RawValues {
uniqueRawValues := make(map[string]RawValue)
for _, value := range r {
uniqueRawValues[value.Value] = value
}

rawValues := make([]RawValue, 0, len(uniqueRawValues))
for _, value := range uniqueRawValues {
rawValues = append(rawValues, value)
}
sort.Sort(ByDisplay(rawValues))
return rawValues
}

func (r RawValues) contains(s string) bool {
for _, value := range r {
if value.Value == s {
Expand Down
21 changes: 5 additions & 16 deletions invokedAction.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ type InvokedAction struct {
// a := carapace.ActionValues("A", "B", "C").Invoke(c)
// b := a.Filter([]string{"B"}) // ["A", "C"]
func (a InvokedAction) Filter(values []string) InvokedAction {
a.rawValues = common.RawValues(a.rawValues).Filter(values...)
a.rawValues = a.rawValues.Filter(values...)
return a
}

Expand All @@ -29,23 +29,12 @@ func (a InvokedAction) Filter(values []string) InvokedAction {
// b := carapace.ActionValues("B", "C").Invoke(c)
// c := a.Merge(b) // ["A", "B", "C"]
func (a InvokedAction) Merge(others ...InvokedAction) InvokedAction {
uniqueRawValues := make(map[string]common.RawValue)
var meta common.Meta
for _, other := range append([]InvokedAction{a}, others...) {
for _, c := range other.rawValues {
uniqueRawValues[c.Value] = c
}
meta.Merge(other.meta)
}

rawValues := make([]common.RawValue, 0, len(uniqueRawValues))
for _, c := range uniqueRawValues {
rawValues = append(rawValues, c)
a.rawValues = append(a.rawValues, other.rawValues...)
a.meta.Merge(other.meta)
}

invoked := InvokedAction{Action{rawValues: rawValues}}
invoked.meta.Merge(meta)
return invoked
a.rawValues = a.rawValues.Unique()
return a
}

// Prefix adds a prefix to values (only the ones inserted, not the display values)
Expand Down

0 comments on commit a1a3382

Please sign in to comment.