Sort found variables by length descending (#33875)
<!-- Add the related story/sub-task/bug number, like Resolves #123, or remove if NA --> **Related issue:** Resolves #33502 This fixes the mentioned issue by always sorting the found variables in length descending, to ensure we process the longest variables first, avoiding us processing a smaller variation of a longer variable first breaking substitution. # Checklist for submitter If some of the following don't apply, delete the relevant line. - [x] Changes file added for user-visible changes in `changes/`, `orbit/changes/` or `ee/fleetd-chrome/changes`. See [Changes files](https://github.com/fleetdm/fleet/blob/main/docs/Contributing/guides/committing-changes.md#changes-files) for more information. ## Testing - [x] Added/updated automated tests - [x] QA'd all new/changed functionality manually
This commit is contained in:
@@ -0,0 +1 @@
|
||||
* Fixed an issue where longer variable names ($FLEET_VAR_HOST_END_USER_IDP_USERNAME_LOCAL_PART) with the same base ($FLEET_VAR_HOST_END_USER_IDP_USERNAME) was not processed in the right order.
|
||||
@@ -5,6 +5,7 @@ package variables
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -59,7 +60,14 @@ func FindKeepDuplicates(contents string) []string {
|
||||
}
|
||||
}
|
||||
}
|
||||
return result
|
||||
|
||||
// sort result array by length descending, to ensure longer variables are processed first
|
||||
sortedResults := make([]string, len(result))
|
||||
copy(sortedResults, result)
|
||||
sort.Slice(sortedResults, func(i, j int) bool {
|
||||
return len(sortedResults[i]) > len(sortedResults[j])
|
||||
})
|
||||
return sortedResults
|
||||
}
|
||||
|
||||
// dedupe removes duplicates from the slice and returns a map for O(1) lookups.
|
||||
|
||||
@@ -102,7 +102,16 @@ func TestFindKeepDuplicates(t *testing.T) {
|
||||
{
|
||||
name: "mixed variables with duplicates",
|
||||
content: "$FLEET_VAR_HOST_UUID, $FLEET_VAR_HOST_EMAIL, ${FLEET_VAR_HOST_UUID}",
|
||||
expected: []string{"HOST_UUID", "HOST_EMAIL", "HOST_UUID"},
|
||||
expected: []string{"HOST_EMAIL", "HOST_UUID", "HOST_UUID"},
|
||||
},
|
||||
{
|
||||
name: "sorted by length",
|
||||
content: "$FLEET_VAR_HOST_END_USER_IDP_USERNAME, $FLEET_VAR_HOST_END_USER_IDP_USERNAME_LOCAL_PART, $FLEET_VAR_HOST_UUID",
|
||||
expected: []string{
|
||||
"HOST_END_USER_IDP_USERNAME_LOCAL_PART",
|
||||
"HOST_END_USER_IDP_USERNAME",
|
||||
"HOST_UUID",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user