From 0141ee19d215c5e29794b8b707c399293b6c2fe4 Mon Sep 17 00:00:00 2001 From: Ahmet Alp Balkan Date: Sun, 31 May 2020 14:24:01 -0700 Subject: [PATCH] handle ctxs with ':' in the name for windows (#235) For windows, if the ctx name for kubens state file contains a colon ':' (EKS), we replace it with __ (both while reading/writing). It doesn't break existing users (as it didn't work in the first place). Other characters remain unhandled, hoping it won't happen again. Signed-off-by: Ahmet Alp Balkan --- cmd/kubens/statefile.go | 19 ++++++++++++++++++- cmd/kubens/statefile_test.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/cmd/kubens/statefile.go b/cmd/kubens/statefile.go index 61bcbc5..bd79dc7 100644 --- a/cmd/kubens/statefile.go +++ b/cmd/kubens/statefile.go @@ -5,6 +5,8 @@ import ( "io/ioutil" "os" "path/filepath" + "runtime" + "strings" "github.com/ahmetb/kubectx/internal/cmdutil" ) @@ -18,7 +20,14 @@ type NSFile struct { func NewNSFile(ctx string) NSFile { return NSFile{dir: defaultDir, ctx: ctx} } -func (f NSFile) path() string { return filepath.Join(f.dir, f.ctx) } +func (f NSFile) path() string { + fn := f.ctx + if isWindows() { + // bug 230: eks clusters contain ':' in ctx name, not a valid file name for win32 + fn = strings.ReplaceAll(fn, ":", "__") + } + return filepath.Join(f.dir, fn) +} // Load reads the previous namespace setting, or returns empty if not exists. func (f NSFile) Load() (string, error) { @@ -40,3 +49,11 @@ func (f NSFile) Save(value string) error { } return ioutil.WriteFile(f.path(), []byte(value), 0644) } + +// isWindows determines if the process is running on windows OS. +func isWindows() bool { + if os.Getenv("_FORCE_GOOS") == "windows" { // for testing + return true + } + return runtime.GOOS == "windows" +} diff --git a/cmd/kubens/statefile_test.go b/cmd/kubens/statefile_test.go index f6575b8..bad7ba2 100644 --- a/cmd/kubens/statefile_test.go +++ b/cmd/kubens/statefile_test.go @@ -3,7 +3,11 @@ package main import ( "io/ioutil" "os" + "runtime" + "strings" "testing" + + "github.com/ahmetb/kubectx/internal/testutil" ) func TestNSFile(t *testing.T) { @@ -36,3 +40,28 @@ func TestNSFile(t *testing.T) { t.Fatalf("Load()=%q; expected=%q", v, expected) } } + +func TestNSFile_path_windows(t *testing.T) { + defer testutil.WithEnvVar("_FORCE_GOOS", "windows")() + fp := NewNSFile("a:b:c").path() + + if expected := "a__b__c"; !strings.HasSuffix(fp, expected) { + t.Fatalf("file did not have expected ending %q: %s", expected, fp) + } +} + +func Test_isWindows(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("won't test this case on windows") + } + + got := isWindows() + if got { + t.Fatalf("isWindows() returned true for %s", runtime.GOOS) + } + + defer testutil.WithEnvVar("_FORCE_GOOS", "windows")() + if !isWindows() { + t.Fatalf("isWindows() failed to detect windows with env override.") + } +}