github.com/woremacx/kocha@v0.7.1-0.20150731103243-a5889322afc9/cmd/kocha/main.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"go/build"
     6  	"os"
     7  	"os/exec"
     8  	"path/filepath"
     9  	"strings"
    10  
    11  	"github.com/woremacx/kocha/util"
    12  )
    13  
    14  const (
    15  	commandPrefix = "kocha-"
    16  )
    17  
    18  var (
    19  	aliases = map[string]string{
    20  		"g": "generate",
    21  		"b": "build",
    22  	}
    23  )
    24  
    25  type kochaCommand struct {
    26  	option struct {
    27  		Help bool `short:"h" long:"help"`
    28  	}
    29  }
    30  
    31  func (c *kochaCommand) Name() string {
    32  	return filepath.Base(os.Args[0])
    33  }
    34  
    35  func (c *kochaCommand) Usage() string {
    36  	return fmt.Sprintf(`Usage: %s [OPTIONS] COMMAND [argument...]
    37  
    38  Commands:
    39      new               create a new application
    40      generate          generate files (alias: "g")
    41      build             build your application (alias: "b")
    42      run               run the your application
    43      migrate           run the migrations
    44  
    45  Options:
    46      -h, --help        display this help and exit
    47  
    48  `, c.Name())
    49  }
    50  
    51  func (c *kochaCommand) Option() interface{} {
    52  	return &c.option
    53  }
    54  
    55  // run runs the subcommand specified by the argument.
    56  // run is the launcher of another command actually. It will find a subcommand
    57  // from $GOROOT/bin, $GOPATH/bin and $PATH, and then run it.
    58  // If subcommand is not found, run prints the usage and exit.
    59  func (c *kochaCommand) Run(args []string) error {
    60  	if len(args) < 1 || args[0] == "" {
    61  		return fmt.Errorf("no COMMAND given")
    62  	}
    63  	var paths []string
    64  	for _, dir := range build.Default.SrcDirs() {
    65  		paths = append(paths, filepath.Clean(filepath.Join(filepath.Dir(dir), "bin")))
    66  	}
    67  	paths = append(paths, filepath.SplitList(os.Getenv("PATH"))...)
    68  	if err := os.Setenv("PATH", strings.Join(paths, string(filepath.ListSeparator))); err != nil {
    69  		return err
    70  	}
    71  	name := args[0]
    72  	if n, exists := aliases[name]; exists {
    73  		name = n
    74  	}
    75  	filename, err := exec.LookPath(commandPrefix + name)
    76  	if err != nil {
    77  		return fmt.Errorf("command not found: %s", name)
    78  	}
    79  	cmd := exec.Command(filename, args[1:]...)
    80  	cmd.Stdin = os.Stdin
    81  	cmd.Stdout = os.Stdout
    82  	cmd.Stderr = os.Stderr
    83  	return cmd.Run()
    84  }
    85  
    86  func main() {
    87  	util.RunCommand(&kochaCommand{})
    88  }