Browse Source

Move data source loading into a command helpers function

pull/4156/head
Matt Keeler 7 years ago
parent
commit
2e7a37890c
  1. 42
      command/helpers/helpers.go
  2. 36
      command/kv/put/kv_put.go

42
command/helpers/helpers.go

@ -0,0 +1,42 @@
package helpers
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
)
func LoadDataSource(data string, testStdin io.Reader) (string, error) {
var stdin io.Reader = os.Stdin
if testStdin != nil {
stdin = testStdin
}
// Handle empty quoted shell parameters
if len(data) == 0 {
return "", nil
}
switch data[0] {
case '@':
data, err := ioutil.ReadFile(data[1:])
if err != nil {
return "", fmt.Errorf("Failed to read file: %s", err)
} else {
return string(data), nil
}
case '-':
if len(data) > 1 {
return data, nil
}
var b bytes.Buffer
if _, err := io.Copy(&b, stdin); err != nil {
return "", fmt.Errorf("Failed to read stdin: %s", err)
}
return b.String(), nil
default:
return data, nil
}
}

36
command/kv/put/kv_put.go

@ -1,16 +1,14 @@
package put package put
import ( import (
"bytes"
"encoding/base64" "encoding/base64"
"flag" "flag"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"os"
"github.com/hashicorp/consul/api" "github.com/hashicorp/consul/api"
"github.com/hashicorp/consul/command/flags" "github.com/hashicorp/consul/command/flags"
"github.com/hashicorp/consul/command/helpers"
"github.com/mitchellh/cli" "github.com/mitchellh/cli"
) )
@ -173,11 +171,6 @@ func (c *cmd) Run(args []string) int {
} }
func (c *cmd) dataFromArgs(args []string) (string, string, error) { func (c *cmd) dataFromArgs(args []string) (string, string, error) {
var stdin io.Reader = os.Stdin
if c.testStdin != nil {
stdin = c.testStdin
}
switch len(args) { switch len(args) {
case 0: case 0:
return "", "", fmt.Errorf("Missing KEY argument") return "", "", fmt.Errorf("Missing KEY argument")
@ -189,30 +182,11 @@ func (c *cmd) dataFromArgs(args []string) (string, string, error) {
} }
key := args[0] key := args[0]
data := args[1] data, err := helpers.LoadDataSource(args[1], c.testStdin)
// Handle empty quoted shell parameters if err != nil {
if len(data) == 0 { return "", "", err
return key, "", nil } else {
}
switch data[0] {
case '@':
data, err := ioutil.ReadFile(data[1:])
if err != nil {
return "", "", fmt.Errorf("Failed to read file: %s", err)
}
return key, string(data), nil
case '-':
if len(data) > 1 {
return key, data, nil
}
var b bytes.Buffer
if _, err := io.Copy(&b, stdin); err != nil {
return "", "", fmt.Errorf("Failed to read stdin: %s", err)
}
return key, b.String(), nil
default:
return key, data, nil return key, data, nil
} }
} }

Loading…
Cancel
Save