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