github.com/erda-project/erda-infra@v1.0.9/providers/component-protocol/utils/cputil/provider_name.go (about) 1 // Copyright (c) 2021 Terminus, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package cputil 16 17 import ( 18 "fmt" 19 "strings" 20 21 "github.com/erda-project/erda-infra/pkg/strutil" 22 "github.com/erda-project/erda-infra/providers/component-protocol/cptype" 23 ) 24 25 const ( 26 componentProviderNamePrefix = "component-protocol.components." 27 ) 28 29 var ( 30 componentProviderDefaultNamespacePrefix = componentProviderNamePrefix + cptype.DefaultComponentNamespace + "." 31 ) 32 33 // MustGetScenarioAndCompNameFromProviderKey . 34 func MustGetScenarioAndCompNameFromProviderKey(providerKey string) (scenario, compName, instanceName string) { 35 scenario, compName, instanceName, err := GetScenarioAndCompNameFromProviderKey(providerKey) 36 if err != nil { 37 panic(err) 38 } 39 40 return scenario, compName, instanceName 41 } 42 43 // GetScenarioAndCompNameFromProviderKey . 44 func GetScenarioAndCompNameFromProviderKey(providerKey string) (scenario, compName, instanceName string, err error) { 45 // validate prefix 46 if !strutil.HasPrefixes(providerKey, componentProviderNamePrefix, componentProviderDefaultNamespacePrefix) { 47 return "", "", "", fmt.Errorf("invalid prefix") 48 } 49 // parse as std comp providerKey 50 ss := strings.SplitN(providerKey, ".", 4) 51 if len(ss) != 4 { 52 return "", "", "", fmt.Errorf("not standard provider key: %s", providerKey) 53 } 54 scenario = ss[2] 55 // default namespace doesn't belong to any scenario 56 if scenario == cptype.DefaultComponentNamespace { 57 scenario = "" 58 } 59 // split comp and instance name 60 compName, instanceName = splitCompAndInstance(ss[3]) 61 62 return 63 } 64 65 // splitCompAndInstance split compPartKey to compName and instanceName. 66 func splitCompAndInstance(compPartKey string) (compName, instanceName string) { 67 vv := strings.SplitN(compPartKey, "@", 2) 68 if len(vv) == 2 { 69 compName = vv[0] 70 instanceName = vv[1] 71 } else { 72 compName = compPartKey 73 instanceName = compName 74 } 75 return 76 } 77 78 // MakeComponentProviderName . 79 func MakeComponentProviderName(scenario, compType string) string { 80 return fmt.Sprintf("%s%s.%s", componentProviderNamePrefix, scenario, compType) 81 }