1 package bazel 2 3 import ( 4 "strings" 5 ) 6 7 // This function only handles fully formed labels, not label expressions, such as 8 // '//...', '//pkg/edge/edgeadmin/...', etc. It does NOT perform any validation of 9 // the input labels because it assumes the input is derived from the output of 10 // Bazel directly. If you need to validate labels, do so before simplifying them. 11 // 12 // Will not simplify repository references for external repositories because 13 // the function does not know the workspace label (i.e., you can only simplify 14 // @edge_infra//pkg/edge to //pkg/edge if you know that you are currently in 15 // the @edge_infra workspace). 16 func SimplifyLabel(l string) string { 17 // remove '//' before splitting on path 18 tokens := strings.Split(strings.TrimPrefix(l, "//"), "/") 19 // get last token in package path, which is the package name + the target. 20 // e.g., pkg/edge/edgeadmin:cli -> cli:cli 21 // then separate target name from it by splitting on ":" 22 targetTokens := strings.Split(tokens[len(tokens)-1], ":") 23 // length of 1 means we already got the simplified label as input, e.g., 24 // pkg/edge/foo 25 if len(targetTokens) == 1 { 26 return strings.Join(tokens, "/") 27 } 28 // simplify target labels referring to target with same name as package 29 // e.g., pkg/edge:edge -> pkg/edge 30 if targetTokens[0] == targetTokens[1] { 31 tokens[len(tokens)-1] = targetTokens[0] 32 } 33 return strings.Join(tokens, "/") 34 } 35 36 // PackageFromLabel returns the package name for the given label, e.g.: 37 // 38 // //cmd/f8n/foo:container_push -> //cmd/f8n/foo 39 // 40 // If an invalid label is passed in, an empty string is returned. 41 func PackageFromLabel(l string) string { 42 return strings.Split(l, ":")[0] 43 } 44