github.com/emc-advanced-dev/unik@v0.0.0-20190717152701-a58d3e8e33b7/cmd/target.go (about)

     1  package cmd
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"io/ioutil"
     7  	"os"
     8  
     9  	"github.com/sirupsen/logrus"
    10  	"github.com/spf13/cobra"
    11  	"gopkg.in/yaml.v2"
    12  
    13  	"github.com/emc-advanced-dev/pkg/errors"
    14  	"github.com/solo-io/unik/pkg/config"
    15  	"path/filepath"
    16  )
    17  
    18  var show bool
    19  
    20  var targetCmd = &cobra.Command{
    21  	Use:   "target",
    22  	Short: "Configure unik daemon URL for cli client commands",
    23  	Long: `Sets the host url of the unik daemon for cli commands.
    24  If running unik locally, use 'unik target --host localhost'
    25  
    26  args:
    27  --host: <string, required>: host/ip address of the host running the unik daemon
    28  --port: <int, optional>: port the daemon is running on (default: 3000)
    29  
    30  --show: <bool,optional>: shows the current target that is set`,
    31  	Run: func(cmd *cobra.Command, args []string) {
    32  		if err := func() error {
    33  			if show {
    34  				if err := readClientConfig(); err != nil {
    35  					return err
    36  				}
    37  				logrus.Infof("Current target: %s", clientConfig.Host)
    38  				return nil
    39  			}
    40  			if host == "" {
    41  				return errors.New("--host must be set for target", nil)
    42  			}
    43  			if err := setClientConfig(host, port); err != nil {
    44  				return errors.New("failed to save target to config file", err)
    45  			}
    46  			logrus.Infof("target set: %s:%v", host, port)
    47  			return nil
    48  		}(); err != nil {
    49  			logrus.Errorf("failed running target: %v", err)
    50  			os.Exit(-1)
    51  		}
    52  	},
    53  }
    54  
    55  func setClientConfig(host string, port int) error {
    56  	data, err := yaml.Marshal(config.ClientConfig{Host: fmt.Sprintf("%s:%v", host, port)})
    57  	if err != nil {
    58  		return errors.New("failed to convert config to yaml string ", err)
    59  	}
    60  	os.MkdirAll(filepath.Dir(clientConfigFile), 0755)
    61  	if err := ioutil.WriteFile(clientConfigFile, data, 0644); err != nil {
    62  		return errors.New("failed writing config to file "+clientConfigFile, err)
    63  	}
    64  	return nil
    65  }
    66  
    67  func init() {
    68  	RootCmd.AddCommand(targetCmd)
    69  	targetCmd.Flags().BoolVar(&show, "show", false, "<bool,optional>: shows the current target that is set")
    70  }