From a31f670d4eb62d18809648243e4fc251712d524e Mon Sep 17 00:00:00 2001 From: Dave Rolsky Date: Wed, 11 Apr 2018 17:27:16 -0700 Subject: [PATCH] Fix path alias feature to always sort paths by reverse length If you have aliases set up for two paths where one is a subset of the other (for example /home/autarch/go and /home/autarch/go/src/github.com/autarch/project) the alias that was applied would be random depending on the order of map iteration. Now we sort the map keys so we look at longest paths first. --- segment-cwd.go | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/segment-cwd.go b/segment-cwd.go index 6dc40441..b8dac4b7 100644 --- a/segment-cwd.go +++ b/segment-cwd.go @@ -2,6 +2,7 @@ package main import ( "os" + "sort" "strings" ) @@ -15,15 +16,33 @@ type pathSegment struct { alias bool } +type byRevLength []string + +func (s byRevLength) Len() int { + return len(s) +} +func (s byRevLength) Swap(i, j int) { + s[i], s[j] = s[j], s[i] +} +func (s byRevLength) Less(i, j int) bool { + return len(s[i]) > len(s[j]) +} + func maybeAliasPathSegments(p *powerline, pathSegments []pathSegment) []pathSegment { if p.pathAliases == nil { return pathSegments } + keys := make([]string, len(p.pathAliases)) + for k := range p.pathAliases { + keys = append(keys, k) + } + sort.Sort(byRevLength(keys)) + Aliases: - for p, alias := range p.pathAliases { + for _, k := range keys { // This turns a string like "foo/bar/baz" into an array of strings. - path := strings.Split(p, "/") + path := strings.Split(k, "/") // If the path has 3 elements, we know we should look at pathSegments // in 3-element chunks. @@ -34,6 +53,8 @@ Aliases: continue Aliases } + alias := p.pathAliases[k] + Segments: // We want to see if that array of strings exists in pathSegments. for i, _ := range pathSegments {