github.com/spinnaker/spin@v1.30.0/cmd/canary/canary-config/get.go (about)

     1  // Copyright (c) 2019, Waze, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //   http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  //   Unless required by applicable law or agreed to in writing, software
    10  //   distributed under the License is distributed on an "AS IS" BASIS,
    11  //   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  //   See the License for the specific language governing permissions and
    13  //   limitations under the License.
    14  
    15  package canary_config
    16  
    17  import (
    18  	"errors"
    19  	"fmt"
    20  	"net/http"
    21  
    22  	"github.com/spf13/cobra"
    23  
    24  	gate "github.com/spinnaker/spin/gateapi"
    25  	"github.com/spinnaker/spin/util"
    26  )
    27  
    28  type getOptions struct {
    29  	*canaryConfigOptions
    30  	id string
    31  }
    32  
    33  const (
    34  	getCanaryConfigShort = "Get the canary config with the provided id"
    35  	getCanaryConfigLong  = "Get the specified canary config"
    36  )
    37  
    38  func NewGetCmd(canaryConfigOptions *canaryConfigOptions) *cobra.Command {
    39  	options := &getOptions{
    40  		canaryConfigOptions: canaryConfigOptions,
    41  	}
    42  	cmd := &cobra.Command{
    43  		Use:   "get",
    44  		Short: getCanaryConfigShort,
    45  		Long:  getCanaryConfigLong,
    46  		RunE: func(cmd *cobra.Command, args []string) error {
    47  			return getCanaryConfig(cmd, options, args)
    48  		},
    49  	}
    50  
    51  	cmd.PersistentFlags().StringVar(&options.id, "id", "", "id of the canary config")
    52  
    53  	return cmd
    54  }
    55  
    56  func getCanaryConfig(cmd *cobra.Command, options *getOptions, args []string) error {
    57  	var err error
    58  	id := options.id
    59  	if id == "" {
    60  		id, err = util.ReadArgsOrStdin(args)
    61  		if err != nil {
    62  			return err
    63  		}
    64  		if id == "" {
    65  			return errors.New("no canary config id supplied, exiting")
    66  		}
    67  	}
    68  
    69  	successPayload, resp, err := options.GateClient.V2CanaryConfigControllerApi.GetCanaryConfigUsingGET(
    70  		options.GateClient.Context, id, &gate.V2CanaryConfigControllerApiGetCanaryConfigUsingGETOpts{})
    71  	if err != nil {
    72  		return err
    73  	}
    74  
    75  	if resp.StatusCode != http.StatusOK {
    76  		return fmt.Errorf("Encountered an error getting canary config with id %s, status code: %d\n",
    77  			id,
    78  			resp.StatusCode)
    79  	}
    80  
    81  	options.Ui.JsonOutput(successPayload)
    82  	return nil
    83  }