From 7030add2fe69401d5c9a3a3925c299688b3a1bc7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Graber?= Date: Wed, 25 Sep 2024 16:55:12 -0400 Subject: [PATCH] incus/alias: Stable sorting of alias names MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #1237 Signed-off-by: Stéphane Graber --- cmd/incus/main_aliases.go | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/cmd/incus/main_aliases.go b/cmd/incus/main_aliases.go index c70f9f7d1c7..433a22fa744 100644 --- a/cmd/incus/main_aliases.go +++ b/cmd/incus/main_aliases.go @@ -8,6 +8,7 @@ import ( "path" "path/filepath" "regexp" + "slices" "strconv" "strings" @@ -31,7 +32,29 @@ func findAlias(aliases map[string]string, origArgs []string) ([]string, []string aliasKey := []string{} aliasValue := []string{} - for k, v := range aliases { + // Sort the aliases in a stable order, preferring the long multi-fields ones. + aliasNames := make([]string, 0, len(aliases)) + for k := range aliases { + aliasNames = append(aliasNames, k) + } + + slices.Sort(aliasNames) + slices.SortStableFunc(aliasNames, func(a, b string) int { + aFields := strings.Split(a, " ") + bFields := strings.Split(b, " ") + + if len(aFields) == len(bFields) { + return 0 + } else if len(aFields) < len(bFields) { + return 1 + } + + return -1 + }) + + for _, k := range aliasNames { + v := aliases[k] + foundAlias = true for i, key := range strings.Split(k, " ") { if len(origArgs) <= i+1 || origArgs[i+1] != key {