Пример #1
0
func main() {
	so := cmdr.NewOutput(os.Stdout)
	se := cmdr.NewOutput(os.Stderr)

	c := cmdr.CLI{
		Root:        &root,
		Out:         so,
		Err:         se,
		HelpCommand: os.Args[0] + " help",
	}

	cmds["help"] = &helpCommand{
		CLI: &c,
	}
	cmds["other"] = &otherCommand{}
	cmds["complicated"] = &complicatedCommand{}
	c.Invoke(os.Args)
}
Пример #2
0
// NewSousCLI creates a new Sous cli app.
func NewSousCLI(s *Sous, in io.Reader, out, errout io.Writer) (*CLI, error) {

	stdout := cmdr.NewOutput(out)
	stderr := cmdr.NewOutput(errout)

	cli := &CLI{
		CLI: &cmdr.CLI{
			Root: s,
			Out:  stdout,
			Err:  stderr,
			// HelpCommand is shown to the user if they type something that looks
			// like they want help, but which isn't recognised by Sous properly. It
			// uses the standard flag.ErrHelp value to decide whether or not to show
			// this.
			HelpCommand: os.Args[0] + " help",
		},
	}

	var g *graph.SousGraph
	var chain []cmdr.Command

	cli.Hooks.Startup = func(*cmdr.CLI) error {
		g = BuildCLIGraph(cli, s, in, out, errout)
		chain = make([]cmdr.Command, 0)
		return nil
	}

	cli.Hooks.Parsed = func(cmd cmdr.Command) error {
		chain = append(chain, cmd)
		return nil
	}

	// Before Execute is called on any command, inject it with values from the
	// graph.
	cli.Hooks.PreExecute = func(cmd cmdr.Command) error {
		// Create the CLI dependency graph.

		for _, c := range chain {
			if r, ok := c.(Registrant); ok {
				r.RegisterOn(g)
			}
		}

		for _, c := range chain {
			if err := g.Inject(c); err != nil {
				return err
			}
		}
		return nil
	}

	cli.Hooks.PreFail = func(err error) cmdr.ErrorResult {
		if err != nil {
			originalErr := fmt.Sprint(err)
			err = errors.Cause(err)
			causeStr := err.Error()
			if originalErr != causeStr {
				sous.Log.Debug.Println(originalErr)
			}
		}
		return EnsureErrorResult(err)
	}

	return cli, nil
}