123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- package cmd
- import (
- "bytes"
- "errors"
- "fmt"
- "io"
- "os"
- "os/exec"
- "strings"
- )
- type App struct {
- Args []string
- Stdin io.Reader
- Stderr io.Writer
- Stdout io.Writer
- Directory string
- }
- func NewApp() *App {
- return &App{
- Args: os.Args[1:],
- Stdin: os.Stdin,
- Stderr: os.Stderr,
- Stdout: os.Stdout,
- Directory: getWorkingDirectory(),
- }
- }
- func (a *App) Run() error {
- if len(a.Args) < 1 {
- a.Args = append(a.Args, "help")
- }
- executed := false
- for _, s := range getVersionControlSystems() {
-
- err := isVersionControlled(s, a.Directory)
- if err != nil {
- continue
- }
-
- err = a.executeSubcommand(s, a.Args[0], a.Args[1:]...)
- executed = true
- }
-
- if !executed {
- return errors.New("No repository found")
- }
- return nil
- }
- func getWorkingDirectory() string {
- d, _ := os.Getwd()
- return d
- }
- func getVersionControlSystems() []string {
- return strings.Split(os.Getenv("CODE_VCS"), ";")
- }
- func isVersionControlled(vcs, directory string) error {
- env := os.Getenv(fmt.Sprintf("CODE_%s_CHECK", strings.ToUpper(vcs)))
- if env == "" {
- return errors.New(fmt.Sprintf("CODE_%s_CHECK is not set", strings.ToUpper(vcs)))
- }
-
- var out bytes.Buffer
- actions := strings.Split(env, " ")
- cmd := exec.Command(vcs, actions...)
- cmd.Stdout = &out
- return cmd.Run()
- }
- func (a *App) executeSubcommand(vcs, subcommand string, args ...string) error {
- command := []string{}
- env := os.Getenv(fmt.Sprintf("CODE_%s_%s", strings.ToUpper(vcs), strings.ToUpper(subcommand)))
-
-
- if env == "" {
- command = append(command, subcommand)
- command = append(command, args...)
- } else {
- actions := strings.Split(env, " ")
- command = append(command, actions...)
- command = append(command, args...)
- }
-
- cmd := exec.Command(vcs, command...)
- cmd.Stdout = a.Stdout
- cmd.Stderr = a.Stderr
- cmd.Stdin = a.Stdin
- return cmd.Run()
- }
|