github.com/tcnksm/gcli@v0.2.4-0.20170129033839-7eb950507e5a/command/meta.go (about)

     1  package command
     2  
     3  import (
     4  	"bufio"
     5  	"flag"
     6  	"io"
     7  
     8  	"github.com/mitchellh/cli"
     9  	"github.com/mitchellh/go-homedir"
    10  )
    11  
    12  // ExitCodes
    13  const (
    14  	ExitCodeOK     int = 0
    15  	ExitCodeFailed int = 1
    16  )
    17  
    18  const (
    19  	// EnvGoPath is env name of GOPATH
    20  	EnvGoPath = "GOPATH"
    21  )
    22  
    23  const (
    24  	// DefaultVCSHost is the default VCS host name.
    25  	DefaultVCSHost = "github.com"
    26  
    27  	// DefaultLocalDir is the default path to store directory.
    28  	DefaultLocalDir = "~/.gcli.d"
    29  
    30  	// DefaultLocalStaticDir is the default path for static file.
    31  	DefaultLocalStaticDir = "static"
    32  
    33  	// defaultFrameworkString is default cli framework name
    34  	defaultFrameworkString = "codegangsta_cli"
    35  )
    36  
    37  // Meta contain the meta-option that nealy all subcommand inherited.
    38  type Meta struct {
    39  	UI cli.Ui
    40  }
    41  
    42  // LocalDir returns the local directory for storing user defined data.
    43  func (m *Meta) LocalDir() (string, error) {
    44  	return homedir.Expand(DefaultLocalDir)
    45  }
    46  
    47  // NewFlagSet generates commom flag.FlagSet
    48  func (m *Meta) NewFlagSet(name string, helpText string) *flag.FlagSet {
    49  	flags := flag.NewFlagSet(name, flag.ContinueOnError)
    50  
    51  	// Set usage function
    52  	flags.Usage = func() { m.UI.Error(helpText) }
    53  
    54  	// Set error output to Meta.UI.Error
    55  	errR, errW := io.Pipe()
    56  	errScanner := bufio.NewScanner(errR)
    57  	flags.SetOutput(errW)
    58  
    59  	go func() {
    60  		for errScanner.Scan() {
    61  			m.UI.Error(errScanner.Text())
    62  		}
    63  	}()
    64  
    65  	return flags
    66  }