go.etcd.io/etcd@v3.3.27+incompatible/etcdctl/ctlv2/command/get_command.go (about)

     1  // Copyright 2015 The etcd Authors
     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 command
    16  
    17  import (
    18  	"errors"
    19  	"fmt"
    20  	"os"
    21  
    22  	"github.com/coreos/etcd/client"
    23  	"github.com/urfave/cli"
    24  )
    25  
    26  // NewGetCommand returns the CLI command for "get".
    27  func NewGetCommand() cli.Command {
    28  	return cli.Command{
    29  		Name:      "get",
    30  		Usage:     "retrieve the value of a key",
    31  		ArgsUsage: "<key>",
    32  		Flags: []cli.Flag{
    33  			cli.BoolFlag{Name: "sort", Usage: "returns result in sorted order"},
    34  			cli.BoolFlag{Name: "quorum, q", Usage: "require quorum for get request"},
    35  		},
    36  		Action: func(c *cli.Context) error {
    37  			getCommandFunc(c, mustNewKeyAPI(c))
    38  			return nil
    39  		},
    40  	}
    41  }
    42  
    43  // getCommandFunc executes the "get" command.
    44  func getCommandFunc(c *cli.Context, ki client.KeysAPI) {
    45  	if len(c.Args()) == 0 {
    46  		handleError(c, ExitBadArgs, errors.New("key required"))
    47  	}
    48  
    49  	key := c.Args()[0]
    50  	sorted := c.Bool("sort")
    51  	quorum := c.Bool("quorum")
    52  
    53  	ctx, cancel := contextWithTotalTimeout(c)
    54  	resp, err := ki.Get(ctx, key, &client.GetOptions{Sort: sorted, Quorum: quorum})
    55  	cancel()
    56  	if err != nil {
    57  		handleError(c, ExitServerError, err)
    58  	}
    59  
    60  	if resp.Node.Dir {
    61  		fmt.Fprintln(os.Stderr, fmt.Sprintf("%s: is a directory", resp.Node.Key))
    62  		os.Exit(1)
    63  	}
    64  
    65  	printResponseKey(resp, c.GlobalString("output"))
    66  }