github.com/daniellockard/packer@v0.7.6-0.20141210173435-5a9390934716/post-processor/atlas/util.go (about) 1 package atlas 2 3 import ( 4 "math" 5 "strings" 6 ) 7 8 // longestCommonPrefix finds the longest common prefix for all the strings 9 // given as an argument, or returns the empty string if a prefix can't be 10 // found. 11 // 12 // This function just uses brute force instead of a more optimized algorithm. 13 func longestCommonPrefix(vs []string) string { 14 // Find the shortest string 15 var shortest string 16 length := math.MaxUint32 17 for _, v := range vs { 18 if len(v) < length { 19 shortest = v 20 length = len(v) 21 } 22 } 23 24 // Now go through and find a prefix to all the strings using this 25 // short string, which itself must contain the prefix. 26 for i := len(shortest); i > 0; i-- { 27 // We only care about prefixes with path seps 28 if shortest[i-1] != '/' { 29 continue 30 } 31 32 bad := false 33 prefix := shortest[0 : i] 34 for _, v := range vs { 35 if !strings.HasPrefix(v, prefix) { 36 bad = true 37 break 38 } 39 } 40 41 if !bad { 42 return prefix 43 } 44 } 45 46 return "" 47 }