github.com/muhammadn/cortex@v1.9.1-0.20220510110439-46bb7000d03d/tools/doc-generator/util.go (about) 1 package main 2 3 import ( 4 "math" 5 "strings" 6 ) 7 8 func findFlagsPrefix(flags []string) []string { 9 if len(flags) == 0 { 10 return flags 11 } 12 13 // Split the input flags input tokens separated by "." 14 // because the want to find the prefix where segments 15 // are dot-separated. 16 tokens := [][]string{} 17 for _, flag := range flags { 18 tokens = append(tokens, strings.Split(flag, ".")) 19 } 20 21 // Find the shortest tokens. 22 minLength := math.MaxInt32 23 for _, t := range tokens { 24 if len(t) < minLength { 25 minLength = len(t) 26 } 27 } 28 29 // We iterate backward to find common suffixes. Each time 30 // a common suffix is found, we remove it from the tokens. 31 outer: 32 for i := 0; i < minLength; i++ { 33 lastToken := tokens[0][len(tokens[0])-1] 34 35 // Interrupt if the last token is different across the flags. 36 for _, t := range tokens { 37 if t[len(t)-1] != lastToken { 38 break outer 39 } 40 } 41 42 // The suffix token is equal across all flags, so we 43 // remove it from all of them and re-iterate. 44 for i, t := range tokens { 45 tokens[i] = t[:len(t)-1] 46 } 47 } 48 49 // The remaining tokens are the different flags prefix, which we can 50 // now merge with the ".". 51 prefixes := []string{} 52 for _, t := range tokens { 53 prefixes = append(prefixes, strings.Join(t, ".")) 54 } 55 56 return prefixes 57 }