add auto mode for shell based on SHELL env var and support zsh

This commit is contained in:
iwilltry42 2019-05-29 09:14:36 +02:00
parent df5cc1da84
commit eb5b88052e
3 changed files with 44 additions and 9 deletions

View File

@ -354,10 +354,7 @@ func GetKubeConfig(c *cli.Context) error {
return nil return nil
} }
// Shell starts a new subshell with the KUBECONFIG pointing to the selected cluster
func Shell(c *cli.Context) error { func Shell(c *cli.Context) error {
if c.String("shell") != "bash" { return shell(c.String("name"), c.String("shell"), c.String("command"))
return fmt.Errorf("%s is not supported. Only bash is supported", c.String("shell"))
}
return bashShell(c.String("name"), c.String("command"))
} }

View File

@ -4,25 +4,63 @@ import (
"fmt" "fmt"
"os" "os"
"os/exec" "os/exec"
"path"
) )
func bashShell(cluster string, command string) error { var shells = map[string]map[string][]string{
"bash": {
"options": []string{
"--noprofile", // don't load .profile/.bash_profile
"--norc", // don't load .bashrc
},
},
"zsh": {
"options": []string{
"--no-rcs", // don't load .zshrc
},
},
}
// shell
func shell(cluster, shell, command string) error {
// check if the selected shell is supported
if shell == "auto" {
shell = path.Base(os.Getenv("SHELL"))
}
supported := false
for supportedShell := range shells {
if supportedShell == shell {
supported = true
}
}
if !supported {
return fmt.Errorf("ERROR: selected shell [%s] is not supported", shell)
}
// get kubeconfig for selected cluster
kubeConfigPath, err := getKubeConfig(cluster) kubeConfigPath, err := getKubeConfig(cluster)
if err != nil { if err != nil {
return err return err
} }
// check if we're already in a subshell
subShell := os.ExpandEnv("$__K3D_CLUSTER__") subShell := os.ExpandEnv("$__K3D_CLUSTER__")
if len(subShell) > 0 { if len(subShell) > 0 {
return fmt.Errorf("Error: Already in subshell of cluster %s", subShell) return fmt.Errorf("Error: Already in subshell of cluster %s", subShell)
} }
bashPath, err := exec.LookPath("bash") // get path of shell executable
shellPath, err := exec.LookPath(shell)
if err != nil { if err != nil {
return err return err
} }
cmd := exec.Command(bashPath, "--noprofile", "--norc") // set shell specific options (command line flags)
shellOptions := shells[shell]["options"]
cmd := exec.Command(shellPath, shellOptions...)
if len(command) > 0 { if len(command) > 0 {
cmd.Args = append(cmd.Args, "-c", command) cmd.Args = append(cmd.Args, "-c", command)

View File

@ -61,7 +61,7 @@ func main() {
}, },
cli.StringFlag{ cli.StringFlag{
Name: "shell, s", Name: "shell, s",
Value: "bash", Value: "auto",
Usage: "Sub shell type. Only bash is supported. (default bash)", Usage: "Sub shell type. Only bash is supported. (default bash)",
}, },
}, },