Skip to content

Commit

Permalink
Configure client using a command
Browse files Browse the repository at this point in the history
Closes #31
  • Loading branch information
akshat committed Nov 21, 2018
1 parent 3dd1e03 commit 164c57a
Show file tree
Hide file tree
Showing 12 changed files with 405 additions and 206 deletions.
96 changes: 96 additions & 0 deletions cmd/config/config_manager.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package config

import (
"bufio"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"

"github.com/fatih/color"
proctor_config "github.com/gojektech/proctor/config"
"github.com/gojektech/proctor/io"
"github.com/spf13/cobra"
)

func CreateDirIfNotExist(dir string) {
if _, err := os.Stat(dir); os.IsNotExist(err) {
err = os.MkdirAll(dir, 0755)
if err != nil {
panic(err)
}
}
}

func NewCmd(printer io.Printer) *cobra.Command {
return &cobra.Command{
Use: "config",
Short: "Configure proctor client",
Long: "This command helps configure client with proctord host, email id and access token",
Example: fmt.Sprintf("proctor config set %s=example.proctor.com %s=example@proctor.com %s=XXXXX", proctor_config.ProctorHost, proctor_config.EmailId, proctor_config.AccessToken),
Args: cobra.MinimumNArgs(1),

Run: func(cmd *cobra.Command, args []string) {
configFile := filepath.Join(proctor_config.ConfigFileDir(), "proctor.yaml")
if _, err := os.Stat(configFile); err == nil {
printer.Println("[Warning] This will overwrite current config:", color.FgYellow)
existingProctorConfig, err := ioutil.ReadFile(configFile)
if err != nil {
printer.Println(fmt.Sprintf("Error reading config file: %s", configFile), color.FgRed)
return
}

printer.Println(string(existingProctorConfig))
printer.Println("\nDo you want to continue (Y/n)?\t", color.FgYellow)

in := bufio.NewReader(os.Stdin)
userPermission, err := in.ReadString('\n')

if err != nil {
printer.Println("Error getting user permission for overwriting config", color.FgRed)
return
}

if userPermission != "y\n" && userPermission != "Y\n" {
printer.Println("Skipping configuring proctor client", color.FgYellow)
return
}
}

CreateDirIfNotExist(proctor_config.ConfigFileDir())
var proctorHost, emailID, accessToken string
for _, v := range args {
arg := strings.Split(v, "=")

if len(arg) != 2 {
printer.Println(fmt.Sprintf("%-40s %-100s", "\nIncorrect config format: %s. Correct format: CONFIG_KEY=VALUE\n", v), color.FgRed)
return
}

switch arg[0] {
case proctor_config.ProctorHost:
proctorHost = arg[1]
case "EMAIL_ID":
emailID = arg[1]
case "ACCESS_TOKEN":
accessToken = arg[1]
default:
printer.Println(fmt.Sprintf("Proctor doesn't support config key: %s", arg[0]), color.FgYellow)
}
}

configFileContent := []byte(fmt.Sprintf("%s: "+proctorHost+"\n"+"%s: "+emailID+"\n"+"%s: "+accessToken, proctor_config.ProctorHost, proctor_config.EmailId, proctor_config.AccessToken))
f, err := os.Create(configFile)
if err != nil {
printer.Println(fmt.Sprintf("Error creating config file %s: %s", configFile, err.Error()), color.FgRed)
}
_, err = f.Write(configFileContent)
if err != nil {
printer.Println(fmt.Sprintf("Error writing content %v \n to config file %s: %s", configFileContent, configFile, err.Error()), color.FgRed)
}
defer f.Close()
printer.Println("Proctor client configured successfully", color.FgGreen)
},
}
}
48 changes: 48 additions & 0 deletions cmd/config/view/view.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package view

import (
"fmt"
"io/ioutil"
"os"
"path/filepath"

"github.com/fatih/color"
proctor_config "github.com/gojektech/proctor/config"
"github.com/gojektech/proctor/io"
"github.com/spf13/cobra"
)

func CreateDirIfNotExist(dir string) {
if _, err := os.Stat(dir); os.IsNotExist(err) {
err = os.MkdirAll(dir, 0755)
if err != nil {
panic(err)
}
}
}

func NewCmd(printer io.Printer) *cobra.Command {
return &cobra.Command{
Use: "show",
Short: "Show proctor client config",
Long: "This command helps view proctor client config",
Example: fmt.Sprintf("proctor config show"),

Run: func(cmd *cobra.Command, args []string) {
configFile := filepath.Join(proctor_config.ConfigFileDir(), "proctor.yaml")
if _, err := os.Stat(configFile); os.IsNotExist(err) {
printer.Println(fmt.Sprintf("Client Config is absent: %s", configFile), color.FgRed)
printer.Println(fmt.Sprintf("Setup config using `proctor config PROCTOR_HOST=some.host ...`"), color.FgRed)
return
}

existingProctorConfig, err := ioutil.ReadFile(configFile)
if err != nil {
printer.Println(fmt.Sprintf("Error reading config file: %s", configFile), color.FgRed)
return
}

printer.Println(string(existingProctorConfig))
},
}
}
6 changes: 1 addition & 5 deletions cmd/execution/executioner.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,9 @@ func NewCmd(printer io.Printer, proctorEngineClient daemon.Client) *cobra.Comman
Short: "Execute a proc with arguments given",
Long: "To execute a proc, this command helps communicate with `proctord` and streams to logs of proc in execution",
Example: "proctor execute proc-one SOME_VAR=foo ANOTHER_VAR=bar\nproctor execute proc-two ANY_VAR=baz",
Args: cobra.MinimumNArgs(1),

Run: func(cmd *cobra.Command, args []string) {
if len(args) < 1 {
printer.Println("Incorrect command. See `proctor execute --help` for usage", color.FgRed)
return
}

procName := args[0]
printer.Println(fmt.Sprintf("%-40s %-100s", "Executing Proc", procName), color.Reset)

Expand Down
8 changes: 0 additions & 8 deletions cmd/execution/executioner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,14 +60,6 @@ func (s *ExecutionCmdTestSuite) TestExecutionCmd() {
s.mockPrinter.AssertExpectations(s.T())
}

func (s *ExecutionCmdTestSuite) TestExecutionCmdForIncorrectUsage() {
s.mockPrinter.On("Println", "Incorrect command. See `proctor execute --help` for usage", color.FgRed).Once()

s.testExecutionCmd.Run(&cobra.Command{}, []string{})

s.mockPrinter.AssertExpectations(s.T())
}

func (s *ExecutionCmdTestSuite) TestExecutionCmdForNoProcVariables() {
args := []string{"say-hello-world"}

Expand Down
7 changes: 7 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"fmt"
"os"

"github.com/gojektech/proctor/cmd/config"
"github.com/gojektech/proctor/cmd/config/view"
"github.com/gojektech/proctor/cmd/description"
"github.com/gojektech/proctor/cmd/execution"
"github.com/gojektech/proctor/cmd/list"
Expand Down Expand Up @@ -39,6 +41,11 @@ func Execute(printer io.Printer, proctorEngineClient daemon.Client) {
listCmd := list.NewCmd(printer, proctorEngineClient)
rootCmd.AddCommand(listCmd)

configCmd := config.NewCmd(printer)
configShowCmd := view.NewCmd(printer)
rootCmd.AddCommand(configCmd)
configCmd.AddCommand(configShowCmd)

if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
Expand Down
1 change: 1 addition & 0 deletions cmd/root_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ func TestRootCmdSubCommands(t *testing.T) {
assert.True(t, contains(rootCmd.Commands(), "execute"))
assert.True(t, contains(rootCmd.Commands(), "help"))
assert.True(t, contains(rootCmd.Commands(), "list"))
assert.True(t, contains(rootCmd.Commands(), "config"))
assert.True(t, contains(rootCmd.Commands(), "proc"))
assert.True(t, contains(rootCmd.Commands(), "version"))
}
20 changes: 16 additions & 4 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ package config

import (
"fmt"
"github.com/gojektech/proctor/proctord/utility"
"github.com/pkg/errors"
"os"
"time"

"github.com/gojektech/proctor/proctord/utility"
"github.com/pkg/errors"

"github.com/spf13/viper"
)

Expand Down Expand Up @@ -34,7 +35,17 @@ func (c *ConfigError) RootError() error {
return c.error
}

func LoadConfig() (ProctorConfig, ConfigError) {
type Loader interface {
Load() (ProctorConfig, ConfigError)
}

type loader struct{}

func NewLoader() Loader {
return &loader{}
}

func (loader *loader) Load() (ProctorConfig, ConfigError) {
viper.SetDefault(ConnectionTimeoutSecs, 10)
viper.AutomaticEnv()

Expand All @@ -51,7 +62,8 @@ func LoadConfig() (ProctorConfig, ConfigError) {
bytes, _ := dataConfig_templateYamlBytes()
template := string(bytes)
message = fmt.Sprintf("Config file not found in %s/proctor.yaml\n", ConfigFileDir())
message += fmt.Sprintf("Create a config file with template:\n\n%s\n", template)
message += fmt.Sprintf("Setup config using `proctor config PROCTOR_HOST=some.host ...`\n\n")
message += fmt.Sprintf("Alternatively create a config file with template:\n\n%s\n", template)
}
return ProctorConfig{}, ConfigError{error: err, Message: message}
}
Expand Down
12 changes: 12 additions & 0 deletions config/config_mock.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package config

import "github.com/stretchr/testify/mock"

type MockLoader struct {
mock.Mock
}

func (m *MockLoader) Load() (ProctorConfig, ConfigError) {
args := m.Called()
return args.Get(0).(ProctorConfig), args.Get(1).(ConfigError)
}
Loading

0 comments on commit 164c57a

Please sign in to comment.