lotus/cli/helper.go

93 lines
1.7 KiB
Go
Raw Normal View History

2020-07-23 18:46:22 +00:00
package cli
import (
2023-08-23 23:57:34 +00:00
"errors"
2020-07-23 18:46:22 +00:00
"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: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
2023-08-23 23:57:34 +00:00
if errors.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{}) {
2024-06-21 18:48:22 +00:00
_, _ = fmt.Fprint(a.app.Writer, args...)
}
func (a *AppFmt) Println(args ...interface{}) {
2024-06-21 18:48:22 +00:00
_, _ = fmt.Fprintln(a.app.Writer, args...)
}
func (a *AppFmt) Printf(fmtstr string, args ...interface{}) {
2024-06-21 18:48:22 +00:00
_, _ = fmt.Fprintf(a.app.Writer, fmtstr, args...)
}
func (a *AppFmt) Scan(args ...interface{}) (int, error) {
return fmt.Fscan(a.Stdin, args...)
}