Skip to content

Commit

Permalink
Merge pull request #12 from spideyz0r/configuration
Browse files Browse the repository at this point in the history
Use viper to set default configuration
  • Loading branch information
spideyz0r authored Jul 21, 2023
2 parents 1200ce2 + 0bc072d commit a252024
Show file tree
Hide file tree
Showing 8 changed files with 635 additions and 29 deletions.
35 changes: 33 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,40 @@ set => switch, s
```
Some examples:
```kubesw get ns
kubesw set ctx "somecontext"
kubesw ls ns
kubesw get ns
kubesw switch ns "somenamespace"
kubesw set ctx "somecontext"
kubesw s ctx "somecontext"
```

## Configuration file
The configuration file is optional. You can see the default values below.

It should be installed in ~/.kubesw/config.yaml
```
---
# Use a custom PS1 when using kubesw
# Default: unset
PS1: '[\u@\h \W {$(kubesw get ctx) @ $(kubesw get ns)}]\\$ '
# Set default shell
# Default: auto
shell: /bin/bash
# Configure rc files to be read
# Note: they are read from your home directory
# The default values are listed below
default_rc:
bash:
- .bashrc
- .bash_profile
- .profile
- .bash_login
- .bash_logout
zsh:
- .zshrc
- .zprofile
- .zlogin
- .zlogout
```

## Autocompletion
Expand All @@ -99,7 +130,7 @@ For zshell, pick a path under $fpath and put the contents of `kubesw completion
kubesw completion zsh >$(echo $fpath | cut -d " " -f1)/_kubesw
```

## Fix shell history
## Shell history
In order to have the shell's history, some extra configuration needs to be appended to the rc files.
This will make each command run to be persisted to the history file right-away.

Expand Down
2 changes: 1 addition & 1 deletion cmd/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ var (
Use: "version",
Short: "Get version of kubesw",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("v0.0.10")
fmt.Println("v0.0.11")
},
}
)
Expand Down
14 changes: 14 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,33 @@ go 1.19

require (
github.com/spf13/cobra v1.7.0
github.com/spf13/viper v1.16.0
github.com/stretchr/testify v1.8.3
k8s.io/client-go v0.27.3
)

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/fsnotify/fsnotify v1.6.0 // indirect
github.com/go-logr/logr v1.2.4 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/protobuf v1.5.3 // indirect
github.com/google/gofuzz v1.2.0 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/imdario/mergo v0.3.16 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/magiconair/properties v1.8.7 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.0.8 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/spf13/afero v1.9.5 // indirect
github.com/spf13/cast v1.5.1 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/subosito/gotenv v1.4.2 // indirect
golang.org/x/net v0.12.0 // indirect
golang.org/x/oauth2 v0.10.0 // indirect
golang.org/x/sys v0.10.0 // indirect
Expand All @@ -28,7 +40,9 @@ require (
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/protobuf v1.31.0 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
k8s.io/apimachinery v0.27.3 // indirect
k8s.io/klog/v2 v2.100.1 // indirect
k8s.io/utils v0.0.0-20230711102312-30195339c3c7 // indirect
Expand Down
437 changes: 435 additions & 2 deletions go.sum

Large diffs are not rendered by default.

51 changes: 28 additions & 23 deletions pkg/common/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"regexp"
"strings"

config "github.com/spideyz0r/kubesw/pkg/config"
"k8s.io/client-go/tools/clientcmd"
)

Expand Down Expand Up @@ -125,41 +126,37 @@ func read_rc(shell string) string {
if debug {
fmt.Printf("Reading %s rc files\n", shell)
}

zdotdir := os.Getenv("ZDOTDIR")
homedir := os.Getenv("HOME")
if zdotdir == "" && shell == "zsh" {
zdotdir = homedir
if zdotdir != "" && shell == "zsh" {
homedir = zdotdir
}

rc_shell := make(map[string][]string)
rc_shell["zsh"] = []string{
zdotdir + "/.zshrc",
zdotdir + "/.zprofile",
zdotdir + "/.zlogin",
zdotdir + "/.zlogout",
}
rc_shell["bash"] = []string{
homedir + "/.bashrc",
homedir + "/.bash_profile",
homedir + "/.profile",
homedir + "/.bash_login",
homedir + "/.bash_logout",
if homedir == "" {
if debug {
fmt.Printf("Failed to find homedir, no rc files to return\n")
}
return ""
}

config := config.ReadConfiguration()

var all_rc_files string
for _, rc_file := range rc_shell[shell] {
_, err := os.Stat(rc_file)
for _, rc_file := range config.Rc_files[shell] {
rc_file_path := fmt.Sprintf("%s/%s", homedir, rc_file)
_, err := os.Stat(rc_file_path)
if os.IsNotExist(err) {
if debug {
fmt.Printf("File %s does not exist, skipping...\n", rc_file)
fmt.Printf("File %s does not exist, skipping...\n", rc_file_path)
}
continue
}

if debug {
fmt.Printf("Reading %s\n", rc_file)
fmt.Printf("Reading %s\n", rc_file_path)
}
file, err := os.Open(rc_file)
file, err := os.Open(rc_file_path)
if err != nil {
log.Fatal(err)
}
Expand All @@ -175,6 +172,10 @@ func read_rc(shell string) string {
}

func detect_shell() (string, error) {
config := config.ReadConfiguration()
if config.Shell != "auto" {
return config.Shell, nil
}
shell := os.Getenv("SHELL")
if shell == "" {
return "", fmt.Errorf("Failed to detect shell")
Expand Down Expand Up @@ -218,6 +219,7 @@ func spawn_generic_shell(kube_config, history, shell string) {
var file *os.File
var tmp_rc_path string
var err error

if shell == "bash" {
file, err = ioutil.TempFile("", "kubesw_rc")
if err != nil {
Expand All @@ -237,15 +239,13 @@ func spawn_generic_shell(kube_config, history, shell string) {
# PROMPT_COMMAND="history -a; history -n"
history -n
history -s ` + history + `
# export PS1="[\u@\h \W: $(go run main.go get context) @ $(go run main.go get namespace)]\\$ "
`
} else {
extra_rc_configuration = `
[[ -f /etc/zshenv ]] && source "/etc/zshenv"
[[ -f /etc/zsh/zshenv ]] && source "/etc/zsh/zshenv"
[[ -f "$HOME/.zshenv" ]] && source "$HOME/.zshenv"
export KUBECONFIG=` + kube_config + `:$KUBECONFIG
# export PS1="[\u@\h \W: $(go run main.go get context) @ $(go run main.go get namespace)]\\$ "
`
tmp_rc_path, err = ioutil.TempDir("", "zdir")
if err != nil {
Expand All @@ -258,8 +258,13 @@ func spawn_generic_shell(kube_config, history, shell string) {
}
defer file.Close()
}
PS1 := ""
config := config.ReadConfiguration()
if config.PS1 != "" {
PS1 = "export PS1=\"" + config.PS1 + "\""
}

rc := fmt.Sprintf("%s\n%s", current_rc, extra_rc_configuration)
rc := fmt.Sprintf("%s\n%s\n%s", current_rc, extra_rc_configuration, PS1)
if debug {
fmt.Printf("Writing to rc file: %s:\n", tmp_rc_path)
fmt.Printf("%s\n", rc)
Expand Down
54 changes: 54 additions & 0 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package config

import (
"os"

"github.com/spf13/viper"
)

type Config struct {
Shell string
PS1 string
Rc_files map[string][]string
}

func ReadConfiguration() Config {
viper.SetDefault("shell", "auto")
viper.SetDefault("PS1", "")

rc_shell := make(map[string][]string)

rc_shell["zsh"] = []string{
"/.zshrc",
"/.zprofile",
"/.zlogin",
"/.zlogout",
}
rc_shell["bash"] = []string{
"/.bashrc",
"/.bash_profile",
"/.profile",
"/.bash_login",
"/.bash_logout",
}
viper.SetDefault("default_rc", rc_shell)

homedir := os.Getenv("HOME")
viper.AddConfigPath(homedir + "/.kubesw")
viper.SetConfigName("config")
viper.SetConfigType("yaml")

if err := viper.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
// Config file not found; using defaults
} else {
panic(err)
}
}

return Config{
Shell: viper.GetString("shell"),
PS1: viper.GetString("PS1"),
Rc_files: viper.GetStringMapStringSlice("default_rc"),
}
}
66 changes: 66 additions & 0 deletions pkg/config/config_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package config

import (
"os"
"testing"

"github.com/stretchr/testify/assert"
)

func setupTestEnvironment() {
os.Setenv("HOME", "/tmp")
}

func TestReadConfiguration(t *testing.T) {
setupTestEnvironment()

config := ReadConfiguration()
expectedConfig := Config{
Shell: "auto",
PS1: "",
Rc_files: map[string][]string{
"zsh": []string{
"/.zshrc",
"/.zprofile",
"/.zlogin",
"/.zlogout",
},
"bash": []string{
"/.bashrc",
"/.bash_profile",
"/.profile",
"/.bash_login",
"/.bash_logout",
},
},
}
assert.Equal(t, expectedConfig.Shell, config.Shell)
assert.Equal(t, expectedConfig.PS1, config.PS1)
assert.Equal(t, expectedConfig.Rc_files, config.Rc_files)
}

func TestReadConfiguration_ConfigFileNotFound(t *testing.T) {
config := ReadConfiguration()
expectedConfig := Config{
Shell: "auto",
PS1: "",
Rc_files: map[string][]string{
"zsh": []string{
"/.zshrc",
"/.zprofile",
"/.zlogin",
"/.zlogout",
},
"bash": []string{
"/.bashrc",
"/.bash_profile",
"/.profile",
"/.bash_login",
"/.bash_logout",
},
},
}
assert.Equal(t, expectedConfig.Shell, config.Shell)
assert.Equal(t, expectedConfig.PS1, config.PS1)
assert.Equal(t, expectedConfig.Rc_files, config.Rc_files)
}
5 changes: 4 additions & 1 deletion rpm/kubesw.spec
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
%global go_release go1.18.10

Name: kubesw
Version: 0.0.10
Version: 0.0.11
Release: 1%{?dist}
Summary: kubesw, a tool to switch context and namespaces per terminal
License: GPLv3
Expand Down Expand Up @@ -35,6 +35,9 @@ install -Dpm 0755 %{name} %{buildroot}%{_bindir}/%{name}
%license LICENSE

%changelog
* Fri Jul 21 2023 spideyz0r <47341410+spideyz0r@users.noreply.github.com> 0.0.11-1
- Add support to configuration file

* Wed Jul 19 2023 spideyz0r <47341410+spideyz0r@users.noreply.github.com> 0.0.10-1
- Fix writing to kubeconfig bug

Expand Down

0 comments on commit a252024

Please sign in to comment.