go.etcd.io/etcd@v3.3.27+incompatible/etcdctl/ctlv2/command/mk_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 // NewMakeCommand returns the CLI command for "mk". 27 func NewMakeCommand() cli.Command { 28 return cli.Command{ 29 Name: "mk", 30 Usage: "make a new key with a given value", 31 ArgsUsage: "<key> <value>", 32 Flags: []cli.Flag{ 33 cli.BoolFlag{Name: "in-order", Usage: "create in-order key under directory <key>"}, 34 cli.IntFlag{Name: "ttl", Value: 0, Usage: "key time-to-live in seconds"}, 35 }, 36 Action: func(c *cli.Context) error { 37 mkCommandFunc(c, mustNewKeyAPI(c)) 38 return nil 39 }, 40 } 41 } 42 43 // mkCommandFunc executes the "mk" command. 44 func mkCommandFunc(c *cli.Context, ki client.KeysAPI) { 45 if len(c.Args()) == 0 { 46 handleError(c, ExitBadArgs, errors.New("key required")) 47 } 48 key := c.Args()[0] 49 value, err := argOrStdin(c.Args(), os.Stdin, 1) 50 if err != nil { 51 handleError(c, ExitBadArgs, errors.New("value required")) 52 } 53 54 ttl := c.Int("ttl") 55 inorder := c.Bool("in-order") 56 57 var resp *client.Response 58 ctx, cancel := contextWithTotalTimeout(c) 59 if !inorder { 60 // Since PrevNoExist means that the Node must not exist previously, 61 // this Set method always creates a new key. Therefore, mk command 62 // succeeds only if the key did not previously exist, and the command 63 // prevents one from overwriting values accidentally. 64 resp, err = ki.Set(ctx, key, value, &client.SetOptions{TTL: time.Duration(ttl) * time.Second, PrevExist: client.PrevNoExist}) 65 } else { 66 // If in-order flag is specified then create an inorder key under 67 // the directory identified by the key argument. 68 resp, err = ki.CreateInOrder(ctx, key, value, &client.CreateInOrderOptions{TTL: time.Duration(ttl) * time.Second}) 69 } 70 cancel() 71 if err != nil { 72 handleError(c, ExitServerError, err) 73 } 74 75 printResponseKey(resp, c.GlobalString("output")) 76 }