mirror of
https://github.com/ahmetb/kubectx.git
synced 2025-06-23 14:08:04 +00:00
kubens: Add facility to store state file
Signed-off-by: Ahmet Alp Balkan <ahmetb@google.com>
This commit is contained in:
parent
d0c352c5bf
commit
99b593be90
42
cmd/kubens/statefile.go
Normal file
42
cmd/kubens/statefile.go
Normal 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)
|
||||
}
|
38
cmd/kubens/statefile_test.go
Normal file
38
cmd/kubens/statefile_test.go
Normal 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)
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user