github.com/Konstantin8105/c4go@v0.0.0-20240505174241-768bb1c65a51/program/import.go (about) 1 package program 2 3 import ( 4 "strconv" 5 "strings" 6 ) 7 8 // Imports returns all of the Go imports for this program. 9 func (p *Program) Imports() []string { 10 return p.imports 11 } 12 13 // AddImport will append an absolute import if it is unique to the list of 14 // imports for this program. 15 func (p *Program) AddImport(importPath string) { 16 quotedImportPath := strconv.Quote(importPath) 17 18 if len(importPath) == 0 { 19 return 20 } 21 22 for _, i := range p.imports { 23 if i == quotedImportPath { 24 // Already imported, ignore. 25 return 26 } 27 } 28 29 p.imports = append(p.imports, quotedImportPath) 30 } 31 32 // AddImports is a convenience method for adding multiple imports. 33 func (p *Program) AddImports(importPaths ...string) { 34 for _, importPath := range importPaths { 35 p.AddImport(importPath) 36 } 37 } 38 39 // ImportType imports a package for a fully qualified type and returns the local 40 // type name. For example: 41 // 42 // t := p.ImportType("github.com/Konstantin8105/c4go/noarch.CtRuneT") 43 // 44 // Will import "github.com/Konstantin8105/c4go/noarch" and return (value of t) 45 // "noarch.CtRuneT". 46 func (p *Program) ImportType(name string) string { 47 if strings.Contains(name, ".") { 48 parts := strings.Split(name, ".") 49 p.AddImport(strings.Join(parts[:len(parts)-1], ".")) 50 51 parts2 := strings.Split(name, "/") 52 return parts2[len(parts2)-1] 53 } 54 55 return name 56 }