github.com/wallyqs/gcli@v0.2.3-0.20151010121825-a114d5d1758d/command/meta.go (about)

     1  package command
     2  
     3  import (
     4  	"bufio"
     5  	"flag"
     6  	"io"
     7  
     8  	"github.com/mitchellh/cli"
     9  )
    10  
    11  // ExitCodes
    12  const (
    13  	ExitCodeOK     int = 0
    14  	ExitCodeFailed int = 1
    15  )
    16  
    17  const (
    18  	// defaultFrameworkString is default cli framework name
    19  	defaultFrameworkString = "codegangsta_cli"
    20  )
    21  
    22  // Meta contain the meta-option that nealy all subcommand inherited.
    23  type Meta struct {
    24  	UI cli.Ui
    25  }
    26  
    27  // NewFlagSet generates commom flag.FlagSet
    28  func (m *Meta) NewFlagSet(name string, helpText string) *flag.FlagSet {
    29  	flags := flag.NewFlagSet(name, flag.ContinueOnError)
    30  
    31  	// Set usage function
    32  	flags.Usage = func() { m.UI.Error(helpText) }
    33  
    34  	// Set error output to Meta.UI.Error
    35  	errR, errW := io.Pipe()
    36  	errScanner := bufio.NewScanner(errR)
    37  	flags.SetOutput(errW)
    38  
    39  	go func() {
    40  		for errScanner.Scan() {
    41  			m.UI.Error(errScanner.Text())
    42  		}
    43  	}()
    44  
    45  	return flags
    46  }