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)
}
}
31 changes: 31 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,27 @@ func Delete() error {

return nil
}

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

if _, err := os.Stat(filepath.Clean(configPathValue)); err != nil {
if os.IsNotExist(err) {
if saveErr := Save(New()); saveErr != nil {
return fmt.Errorf("save default config: %w", saveErr)
}
} else {
return fmt.Errorf("check config file: %w", err)
}
}

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.Preload,
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.Preload,
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.Preload,
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.Preload,
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.Preload,
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