errors.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package mg
  2. import (
  3. "errors"
  4. "fmt"
  5. )
  6. type fatalErr struct {
  7. code int
  8. error
  9. }
  10. func (f fatalErr) ExitStatus() int {
  11. return f.code
  12. }
  13. type exitStatus interface {
  14. ExitStatus() int
  15. }
  16. // Fatal returns an error that will cause mage to print out the
  17. // given args and exit with the given exit code.
  18. func Fatal(code int, args ...interface{}) error {
  19. return fatalErr{
  20. code: code,
  21. error: errors.New(fmt.Sprint(args...)),
  22. }
  23. }
  24. // Fatalf returns an error that will cause mage to print out the
  25. // given message and exit with an exit code of 1.
  26. func Fatalf(code int, format string, args ...interface{}) error {
  27. return fatalErr{
  28. code: code,
  29. error: fmt.Errorf(format, args...),
  30. }
  31. }
  32. // ExitStatus queries the error for an exit status. If the error is nil, it
  33. // returns 0. If the error does not implement ExitStatus() int, it returns 1.
  34. // Otherwise it retiurns the value from ExitStatus().
  35. func ExitStatus(err error) int {
  36. if err == nil {
  37. return 0
  38. }
  39. exit, ok := err.(exitStatus)
  40. if !ok {
  41. return 1
  42. }
  43. return exit.ExitStatus()
  44. }