- x and c share these exit statuses: 1 failure, 2 usage, 3 bad input, 4 missing dependency. - Error carries a status; usage errors add a hint to use --help. - Problems reports every validation error before exiting with the status of the first, so users can fix everything in one go. - Main turns SIGINT, SIGTERM and SIGHUP into context cancellation. Commands can then stop their backend and clean up; the process exits with 128 + the signal number, and a second signal kills at once.
121 lines
3.3 KiB
Go
121 lines
3.3 KiB
Go
// Package cli holds what x and c share at the command-line level: exit
|
|
// statuses, GNU-style option parsing, diagnostics and the main wrapper.
|
|
package cli
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"os/signal"
|
|
"sync/atomic"
|
|
"syscall"
|
|
)
|
|
|
|
// Version is reported by --version. Override with
|
|
// -ldflags "-X src.panahifar.ir/ahp/archive-utils/internal/cli.Version=...".
|
|
var Version = "1.0.0"
|
|
|
|
// Exit statuses shared by x and c.
|
|
const (
|
|
ExitFailure = 1 // an operation failed, or the target already exists
|
|
ExitUsage = 2 // invalid command line
|
|
ExitInput = 3 // missing, unreadable or unsupported input; invalid destination
|
|
ExitDependency = 4 // a required external program is not installed
|
|
)
|
|
|
|
// Error is an error that carries an exit status. An empty Msg means the
|
|
// problem has already been reported to the user.
|
|
type Error struct {
|
|
Code int
|
|
Msg string
|
|
}
|
|
|
|
func (e *Error) Error() string { return e.Msg }
|
|
|
|
// Errorf returns an *Error with exit status code.
|
|
func Errorf(code int, format string, a ...any) *Error {
|
|
return &Error{Code: code, Msg: fmt.Sprintf(format, a...)}
|
|
}
|
|
|
|
// UsageErrorf returns a command-line error; Main adds a hint to use --help.
|
|
func UsageErrorf(format string, a ...any) *Error {
|
|
return Errorf(ExitUsage, format, a...)
|
|
}
|
|
|
|
// Problems collects validation errors so that all of them are reported at
|
|
// once. The resulting exit status is the one of the first problem.
|
|
type Problems struct {
|
|
log *Logger
|
|
code int
|
|
}
|
|
|
|
// NewProblems returns an empty collection that reports through log.
|
|
func NewProblems(log *Logger) *Problems { return &Problems{log: log} }
|
|
|
|
// Add reports a problem with exit status code.
|
|
func (p *Problems) Add(code int, format string, a ...any) {
|
|
p.log.Error(format, a...)
|
|
if p.code == 0 {
|
|
p.code = code
|
|
}
|
|
}
|
|
|
|
// Err returns nil if no problem was added.
|
|
func (p *Problems) Err() error {
|
|
if p.code == 0 {
|
|
return nil
|
|
}
|
|
return &Error{Code: p.code}
|
|
}
|
|
|
|
// RunFunc is the body of a command. Output for the user goes to stdout
|
|
// (help and version only) and log (everything else).
|
|
type RunFunc func(ctx context.Context, stdout io.Writer, log *Logger, args []string) error
|
|
|
|
// Main runs a command and exits with its status. SIGINT, SIGTERM and SIGHUP
|
|
// cancel the context so that the command can stop its backend and clean up;
|
|
// the process then exits with 128 + the signal number. A second signal has
|
|
// its default effect.
|
|
func Main(prog string, run RunFunc) {
|
|
log := NewLogger(prog, os.Stderr)
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
var caught atomic.Int32
|
|
signals := make(chan os.Signal, 1)
|
|
signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
|
|
go func() {
|
|
s := <-signals
|
|
signal.Stop(signals)
|
|
caught.Store(int32(s.(syscall.Signal)))
|
|
cancel()
|
|
}()
|
|
|
|
err := run(ctx, os.Stdout, log, os.Args[1:])
|
|
if n := caught.Load(); n != 0 {
|
|
os.Exit(128 + int(n))
|
|
}
|
|
os.Exit(ExitStatus(prog, log, err))
|
|
}
|
|
|
|
// ExitStatus reports err (unless it was already reported) and returns the
|
|
// exit status for it.
|
|
func ExitStatus(prog string, log *Logger, err error) int {
|
|
if err == nil {
|
|
return 0
|
|
}
|
|
var e *Error
|
|
if !errors.As(err, &e) {
|
|
log.Error("%v", err)
|
|
return ExitFailure
|
|
}
|
|
if e.Msg != "" {
|
|
log.Error("%s", e.Msg)
|
|
}
|
|
if e.Code == ExitUsage {
|
|
log.Plain("Try '%s --help' for more information.", prog)
|
|
}
|
|
return e.Code
|
|
}
|