go.etcd.io/etcd@v3.3.27+incompatible/etcdctl/ctlv2/command/set_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  	"os"
    20  	"time"
    21  
    22  	"github.com/coreos/etcd/client"
    23  	"github.com/urfave/cli"
    24  )
    25  
    26  // NewSetCommand returns the CLI command for "set".
    27  func NewSetCommand() cli.Command {
    28  	return cli.Command{
    29  		Name:      "set",
    30  		Usage:     "set the value of a key",
    31  		ArgsUsage: "<key> <value>",
    32  		Description: `Set sets the value of a key.
    33  
    34     When <value> begins with '-', <value> is interpreted as a flag.
    35     Insert '--' for workaround:
    36  
    37     $ set -- <key> <value>`,
    38  		Flags: []cli.Flag{
    39  			cli.IntFlag{Name: "ttl", Value: 0, Usage: "key time-to-live in seconds"},
    40  			cli.StringFlag{Name: "swap-with-value", Value: "", Usage: "previous value"},
    41  			cli.IntFlag{Name: "swap-with-index", Value: 0, Usage: "previous index"},
    42  		},
    43  		Action: func(c *cli.Context) error {
    44  			setCommandFunc(c, mustNewKeyAPI(c))
    45  			return nil
    46  		},
    47  	}
    48  }
    49  
    50  // setCommandFunc executes the "set" command.
    51  func setCommandFunc(c *cli.Context, ki client.KeysAPI) {
    52  	if len(c.Args()) == 0 {
    53  		handleError(c, ExitBadArgs, errors.New("key required"))
    54  	}
    55  	key := c.Args()[0]
    56  	value, err := argOrStdin(c.Args(), os.Stdin, 1)
    57  	if err != nil {
    58  		handleError(c, ExitBadArgs, errors.New("value required"))
    59  	}
    60  
    61  	ttl := c.Int("ttl")
    62  	prevValue := c.String("swap-with-value")
    63  	prevIndex := c.Int("swap-with-index")
    64  
    65  	ctx, cancel := contextWithTotalTimeout(c)
    66  	resp, err := ki.Set(ctx, key, value, &client.SetOptions{TTL: time.Duration(ttl) * time.Second, PrevIndex: uint64(prevIndex), PrevValue: prevValue})
    67  	cancel()
    68  	if err != nil {
    69  		handleError(c, ExitServerError, err)
    70  	}
    71  
    72  	printResponseKey(resp, c.GlobalString("output"))
    73  }