github.com/jduhamel/gcli@v0.2.4-0.20151019142748-0d5307cd7e21/cli.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  
     7  	"github.com/mitchellh/cli"
     8  	"github.com/tcnksm/gcli/command"
     9  )
    10  
    11  // Run execute RunCustom() with color and output to Stdout/Stderr.
    12  // It returns exit code.
    13  func Run(args []string) int {
    14  
    15  	// Meta-option for executables.
    16  	// It defines output color and its stdout/stderr stream.
    17  	meta := &command.Meta{
    18  		UI: &cli.ColoredUi{
    19  			InfoColor:  cli.UiColorBlue,
    20  			ErrorColor: cli.UiColorRed,
    21  			Ui: &cli.BasicUi{
    22  				Writer:      os.Stdout,
    23  				ErrorWriter: os.Stderr,
    24  				Reader:      os.Stdin,
    25  			},
    26  		}}
    27  
    28  	return RunCustom(args, Commands(meta))
    29  }
    30  
    31  // RunCustom execute mitchellh/cli and return its exit code.
    32  func RunCustom(args []string, commands map[string]cli.CommandFactory) int {
    33  
    34  	for _, arg := range args {
    35  
    36  		// If the following options are provided,
    37  		// then execute gcli version command
    38  		if arg == "-v" || arg == "-version" || arg == "--version" {
    39  			newArgs := make([]string, len(args)+1)
    40  			newArgs[0] = "version"
    41  			copy(newArgs[1:], args)
    42  			args = newArgs
    43  			break
    44  		}
    45  
    46  		// Generating godoc (doc.go). This is only for gcli developper.
    47  		if arg == "-godoc" {
    48  			return runGodoc(commands)
    49  
    50  		}
    51  	}
    52  
    53  	cli := &cli.CLI{
    54  		Args:       args[1:],
    55  		Commands:   commands,
    56  		Version:    Version,
    57  		HelpFunc:   cli.BasicHelpFunc(Name),
    58  		HelpWriter: os.Stdout,
    59  	}
    60  
    61  	exitCode, err := cli.Run()
    62  	if err != nil {
    63  		fmt.Fprintf(os.Stderr, "Failed to execute: %s\n", err.Error())
    64  	}
    65  
    66  	return exitCode
    67  }