golang.org/x/exp@v0.0.0-20240506185415-9bf2ced13842/cmd/gorelease/errors.go (about) 1 // Copyright 2019 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package main 6 7 import ( 8 "errors" 9 "flag" 10 "fmt" 11 "os/exec" 12 "strings" 13 14 "golang.org/x/mod/module" 15 ) 16 17 type usageError struct { 18 err error 19 } 20 21 func usageErrorf(format string, args ...interface{}) error { 22 return &usageError{err: fmt.Errorf(format, args...)} 23 } 24 25 const usageText = `usage: gorelease [-base=version] [-version=version]` 26 27 func (e *usageError) Error() string { 28 msg := "" 29 if !errors.Is(e.err, flag.ErrHelp) { 30 msg = e.err.Error() 31 } 32 return usageText + "\n" + msg + "\nFor more information, run go doc golang.org/x/exp/cmd/gorelease" 33 } 34 35 type baseVersionError struct { 36 err error 37 modPath string 38 } 39 40 func (e *baseVersionError) Error() string { 41 firstVersion := "v0.1.0" 42 _, major, _ := module.SplitPathVersion(e.modPath) 43 if major != "" { 44 firstVersion = major[1:] + ".0.0" 45 } 46 47 return fmt.Sprintf("could not find base version. Consider setting -version=%s if this is a first release, or explicitly set -base=none: %v", firstVersion, e.err) 48 } 49 50 func (e *baseVersionError) Unwrap() error { 51 return e.err 52 } 53 54 type downloadError struct { 55 m module.Version 56 err error 57 } 58 59 func (e *downloadError) Error() string { 60 msg := e.err.Error() 61 sep := " " 62 if strings.Contains(msg, "\n") { 63 sep = "\n" 64 } 65 return fmt.Sprintf("error downloading module %s@%s:%s%s", e.m.Path, e.m.Version, sep, msg) 66 } 67 68 // cleanCmdError simplifies error messages from os/exec.Cmd.Run. 69 // For ExitErrors, it trims and returns stderr. This is useful for go commands 70 // that print well-formatted errors. By default, ExitError prints the exit 71 // status but not stderr. 72 // 73 // cleanCmdError returns other errors unmodified. 74 func cleanCmdError(err error) error { 75 if xerr, ok := err.(*exec.ExitError); ok { 76 if stderr := strings.TrimSpace(string(xerr.Stderr)); stderr != "" { 77 return errors.New(stderr) 78 } 79 } 80 return err 81 }