Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplify CLI commands by saving rpc-addr and project to context #592

Closed
wants to merge 12 commits into from
22 changes: 17 additions & 5 deletions cmd/yorkie/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,14 @@
package main

import (
"log"
"os"
"path"

"github.com/spf13/cobra"
"github.com/spf13/viper"

"github.com/yorkie-team/yorkie/cmd/yorkie/config"
"github.com/yorkie-team/yorkie/cmd/yorkie/context"
"github.com/yorkie-team/yorkie/cmd/yorkie/document"
"github.com/yorkie-team/yorkie/cmd/yorkie/project"
)
Expand All @@ -46,8 +49,17 @@ func init() {
rootCmd.SetErr(os.Stderr)
rootCmd.AddCommand(project.SubCmd)
rootCmd.AddCommand(document.SubCmd)
// TODO(chacha912): set rpcAddr from env using viper.
// https://github.com/spf13/cobra/blob/main/user_guide.md#bind-flags-with-config
rootCmd.PersistentFlags().StringVar(&config.RPCAddr, "rpc-addr", "localhost:11101", "Address of the rpc server")
rootCmd.PersistentFlags().BoolVar(&config.IsInsecure, "insecure", false, "Skip the TLS connection of the client")
rootCmd.AddCommand(context.SubCmd)
viper.SetConfigName("config")
viper.SetConfigType("json")
viper.AddConfigPath(path.Join(os.Getenv("HOME"), ".yorkie"))

rootCmd.PersistentFlags().String("rpc-addr", "localhost:11101", "Address of the rpc server")
rootCmd.PersistentFlags().Bool("insecure", false, "Skip the TLS connection of the client")
if err := viper.BindPFlag("rpcAddr", rootCmd.PersistentFlags().Lookup("rpc-addr")); err != nil {
log.Fatalf("Failed to bind rpcAddr flag: %v", err)
}
if err := viper.BindPFlag("isInsecure", rootCmd.PersistentFlags().Lookup("insecure")); err != nil {
log.Fatalf("Failed to bind isInsecure flag: %v", err)
}
}
33 changes: 33 additions & 0 deletions cmd/yorkie/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ import (
"os"
"path"
"path/filepath"

"github.com/spf13/cobra"
"github.com/spf13/viper"
)

var (
Expand Down Expand Up @@ -54,6 +57,10 @@ func configPath() (string, error) {
type Config struct {
// Auths is the map of the address and the token.
Auths map[string]string `json:"auths"`
// RPCAddr is the address of the rpc server
RPCAddr string `json:"rpcAddr"`
// IsInsecure specifies whether to skip the TLS connection of the client
IsInsecure bool `json:"isInsecure"`
}

// New creates a new configuration.
Expand Down Expand Up @@ -137,3 +144,29 @@ func Delete() error {

return nil
}

// ReadConfig read configuration file for viper before runnning command
func ReadConfig(cmd *cobra.Command, args []string) error {
configPathValue, err := configPath()
if err != nil {
fmt.Fprintln(os.Stderr, "get config path: %w", err)
os.Exit(1)
}

file, err := os.Open(filepath.Clean(configPathValue))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What does this file do?
Is this required for viper.ReadInConfig()?

Copy link
Contributor Author

@Wu22e Wu22e Sep 11, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had some concerns about this part.
Actually, I don't use the file variable in the section you mentioned.

In the existing CLI command, the Load function of config.go is used, and the Load function checks for the existence of the config path and config.json file and creates one if it doesn't exist.

viper.ReadInConfig() primarily reads the configuration values based on the configname, configtype, and config path set in commands.go.

During this process, for users who have installed the yorkie program for the first time, the config.json does not exist in the ~/.yorkie directory. Therefore, if simply call viper.ReadInConfig(), an error occurs.

To resolve this, I utilized the logic of the Load function from config.go. Do you think there's a need to modify the logic, or would it be better to remove the duplicated logic from the Load method?

(Additionally, the statement path.Join(os.Getenv("HOME"), ".yorkie") in commands.go seems not to properly find the HOME directory in a Windows environment. Should this also be taken into consideration?)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you think there's a need to modify the logic, or would it be better to remove the duplicated logic from the Load method?

It will be better to refactor duplicate codes in Load() and ReadConfig().

Also, since ReadConfig()name is confusing with Load(), how about changing this function name to something like Preload()?

(Additionally, the statement path.Join(os.Getenv("HOME"), ".yorkie") in commands.go seems not to properly find the HOME directory in a Windows environment. Should this also be taken into consideration?)

We need to cover Windows as well. We might need to code like this: https://gist.github.com/miguelmota/f30a04a6d64bd52d7ab59ea8d95e54da

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for the feedback. I will make the changes.

if err != nil {
if os.IsNotExist(err) {
New()
return nil
}

return fmt.Errorf("open config file: %w", err)
}
defer func() {
_ = file.Close()
}()
if err := viper.ReadInConfig(); err != nil {
return fmt.Errorf("failed to read in config: %w", err)
}
return nil
}
30 changes: 30 additions & 0 deletions cmd/yorkie/context/context.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/*
* Copyright 2023 The Yorkie Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

// Package context provides the context(configuration) command.
package context

import (
"github.com/spf13/cobra"
)

var (
// SubCmd represents the document command
SubCmd = &cobra.Command{
Use: "context",
Short: "Manage contexts",
}
)
58 changes: 58 additions & 0 deletions cmd/yorkie/context/list.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/*
* Copyright 2023 The Yorkie Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package context

import (
"fmt"

"github.com/jedib0t/go-pretty/v6/table"
"github.com/spf13/cobra"
"github.com/spf13/viper"

"github.com/yorkie-team/yorkie/cmd/yorkie/config"
)

func newListCommand() *cobra.Command {
return &cobra.Command{
Use: "ls",
Short: "List all contexts from configuration",
PreRunE: config.ReadConfig,
RunE: func(cmd *cobra.Command, args []string) error {
conf, err := config.Load()
if err != nil {
return err
}

fmt.Println("Current Context:")
fmt.Printf(" rpcAddr: %s\n isInsecure: %v\n", viper.GetString("rpcAddr"), viper.GetBool("isInsecure"))

fmt.Println("All Auth Contexts:")
tw := table.NewWriter()
tw.AppendHeader(table.Row{"RpcAddr", "Token"})
for addr, auth := range conf.Auths {
tw.AppendRow(table.Row{addr, auth})
}
fmt.Println(tw.Render())

return nil
},
}
}

func init() {
SubCmd.AddCommand(newListCommand())
}
62 changes: 62 additions & 0 deletions cmd/yorkie/context/remove.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/*
* Copyright 2023 The Yorkie Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package context

import (
"fmt"

"github.com/spf13/cobra"

"github.com/yorkie-team/yorkie/cmd/yorkie/config"
)

func newRemoveCmd() *cobra.Command {
return &cobra.Command{
Use: "remove [rpcAddr]",
Short: "Remove the context for the specified rpcAddr",
Args: cobra.ExactArgs(1),
PreRunE: config.ReadConfig,
RunE: func(cmd *cobra.Command, args []string) error {
conf, err := config.Load()
if err != nil {
return err
}

rpcAddr := args[0]

// Check if auth exists for the rpcAddr
if _, ok := conf.Auths[rpcAddr]; !ok {
return fmt.Errorf("no context exists for the rpcAddr: %s", rpcAddr)
}

// Delete the context for the rpcAddr
delete(conf.Auths, rpcAddr)

err = config.Save(conf)
if err != nil {
return err
}

fmt.Printf("Context for rpcAddr: %s has been removed.\n", rpcAddr)
return nil
},
}
}

func init() {
SubCmd.AddCommand(newRemoveCmd())
}
62 changes: 62 additions & 0 deletions cmd/yorkie/context/set.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/*
* Copyright 2023 The Yorkie Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package context

import (
"fmt"

"github.com/spf13/cobra"
"github.com/spf13/viper"

"github.com/yorkie-team/yorkie/cmd/yorkie/config"
)

func newSetContextCmd() *cobra.Command {
return &cobra.Command{
Use: "set",
Short: "Set the current global flags as the context",
PreRunE: config.ReadConfig,
RunE: func(cmd *cobra.Command, args []string) error {
conf, err := config.Load()
if err != nil {
return err
}

rpcAddr := viper.GetString("rpcAddr")
conf.RPCAddr = rpcAddr
conf.IsInsecure = viper.GetBool("isInsecure")

// check if auth exists for the rpcAddr
if _, ok := conf.Auths[rpcAddr]; !ok {
conf.Auths[rpcAddr] = ""
fmt.Println("A new RPC address has been set. Please log in again.")
}

err = config.Save(conf)
if err != nil {
return err
}

fmt.Println("Context has been updated.")
return nil
},
}
}

func init() {
SubCmd.AddCommand(newSetContextCmd())
}
13 changes: 9 additions & 4 deletions cmd/yorkie/document/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (

"github.com/jedib0t/go-pretty/v6/table"
"github.com/spf13/cobra"
"github.com/spf13/viper"

"github.com/yorkie-team/yorkie/admin"
"github.com/yorkie-team/yorkie/cmd/yorkie/config"
Expand All @@ -37,19 +38,23 @@ var (

func newListCommand() *cobra.Command {
return &cobra.Command{
Use: "ls [project name]",
Short: "List all documents in the project",
Use: "ls [project name]",
Short: "List all documents in the project",
PreRunE: config.ReadConfig,
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return errors.New("project is required")
}
projectName := args[0]

token, err := config.LoadToken(config.RPCAddr)
rpcAddr := viper.GetString("rpcAddr")
token, err := config.LoadToken(rpcAddr)
if err != nil {
return err
}
cli, err := admin.Dial(config.RPCAddr, admin.WithToken(token), admin.WithInsecure(config.IsInsecure))

cli, err := admin.Dial(rpcAddr, admin.WithToken(token), admin.WithInsecure(viper.GetBool("isInsecure")))

if err != nil {
return err
}
Expand Down
7 changes: 5 additions & 2 deletions cmd/yorkie/document/remove.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"errors"

"github.com/spf13/cobra"
"github.com/spf13/viper"

"github.com/yorkie-team/yorkie/admin"
"github.com/yorkie-team/yorkie/cmd/yorkie/config"
Expand All @@ -35,18 +36,20 @@ func newRemoveCommand() *cobra.Command {
Use: "remove [project name] [document key]",
Short: "Remove documents in the project",
Example: "yorkie document remove sample-project sample-document [options]",
PreRunE: config.ReadConfig,
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) != 2 {
return errors.New("project name and document key are required")
}
projectName := args[0]
documentKey := args[1]

token, err := config.LoadToken(config.RPCAddr)
rpcAddr := viper.GetString("rpcAddr")
token, err := config.LoadToken(rpcAddr)
if err != nil {
return err
}
cli, err := admin.Dial(config.RPCAddr, admin.WithToken(token), admin.WithInsecure(config.IsInsecure))
cli, err := admin.Dial(rpcAddr, admin.WithToken(token), admin.WithInsecure(viper.GetBool("isInsecure")))
if err != nil {
return err
}
Expand Down
Loading