github.com/galaxyobe/gen@v0.0.0-20220910125335-392fa8f0990f/pkg/util/package.go (about) 1 /* 2 Copyright 2022 Galaxyobe. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package util 18 19 import ( 20 "go/ast" 21 "strings" 22 23 "github.com/galaxyobe/gen/third_party/gengo/parser" 24 ) 25 26 type PackageTypes []*PackageType 27 28 type PackageType struct { 29 Name string // pkg name 30 Types map[string]string // key: type's name value: type 31 } 32 33 func (p PackageType) IsExternalType(name string) bool { 34 for name_, type_ := range p.Types { 35 if name_ == name { 36 return strings.Contains(type_, ".") 37 } 38 } 39 return false 40 } 41 42 func (p PackageType) GetType(name string) string { 43 for name_, type_ := range p.Types { 44 if name_ == name { 45 return type_ 46 } 47 } 48 return "" 49 } 50 51 func NewPackageTypes(build *parser.Builder) (ret PackageTypes) { 52 for pkg, list := range build.GetParsedFiles() { 53 var files []*ast.File 54 for _, item := range list { 55 files = append(files, item.File) 56 } 57 ret = append(ret, &PackageType{ 58 Name: pkg, 59 Types: FindTypeNames(files), 60 }) 61 } 62 return 63 } 64 65 func (list PackageTypes) Find(pkg string) *PackageType { 66 for _, item := range list { 67 switch { 68 case item.Name == pkg: 69 return item 70 case strings.HasSuffix(item.Name, pkg): 71 return item 72 } 73 } 74 return nil 75 } 76 77 func (list PackageTypes) IsExternalType(pkg, name string) bool { 78 p := list.Find(pkg) 79 if p == nil { 80 return false 81 } 82 return p.IsExternalType(name) 83 }