github.com/cloudwego/kitex@v0.9.0/tool/internal_pkg/pluginmode/protoc/util.go (about) 1 // Copyright 2021 CloudWeGo Authors 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 protoc 16 17 import ( 18 "go/token" 19 "strings" 20 "unicode" 21 22 "github.com/cloudwego/kitex/tool/internal_pkg/util" 23 ) 24 25 func goSanitized(s string) string { 26 // replace invalid characters with '_' 27 s = strings.Map(func(r rune) rune { 28 if !unicode.IsLetter(r) && !unicode.IsDigit(r) { 29 return '_' 30 } 31 return r 32 }, s) 33 34 // avoid invalid identifier 35 if !token.IsIdentifier(s) { 36 return "_" + s 37 } 38 return s 39 } 40 41 type pathElements struct { 42 module string // module name 43 prefix string // prefix of import path for generated codes 44 } 45 46 func (p *pathElements) getImportPath(pkg string) (path string, ok bool) { 47 parts := strings.Split(pkg, "/") 48 if len(parts) == 0 { 49 // malformed import path 50 return "", false 51 } 52 53 if strings.HasPrefix(pkg, p.prefix) { 54 return pkg, true 55 } 56 if strings.Contains(parts[0], ".") || (p.module != "" && strings.HasPrefix(pkg, p.module)) { 57 // already a complete import path, but outside the target path 58 return "", false 59 } 60 // incomplete import path 61 return util.JoinPath(p.prefix, pkg), true 62 }