├── .gitignore ├── LICENSE ├── README.md ├── go.mod ├── iferr_test.go ├── main.go └── vim └── ftplugin └── go └── iferr.vim /.gitignore: -------------------------------------------------------------------------------- 1 | iferr 2 | iferr.exe 3 | tags 4 | tmp/ 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2018 MURAOKA Taro 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Generate "if err != nil {" block 2 | 3 | Generate `if err != nil {` block for current function. 4 | 5 | ## Usage 6 | 7 | Install and update by 8 | 9 | ```console 10 | $ go install github.com/koron/iferr@latest 11 | ``` 12 | 13 | Run, it get `if err != nil {` block for the postion at 1234 bytes. 14 | 15 | ```console 16 | $ iferr -pos 1234 < main.go 17 | if err != nil { 18 | return "" 19 | } 20 | ``` 21 | 22 | ```console 23 | $ iferr -pos 1234 < main.go 24 | if err != nil { 25 | return "" 26 | } 27 | ``` 28 | 29 | Customize your error message: 30 | ```console 31 | $ iferr -pos 110 -message 'fmt.Errorf("failed to %w", err)' < main.go 32 | if err != nil { 33 | return 0, fmt.Errorf("failed to %w", err) 34 | } 35 | ``` 36 | 37 | ## Vim plugin 38 | 39 | Copy `vim/ftplugin/go/iferr.vim` as `~/.vim/ftplugin/go/iferr.vim`. 40 | 41 | It defines `:IfErr` command for go filetype. It will insert `if err != nil {` 42 | block at next line of the cursor. 43 | 44 | Before: 45 | 46 | ```go 47 | package foo 48 | 49 | import "io" 50 | 51 | func Foo() (io.Reader, error) { // the cursor on this line. 52 | } 53 | ``` 54 | 55 | Run `:IfErr` then you will get: 56 | 57 | ```go 58 | package foo 59 | 60 | import "io" 61 | 62 | func Foo() (io.Reader, error) { 63 | if err != nil { 64 | return nil, err 65 | } 66 | } // new cursor is at here. 67 | ``` 68 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/koron/iferr 2 | 3 | go 1.21.5 4 | -------------------------------------------------------------------------------- /iferr_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "strings" 6 | "testing" 7 | ) 8 | 9 | func iferrStr(in string, pos int, errMsg string) (string, error) { 10 | out := &bytes.Buffer{} 11 | r := strings.NewReader(in) 12 | err := iferr(out, r, pos, errMsg) 13 | if err != nil { 14 | return "", err 15 | } 16 | return out.String(), nil 17 | } 18 | 19 | func iferrOK(t *testing.T, fn string, off int, errMsg, exp string) { 20 | const ( 21 | fnPre = "package main\nfunc foo() " 22 | fnPost = " {}" 23 | actPre = "if err != nil {\n\treturn " 24 | actPost = "\n}\n" 25 | ) 26 | 27 | act, err := iferrStr(fnPre+fn, len(fnPre)+1+off, errMsg) 28 | if err != nil { 29 | t.Errorf("iferr() is failed: %s for %q", err, fn) 30 | return 31 | } 32 | if !strings.HasPrefix(act, actPre) || !strings.HasSuffix(act, actPost) { 33 | t.Errorf("iferr() returns with unexpected prefix or suffix: %q", act) 34 | return 35 | } 36 | act = act[len(actPre) : len(act)-len(actPost)] 37 | if act != exp { 38 | t.Errorf("iferr() returns unexpected: actual=%q expect=%q", act, exp) 39 | return 40 | } 41 | } 42 | 43 | func TestIferr(t *testing.T) { 44 | iferrOK(t, `(interface{}, error)`, 0, `err`, `nil, err`) 45 | iferrOK(t, `(map[string]struct{}, error)`, 0, `err`, `nil, err`) 46 | iferrOK(t, `(chan bool, error)`, 0, `err`, `nil, err`) 47 | iferrOK(t, `(bool, error)`, 0, `err`, `false, err`) 48 | iferrOK(t, `(foo, error)`, 0, `err`, `foo{}, err`) 49 | iferrOK(t, `(*foo, error)`, 0, `err`, `nil, err`) 50 | iferrOK(t, `(*foo, error)`, 0, `err`, `nil, err`) 51 | iferrOK(t, `(*foo, error)`, 0, `err`, `nil, err`) 52 | iferrOK(t, `(*foo, error)`, 0, `err`, `nil, err`) 53 | iferrOK(t, `(*foo, error)`, 0, `fmt.Errorf("failed to %v", err)`, `nil, fmt.Errorf("failed to %v", err)`) 54 | } 55 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "flag" 6 | "fmt" 7 | "go/ast" 8 | "go/parser" 9 | "go/token" 10 | "io" 11 | "log" 12 | "os" 13 | "strings" 14 | ) 15 | 16 | const noname = "(no name)" 17 | 18 | var dbgLog *log.Logger 19 | 20 | var isNum = map[string]struct{}{ 21 | "int": {}, 22 | "int16": {}, 23 | "int32": {}, 24 | "int64": {}, 25 | "uint": {}, 26 | "uint16": {}, 27 | "uint32": {}, 28 | "uint64": {}, 29 | "float": {}, 30 | "float32": {}, 31 | "float64": {}, 32 | } 33 | 34 | func logd(s string, args ...interface{}) { 35 | if dbgLog == nil { 36 | return 37 | } 38 | dbgLog.Printf(s, args...) 39 | } 40 | 41 | type visitor struct { 42 | pos token.Pos 43 | err error 44 | ft *ast.FuncType 45 | fn string 46 | } 47 | 48 | func (v *visitor) Visit(node ast.Node) ast.Visitor { 49 | if node == nil { 50 | return nil 51 | } 52 | switch x := node.(type) { 53 | case *ast.FuncDecl: 54 | x, ok := node.(*ast.FuncDecl) 55 | if !ok { 56 | return v 57 | } 58 | fname := noname 59 | if x.Name != nil { 60 | fname = x.Name.Name 61 | } 62 | fname = x.Name.Name 63 | if v.pos < x.Pos() || v.pos > x.End() { 64 | return nil 65 | } 66 | if x.Type == nil { 67 | return v 68 | } 69 | v.fn = fname 70 | v.ft = x.Type 71 | logd("found a FuncDecl: name=%s pos=%d end=%d", v.fn, x.Pos(), x.End()) 72 | return v 73 | case *ast.FuncLit: 74 | if x.Type == nil || x.Body == nil { 75 | return nil 76 | } 77 | if v.pos < x.Pos() || v.pos > x.End() { 78 | return nil 79 | } 80 | v.fn = noname 81 | v.ft = x.Type 82 | logd("found a FuncLit: pos=%d end=%d", x.Pos(), x.End()) 83 | return v 84 | default: 85 | return v 86 | } 87 | } 88 | 89 | type field struct { 90 | name string 91 | } 92 | 93 | func toTypes(fl *ast.FieldList) []ast.Expr { 94 | if fl == nil || len(fl.List) == 0 { 95 | return nil 96 | } 97 | types := make([]ast.Expr, 0, len(fl.List)) 98 | for _, f := range fl.List { 99 | types = append(types, f.Type) 100 | } 101 | return types 102 | } 103 | 104 | func typeString(x ast.Expr) string { 105 | switch t := x.(type) { 106 | case *ast.Ident: 107 | return t.Name 108 | case *ast.SelectorExpr: 109 | if _, ok := t.X.(*ast.Ident); ok { 110 | return typeString(t.X) + "." + t.Sel.Name 111 | } 112 | case *ast.StarExpr: 113 | return "*" + typeString(t.X) 114 | case *ast.ArrayType: 115 | return "[]" + typeString(t.Elt) 116 | case *ast.InterfaceType: 117 | return "interface{}" 118 | case *ast.MapType: 119 | return "map[" + typeString(t.Key) + "]" + typeString(t.Value) 120 | case *ast.StructType: 121 | return "struct{}" 122 | case *ast.ChanType: 123 | return "chan " + typeString(t.Value) 124 | default: 125 | logd("typeString: unsupported type: %T", x) 126 | } 127 | return "" 128 | } 129 | 130 | func writeIferr(w io.Writer, types []ast.Expr, errMsg string) error { 131 | if len(types) == 0 { 132 | _, err := fmt.Fprint(w, "if err != nil {\n\treturn\n}\n") 133 | return err 134 | } 135 | bb := &bytes.Buffer{} 136 | bb.WriteString("if err != nil {\n\treturn ") 137 | for i, t := range types { 138 | if i > 0 { 139 | bb.WriteString(", ") 140 | } 141 | ts := typeString(t) 142 | logd(" type#%d %s", i, ts) 143 | if ts == "bool" { 144 | bb.WriteString(`false`) 145 | continue 146 | } 147 | if ts == "error" { 148 | bb.WriteString(errMsg) 149 | continue 150 | } 151 | if ts == "string" { 152 | bb.WriteString(`""`) 153 | continue 154 | } 155 | if ts == "interface{}" { 156 | bb.WriteString(`nil`) 157 | continue 158 | } 159 | if _, ok := isNum[ts]; ok { 160 | bb.WriteString("0") 161 | continue 162 | } 163 | if strings.HasPrefix(ts, "[]") { 164 | bb.WriteString("nil") 165 | continue 166 | } 167 | if strings.HasPrefix(ts, "map[") { 168 | bb.WriteString("nil") 169 | continue 170 | } 171 | if strings.HasPrefix(ts, "chan ") { 172 | bb.WriteString("nil") 173 | continue 174 | } 175 | if strings.HasPrefix(ts, "*") { 176 | bb.WriteString("nil") 177 | continue 178 | } 179 | // treat it as an interface when type name has "." 180 | if strings.Index(ts, ".") >= 0 { 181 | bb.WriteString("nil") 182 | continue 183 | } 184 | // TODO: support more types. 185 | bb.WriteString(ts) 186 | bb.WriteString("{}") 187 | } 188 | bb.WriteString("\n}\n") 189 | io.Copy(w, bb) 190 | return nil 191 | } 192 | 193 | func iferr(w io.Writer, r io.Reader, pos int, errMsg string) error { 194 | fset := token.NewFileSet() 195 | file, err := parser.ParseFile(fset, "iferr.go", r, 0) 196 | if err != nil { 197 | return err 198 | } 199 | v := &visitor{pos: token.Pos(pos)} 200 | ast.Walk(v, file) 201 | if v.err != nil { 202 | return err 203 | } 204 | if v.ft == nil { 205 | return fmt.Errorf("no functions at %d", pos) 206 | } 207 | types := toTypes(v.ft.Results) 208 | return writeIferr(w, types, errMsg) 209 | } 210 | 211 | func main() { 212 | var ( 213 | pos int 214 | debug bool 215 | errMsg string 216 | ) 217 | flag.IntVar(&pos, "pos", 0, "position of cursor") 218 | flag.BoolVar(&debug, "debug", false, "enable debug log") 219 | flag.StringVar(&errMsg, "message", "err", "choose a custom error message") 220 | flag.Parse() 221 | if debug { 222 | dbgLog = log.New(os.Stderr, "D ", 0) 223 | } 224 | err := iferr(os.Stdout, os.Stdin, pos, errMsg) 225 | if err != nil { 226 | fmt.Fprintln(os.Stderr, err.Error()) 227 | os.Exit(1) 228 | } 229 | } 230 | -------------------------------------------------------------------------------- /vim/ftplugin/go/iferr.vim: -------------------------------------------------------------------------------- 1 | scriptencoding utf-8 2 | 3 | function! s:IfErr() 4 | let bpos = wordcount()['cursor_bytes'] 5 | let out = systemlist('iferr -pos ' . bpos, bufnr('%')) 6 | if len(out) == 1 7 | return 8 | endif 9 | let pos = getcurpos() 10 | call append(pos[1], out) 11 | silent normal! j=2j 12 | call setpos('.', pos) 13 | silent normal! 4j 14 | endfunction 15 | 16 | command! -buffer -nargs=0 IfErr call s:IfErr() 17 | --------------------------------------------------------------------------------