lotus/cli/helper.go

93 lines
1.7 KiB
Go
Raw Permalink Normal View History

2020-07-23 18:46:22 +00:00
package cli
import (
"fmt"
"io"
2020-07-23 18:46:22 +00:00
"os"
"os/signal"
"syscall"
2020-07-23 18:46:22 +00:00
ufcli "github.com/urfave/cli/v2"
2020-07-23 18:48:48 +00:00
"golang.org/x/xerrors"
2020-07-23 18:46:22 +00:00
)
type PrintHelpErr struct {
Err error
Ctx *ufcli.Context
2020-07-23 18:46:22 +00:00
}
func (e *PrintHelpErr) Error() string {
return e.Err.Error()
}
func (e *PrintHelpErr) Unwrap() error {
return e.Err
}
func (e *PrintHelpErr) Is(o error) bool {
_, ok := o.(*PrintHelpErr)
return ok
}
func ShowHelp(cctx *ufcli.Context, err error) error {
2020-07-23 18:46:22 +00:00
return &PrintHelpErr{Err: err, Ctx: cctx}
}
func IncorrectNumArgs(cctx *ufcli.Context) error {
return ShowHelp(cctx, fmt.Errorf("incorrect number of arguments, got %d", cctx.NArg()))
}
func RunApp(app *ufcli.App) {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGTERM, syscall.SIGINT)
go func() {
<-c
os.Exit(1)
}()
2020-07-23 18:46:22 +00:00
if err := app.Run(os.Args); err != nil {
if os.Getenv("LOTUS_DEV") != "" {
log.Warnf("%+v", err)
} else {
2020-10-10 13:38:14 +00:00
fmt.Fprintf(os.Stderr, "ERROR: %s\n\n", err) // nolint:errcheck
2020-07-23 18:46:22 +00:00
}
2020-07-23 18:48:48 +00:00
var phe *PrintHelpErr
if xerrors.As(err, &phe) {
_ = ufcli.ShowCommandHelp(phe.Ctx, phe.Ctx.Command.Name)
2020-07-23 18:46:22 +00:00
}
os.Exit(1)
}
}
type AppFmt struct {
app *ufcli.App
Stdin io.Reader
}
func NewAppFmt(a *ufcli.App) *AppFmt {
var stdin io.Reader
istdin, ok := a.Metadata["stdin"]
if ok {
stdin = istdin.(io.Reader)
} else {
stdin = os.Stdin
}
return &AppFmt{app: a, Stdin: stdin}
}
func (a *AppFmt) Print(args ...interface{}) {
fmt.Fprint(a.app.Writer, args...)
}
func (a *AppFmt) Println(args ...interface{}) {
fmt.Fprintln(a.app.Writer, args...)
}
func (a *AppFmt) Printf(fmtstr string, args ...interface{}) {
fmt.Fprintf(a.app.Writer, fmtstr, args...)
}
func (a *AppFmt) Scan(args ...interface{}) (int, error) {
return fmt.Fscan(a.Stdin, args...)
}