From 377cc7f377c09f82dabbfda58e8f1630ea9a1a45 Mon Sep 17 00:00:00 2001 From: Matthew Rothenberg Date: Mon, 17 Jan 2022 15:46:07 -0500 Subject: [PATCH] init: auto default shell detection based on $SHELL --- commands/inits/init.go | 9 +++++++++ commands/inits/init_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 commands/inits/init_test.go diff --git a/commands/inits/init.go b/commands/inits/init.go index e8360df..5aaca0f 100644 --- a/commands/inits/init.go +++ b/commands/inits/init.go @@ -3,6 +3,7 @@ package inits import ( "fmt" "os" + "path/filepath" "strings" "github.com/spf13/cobra" @@ -97,5 +98,13 @@ There are a number of flags to customize the shell integration. // defaultShell returns the shellType assumed if user does not specify. // in the future, we may wish to customize this based on the $SHELL variable. func defaultShellType() string { + if shellenv, ok := os.LookupEnv("SHELL"); ok { + base := filepath.Base(shellenv) + switch base { + case "sh", "bash", "zsh", "fish": + return base + } + } + return "sh" } diff --git a/commands/inits/init_test.go b/commands/inits/init_test.go new file mode 100644 index 0000000..029db41 --- /dev/null +++ b/commands/inits/init_test.go @@ -0,0 +1,27 @@ +package inits + +import "testing" + +func Test_defaultShellType(t *testing.T) { + tests := []struct { + shellenv string + want string + }{ + // supported shells at a bunch of different locations + {"/bin/zsh", "zsh"}, + {"/usr/bin/zsh", "zsh"}, + {"/usr/local/bin/zsh", "zsh"}, + {"/bin/bash", "bash"}, + {"/usr/local/bin/fish", "fish"}, + + // edge cases + {"", "sh"}, + {"/bin/unsupported", "sh"}, + } + for _, tt := range tests { + t.Setenv("SHELL", tt.shellenv) + if got := defaultShellType(); got != tt.want { + t.Errorf("defaultShellType(%v) = %v, want %v", tt.shellenv, got, tt.want) + } + } +}