github.com/artisanhe/tools@v1.0.1-0.20210607022958-19a8fef2eb04/codegen/utils.go (about) 1 package codegen 2 3 import ( 4 "fmt" 5 "go/build" 6 "log" 7 "os" 8 "path" 9 "path/filepath" 10 "strings" 11 12 "github.com/fatih/color" 13 ) 14 15 func GetPackageImportPath(dir string) string { 16 pkg, err := build.ImportDir(dir, build.FindOnly) 17 if err != nil { 18 panic(err) 19 } 20 return pkg.ImportPath 21 } 22 23 func IsGoFile(filename string) bool { 24 return filepath.Ext(filename) == ".go" 25 } 26 27 func IsGoTextFile(filename string) bool { 28 return strings.HasSuffix(filepath.Base(filename), "_test.go") 29 } 30 31 func GeneratedSuffix(filename string) string { 32 dir := filepath.Dir(filename) 33 base := filepath.Base(filename) 34 ext := filepath.Ext(filename) 35 36 if IsGoFile(filename) && IsGoTextFile(filename) { 37 base = strings.Replace(base, "_test.go", "__generated_test.go", -1) 38 } else { 39 base = strings.Replace(base, ext, fmt.Sprintf("__generated%s", ext), -1) 40 41 } 42 return fmt.Sprintf("%s/%s", dir, base) 43 } 44 45 func mustWriteFile(filename string, content string) int { 46 dir := filepath.Dir(filename) 47 48 if dir != "" { 49 os.MkdirAll(dir, os.ModePerm) 50 } 51 52 f, err := os.Create(filename) 53 if err != nil { 54 panic(err) 55 } 56 defer f.Close() 57 58 n3, err := f.WriteString(content) 59 if err != nil { 60 panic(err) 61 } 62 f.Sync() 63 64 return n3 65 } 66 67 func WriteFile(filename string, content string) { 68 pwd, _ := os.Getwd() 69 if filepath.IsAbs(filename) { 70 filename, _ = filepath.Rel(pwd, filename) 71 } 72 n3 := mustWriteFile(filename, content) 73 log.Printf(color.GreenString("Generated file to %s (%d KiB)", color.BlueString(path.Join(pwd, filename)), n3/1024)) 74 } 75 76 func CreateTempFile(filename, content string) func() { 77 mustWriteFile(filename, content) 78 return func() { 79 os.RemoveAll(filepath.Dir(filename)) 80 } 81 }