Skip to content

Commit

Permalink
Small updates
Browse files Browse the repository at this point in the history
  • Loading branch information
cristaloleg committed Oct 27, 2021
1 parent 9de0de6 commit 0db01dc
Showing 1 changed file with 20 additions and 18 deletions.
38 changes: 20 additions & 18 deletions acmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ type Config struct {
// Args passed to the executable, if nil os.Args[1:] will be used.
Args []string

// Usage of the application, if nil flag.Usage will be used,
Usage func()
// Usage of the application, if nil default will be used,
Usage func(name string, cmds []Command)
}

// RunnerOf creates a Runner.
Expand All @@ -60,29 +60,31 @@ func RunnerOf(cmds []Command, cfg Config) *Runner {
}

func (r *Runner) init() error {
args := r.cfg.Args
if len(args) == 0 {
args = os.Args[1:]
r.args = r.cfg.Args
if len(r.args) == 0 {
r.args = os.Args[1:]
}
if len(r.cfg.Args) == 0 {
return errors.New("acmd: no args provided")
if len(r.args) == 0 {
return errors.New("no args provided")
}

ctx := r.cfg.Context
if ctx == nil {
var cancel context.CancelFunc
r.cfg.Context, cancel = signal.NotifyContext(context.Background(), os.Interrupt)
// TODO: fix
defer cancel()
r.ctx = r.cfg.Context
if r.ctx == nil {
// ok to ignore cancel func because os.Interrupt is already almost os.Exit
r.ctx, _ = signal.NotifyContext(context.Background(), os.Interrupt)
}

names := make(map[string]struct{})
for _, cmd := range r.cmds {
if cmd.Name == "help" || cmd.Name == "version" {
return fmt.Errorf("acmd: command name %q is reserved", cmd.Name)
switch {
case cmd.Do == nil:
return fmt.Errorf("command %q function cannot be nil", cmd.Name)
case cmd.Name == "help" || cmd.Name == "version":
return fmt.Errorf("command %q is reserved", cmd.Name)
}

if _, ok := names[cmd.Name]; ok {
return fmt.Errorf("acmd: duplicate command %q", cmd.Name)
return fmt.Errorf("duplicate command %q", cmd.Name)
}
names[cmd.Name] = struct{}{}
}
Expand All @@ -108,7 +110,7 @@ func (r *Runner) run() error {
cmd, params := r.args[0], r.args[1:]
switch {
case cmd == "help":
r.cfg.Usage()
r.cfg.Usage(r.cfg.AppName, r.cmds)
return nil
case cmd == "version":
fmt.Printf("%s version: %s\n", r.cfg.AppName, r.cfg.Version)
Expand All @@ -120,5 +122,5 @@ func (r *Runner) run() error {
return c.Do(r.ctx, params)
}
}
return fmt.Errorf("acmd: no such command %q", cmd)
return fmt.Errorf("no such command %q", cmd)
}

0 comments on commit 0db01dc

Please sign in to comment.