github.com/jmigpin/editor@v1.6.0/util/goutil/misc.go (about) 1 package goutil 2 3 import ( 4 "fmt" 5 "go/ast" 6 "go/printer" 7 "go/token" 8 "io" 9 "log" 10 "os" 11 "runtime" 12 "runtime/pprof" 13 "strings" 14 ) 15 16 //---------- 17 18 func PrintAstFile(w io.Writer, fset *token.FileSet, astFile *ast.File) error { 19 // TODO: without tabwidth set, it won't output the source correctly 20 21 // print with source positions from original file 22 23 // Fail: has struct fields without spaces "field int"->"fieldint" 24 //cfg := &printer.Config{Mode: printer.SourcePos | printer.TabIndent} 25 26 // Fail: has stmts split with comments in the middle 27 //cfg := &printer.Config{Mode: printer.SourcePos | printer.TabIndent | printer.UseSpaces} 28 29 cfg := &printer.Config{Mode: printer.SourcePos, Tabwidth: 4} 30 31 return cfg.Fprint(w, fset, astFile) 32 } 33 34 //---------- 35 36 // frame callers 37 38 func Printfc(skip int, f string, args ...interface{}) { 39 fmt.Print(Sprintfc(skip, f, args...)) 40 } 41 func Sprintfc(skip int, f string, args ...interface{}) string { 42 pc, _, _, ok := runtime.Caller(1 + skip) 43 if ok { 44 details := runtime.FuncForPC(pc) 45 if details != nil { 46 //u := details.Name() 47 //i := strings.Index(u, "(") 48 //if i > 0 { 49 // u = u[i:] 50 //} 51 //return fmt.Sprintf(u+": "+f, args...) 52 53 f2, l := details.FileLine(pc) 54 u := fmt.Sprintf("%v:%v", f2, l) 55 return fmt.Sprintf(u+": "+f, args...) 56 } 57 } 58 return fmt.Sprintf(f, args...) 59 } 60 61 // ---------- 62 // 63 //godebug:annotatefile 64 func TodoError() error { 65 return fmt.Errorf(Sprintfc(1, "TODO")) 66 } 67 func TodoErrorStr(s string) error { 68 return fmt.Errorf(Sprintfc(1, "TODO: %v", s)) 69 } 70 func TodoErrorType(t interface{}) error { 71 return fmt.Errorf(Sprintfc(1, "TODO: %T", t)) 72 } 73 74 //---------- 75 76 func Trace(n int) (string, int, string) { 77 pc, file, line, ok := runtime.Caller(n + 1) 78 if !ok { 79 return "?", 0, "?" 80 } 81 82 fn := runtime.FuncForPC(pc) 83 if fn == nil { 84 return file, line, "?" 85 } 86 87 return file, line, fn.Name() 88 } 89 90 //---------- 91 92 func JoinPathLists(w ...string) string { 93 return strings.Join(w, string(os.PathListSeparator)) 94 } 95 96 //---------- 97 98 // go test -cpuprofile cpu.prof -memprofile mem.prof 99 // go tool pprof cpu.prof 100 // view with a browser: 101 // go tool pprof -http=:8000 cpu.prof 102 103 var profFile *os.File 104 105 func StartCPUProfile() error { 106 filename := "cpu.prof" 107 f, err := os.Create(filename) 108 if err != nil { 109 return err 110 } 111 profFile = f 112 log.Printf("profile cpu: %v\n", filename) 113 return pprof.StartCPUProfile(f) 114 } 115 116 func StopCPUProfile() error { 117 pprof.StopCPUProfile() 118 return profFile.Close() 119 }