github.com/crosseyed/versionbump@v1.1.0/internal/app.go (about) 1 package internal 2 3 import ( 4 "fmt" 5 "os" 6 ) 7 8 const ( 9 Default = iota // Default 10 Testing // Testing 11 ) 12 13 // Assigned in main 14 var App AppHelper 15 16 // Helper for exits and errors. 17 // mode can be one of Default or Testing. 18 type AppHelper struct { 19 mode int 20 } 21 22 // Exit code wrapper. 23 // Used for unit testing. 24 func (a *AppHelper) Exit(code int) { 25 for { 26 switch a.mode { 27 case Default: 28 os.Exit(code) 29 case Testing: 30 panic(fmt.Sprintf("Exit(%d)", code)) 31 default: 32 // Unknown mode switching to default 33 a.mode = Default 34 } 35 } 36 } 37 38 // Check if an error was generated and run a callback. 39 // If err is nil the function returns. 40 // 41 // Print a standard error and exit: 42 // a := AppHelper{} 43 // err := errors.New("More cowbell") 44 // a.Errors(err, nil) 45 // 46 // Custom code on error: 47 // errcnt := 0 48 // efunc := func(err error) { 49 // e := fmt.Errorf("Got error: %v", err) 50 // log.Printf("%v", e) 51 // errcnt = errcnt + 1 52 // } 53 // err := SomeFunction() 54 // a.Errors(err, efunc) 55 // log.Printf("Error count: %d", errcnt) 56 func (a *AppHelper) Errors(err error, call func(err error)) { 57 if err == nil { 58 return 59 } 60 if call != nil { 61 call(err) 62 } else { 63 fmt.Printf("\x1b[31;1m%s\x1b[0m\n", err) 64 a.Exit(-1) 65 } 66 }