forked from mattolenik/hclq
/
set.go
181 lines (166 loc) · 4.5 KB
/
set.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
package cmd
import (
"fmt"
"io"
"os"
"strconv"
"strings"
"github.com/hashicorp/hcl/hcl/ast"
"github.com/hashicorp/hcl/hcl/token"
"github.com/spf13/cobra"
"github.com/tibrn/hclq/config"
"github.com/tibrn/hclq/hclq"
)
// SetCmd cobra command
var SetCmd = &cobra.Command{
Use: "set <query> <newValue>",
Short: "set matching value(s), specify a string, number, or JSON object or array",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
newValue := args[1]
return performSet(args[0],
func(list *ast.ListType) error {
listNode, err := hclq.HclListFromJSON(newValue)
if err != nil {
return err
}
list.List = listNode.List
return nil
}, func(tok *token.Token) error {
tok.Text = `"` + newValue + `"`
tok.Type = getTokenType(newValue)
return nil
})
},
}
// AppendCmd cobra command
var AppendCmd = &cobra.Command{
Use: "append <query> <newValue>",
Short: "append value(s) to a list or a string",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
newValue := args[1]
return performSet(args[0],
func(list *ast.ListType) error {
node, err := hclq.HclFromJSON(newValue)
if err != nil {
return err
}
list.List = append(list.List, node)
return nil
}, func(tok *token.Token) error {
tok.Text = `"` + trimToken(tok.Text) + newValue + `"`
tok.Type = token.STRING
return nil
})
},
}
// PrependCmd cobra command
var PrependCmd = &cobra.Command{
Use: "prepend <query> <newValue>",
Short: "prepend value(s) to a list or a string",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
newValue := args[1]
return performSet(args[0],
func(list *ast.ListType) error {
node, err := hclq.HclFromJSON(newValue)
if err != nil {
return err
}
list.List = append(node.(*ast.ListType).List, list.List...)
return nil
}, func(tok *token.Token) error {
tok.Text = `"` + newValue + trimToken(tok.Text) + `"`
tok.Type = token.STRING
return nil
})
},
}
// ReplaceCmd cobra command
var ReplaceCmd = &cobra.Command{
Use: "replace <query> <oldSequence> <newSequence>",
Short: "find and replace a subsequence of items (or chars for strings)",
Args: cobra.ExactArgs(3),
RunE: func(cmd *cobra.Command, args []string) error {
return performSet(args[0],
func(list *ast.ListType) error {
// TODO: implement replace on lists
panic("replace on lists is not implemented yet")
}, func(tok *token.Token) error {
tok.Text = `"` + strings.Replace(trimToken(tok.Text), args[1], args[2], config.ReplaceNTimes) + `"`
tok.Type = token.STRING
return nil
})
},
}
func trimToken(tok string) string {
return strings.Trim(tok, `"`)
}
func getTokenType(val string) token.Type {
_, err := strconv.ParseInt(val, 0, 64)
if err == nil {
return token.NUMBER
}
_, err = strconv.ParseFloat(val, 64)
if err == nil {
return token.FLOAT
}
_, err = strconv.ParseBool(val)
if err == nil {
return token.BOOL
}
return token.STRING
// TODO: support HEREDOC
}
func init() {
SetCmd.PersistentFlags().BoolVarP(&config.ModifyInPlace, "in-place", "", false, "edit the input file in-place rather than printing to stdout, conflicts with --out")
SetCmd.AddCommand(AppendCmd)
SetCmd.AddCommand(PrependCmd)
SetCmd.AddCommand(ReplaceCmd)
RootCmd.AddCommand(SetCmd)
ReplaceCmd.Flags().IntVarP(&config.ReplaceNTimes, "replace-n", "n", -1, "Limit replacements to n occurrences")
}
func performSet(queryString string, listAction func(*ast.ListType) error, valueAction func(*token.Token) error) error {
err := validateOutputConfig()
if err != nil {
return err
}
reader, err := getInputReader()
if err != nil {
return err
}
doc, err := hclq.FromReader(reader)
if err != nil {
return err
}
err = doc.Set(queryString, listAction, valueAction)
if err != nil {
return err
}
writer, err := getOutputWriter()
if err != nil {
return err
}
defer writer.Close()
doc.Print(writer)
return nil
}
func getOutputWriter() (io.WriteCloser, error) {
if config.OutputFile != "" {
return os.Create(config.OutputFile)
}
if config.ModifyInPlace {
return os.Create(config.InputFile)
}
return os.Stdout, nil
}
func validateOutputConfig() error {
if config.ModifyInPlace && len(config.OutputFile) > 0 {
return fmt.Errorf("cannot use both --modify and --out at the same time")
}
if config.ModifyInPlace && len(config.InputFile) == 0 {
return fmt.Errorf("cannot use --modify without specifying an input file with --in")
}
return nil
}