git-ea/cmd/cd.go

60 lines
1.2 KiB
Go

package cmd
import (
"context"
"flag"
"fmt"
"os"
"os/exec"
"runtime"
"go.jolheiser.com/git-ea/config"
"github.com/peterbourgon/ff/v3/ffcli"
)
func (h *Handler) CD() *ffcli.Command {
fs := flag.NewFlagSet("cd", flag.ContinueOnError)
printFlag := fs.Bool("print", false, "Print workspace dir instead of spawning a shell")
fs.BoolVar(printFlag, "p", *printFlag, "--print")
return &ffcli.Command{
Name: "cd",
FlagSet: fs,
ShortUsage: "cd [workspace=base]",
ShortHelp: "Open a shell in the specified `workspace`",
Exec: func(ctx context.Context, _ []string) error {
dir := h.Config.Workspace()
if fs.NArg() > 0 {
dir = h.Config.WorkspaceBranch(fs.Arg(0))
}
if *printFlag {
fmt.Println(dir)
return nil
}
command, args := cd(h.Config)
cmd := exec.CommandContext(ctx, command, args...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Dir = dir
return cmd.Run()
},
}
}
func cd(cfg *config.Config) (string, []string) {
if cfg.CD.Command != "" {
return cfg.CD.Command, cfg.CD.Args
}
var shell string
switch runtime.GOOS {
case "windows":
shell = "powershell.exe"
case "linux":
shell = "/bin/bash"
}
return shell, nil
}