kubens: Add facility to store state file

Signed-off-by: Ahmet Alp Balkan <ahmetb@google.com>
This commit is contained in:
Ahmet Alp Balkan 2020-04-18 14:26:38 -07:00
parent d0c352c5bf
commit 99b593be90
No known key found for this signature in database
GPG Key ID: 441833503E604E2C
2 changed files with 80 additions and 0 deletions

42
cmd/kubens/statefile.go Normal file
View File

@ -0,0 +1,42 @@
package main
import (
"bytes"
"io/ioutil"
"os"
"path/filepath"
"github.com/ahmetb/kubectx/internal/cmdutil"
)
var defaultDir = filepath.Join(cmdutil.HomeDir(), "kubens")
type NSFile struct {
dir string
ctx string
}
func NewNSFile(ctx string) NSFile { return NSFile{dir: defaultDir, ctx: ctx} }
func (f NSFile) path() string { return filepath.Join(f.dir, f.ctx) }
// Load reads the previous namespace setting, or returns empty if not exists.
func (f NSFile) Load() (string, error) {
b, err := ioutil.ReadFile(f.path())
if err != nil {
if os.IsNotExist(err) {
return "", nil
}
return "", err
}
return string(bytes.TrimSpace(b)), nil
}
// Save stores the previous namespace information in the file.
func (f NSFile) Save(value string) error {
d := filepath.Dir(f.path())
if err := os.MkdirAll(d, 0755); err != nil {
return err
}
return ioutil.WriteFile(f.path(), []byte(value), 0644)
}

View File

@ -0,0 +1,38 @@
package main
import (
"io/ioutil"
"os"
"testing"
)
func TestNSFile(t *testing.T) {
td, err := ioutil.TempDir(os.TempDir(), "")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(td)
f := NewNSFile("foo")
f.dir = td
v, err := f.Load()
if err != nil {
t.Fatal(err)
}
if v != "" {
t.Fatalf("Load() expected empty; got=%v", err)
}
err = f.Save("bar")
if err != nil {
t.Fatalf("Save() err=%v", err)
}
v, err = f.Load()
if err != nil {
t.Fatal(err)
}
if expected := "bar"; v != expected {
t.Fatalf("Load()=%q; expected=%q", v, expected)
}
}