-
Notifications
You must be signed in to change notification settings - Fork 23
/
common.go
44 lines (41 loc) · 993 Bytes
/
common.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package cmd
import (
"encoding/json"
"fmt"
"github.com/mattolenik/hclq/config"
"io"
"os"
"strings"
)
func getOutput(obj interface{}, raw bool) (string, error) {
if raw {
result := ""
arr, isArray := obj.([]interface{})
if isArray {
for _, item := range arr {
// Simple output, uses built-in %v, most useful for simple types.
result += strings.Trim(fmt.Sprintf("%v", item), `"`) + " "
}
result = strings.TrimRight(result, " ")
return result, nil
}
return strings.Trim(fmt.Sprintf("%v", obj), `"`), nil
}
jsonBody, err := json.Marshal(obj)
if err != nil {
return "", err
}
return string(jsonBody), nil
}
// getInputReader provides an io.Reader for reading from either a file
// or stdin, depending on whether or not an input file was specified.
func getInputReader() (io.Reader, error) {
if val := config.InputFile; val != "" {
reader, err := os.Open(val)
if err != nil {
return nil, err
}
return reader, nil
}
return os.Stdin, nil
}