-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
315 lines (286 loc) · 9.8 KB
/
main.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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
package main
import (
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/urfave/cli/v2"
"github.com/urfave/cli/v2/altsrc"
)
type Config struct {
Backup, State bool
Indent int
Block, InsertBefore, InsertAfter, BeginMarker, EndMarker, Path string
}
func main() {
var indent int
var backup, block, insertBefore, insertAfter, marker, markerBegin, markerEnd, path, state string
flags := []cli.Flag{
altsrc.NewStringFlag(&cli.StringFlag{
Name: "backup",
Usage: "create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.",
Destination: &backup,
DefaultText: "false",
Value: "false",
}),
altsrc.NewStringFlag(&cli.StringFlag{
Name: "block",
Usage: `The text to insert inside the marker lines.
If it is missing or an empty string, the block will be removed as if state were specified to absent.`,
Destination: &block,
}),
altsrc.NewIntFlag(&cli.IntFlag{
Name: "indent",
Usage: "The number of spaces to indent the block. Indent must be >= 0.",
Destination: &indent,
DefaultText: "0",
Value: 0,
}),
altsrc.NewStringFlag(&cli.StringFlag{
Name: "insertafter",
Usage: `If specified and no begin/ending marker lines are found, the block will be inserted after the last match of specified regular expression.
A special value is available; EOF for inserting the block at the end of the file.
If specified regular expression has no matches, EOF will be used instead.`,
Destination: &insertAfter,
Value: "",
}),
altsrc.NewStringFlag(&cli.StringFlag{
Name: "insertbefore",
Usage: `If specified and no begin/ending marker lines are found, the block will be inserted before the last match of specified regular expression.
A special value is available; BOF for inserting the block at the beginning of the file.
If specified regular expression has no matches, the block will be inserted at the end of the file.`,
Destination: &insertBefore,
Value: "",
}),
altsrc.NewStringFlag(&cli.StringFlag{
Name: "marker",
Usage: `The marker line template.
{mark} will be replaced with the values in marker_begin (default="BEGIN") and marker_end (default="END").
Using a custom marker without the {mark} variable may result in the block being repeatedly inserted on subsequent playbook runs.`,
Destination: &marker,
Value: "# {mark} MANAGED BLOCK",
}),
altsrc.NewStringFlag(&cli.StringFlag{
Name: "markerbegin",
Usage: "This will be inserted at {mark} in the opening ansible block marker.",
Destination: &markerBegin,
DefaultText: "BEGIN",
Value: "BEGIN",
}),
altsrc.NewStringFlag(&cli.StringFlag{
Name: "markerend",
Usage: "This will be inserted at {mark} in the closing ansible block marker.",
Destination: &markerEnd,
DefaultText: "END",
Value: "END",
}),
altsrc.NewStringFlag(&cli.StringFlag{
Name: "path",
Usage: "The file to modify. If the path is relative, the working directory of where blockinfile is running will be pre-fixed to the path.",
Destination: &path,
}),
altsrc.NewStringFlag(&cli.StringFlag{
Name: "state",
Usage: "Whether the block should be there or not.",
Destination: &state,
DefaultText: "true",
Value: "true",
}),
&cli.StringFlag{
Name: "config",
Usage: "YAML configuration file containing parameters for blockinfile",
},
}
// TODO Dynamically set the Version
app := &cli.App{
Name: "blockinfile",
Usage: "insert/update/remove a block of multi-line text surrounded by customizable marker lines",
Version: "v0.1.8",
Action: func(c *cli.Context) error {
var backupAsBool, _ = strconv.ParseBool(backup)
var stateAsBool, _ = strconv.ParseBool(state)
config := Config{
Backup: backupAsBool,
State: stateAsBool,
Indent: indent,
Block: block,
InsertBefore: insertBefore,
InsertAfter: insertAfter,
BeginMarker: strings.Replace(marker, "{mark}", markerBegin, 1),
EndMarker: strings.Replace(marker, "{mark}", markerEnd, 1),
Path: getFullPath(path),
}
updateBlockInFile(config)
return nil
},
Before: altsrc.InitInputSourceWithContext(flags, altsrc.NewYamlSourceFromFlagFunc("config")),
Flags: flags,
}
sort.Sort(cli.FlagsByName(app.Flags))
sort.Sort(cli.CommandsByName(app.Commands))
if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
}
func backupFile(sourceFile string) {
input, err := ioutil.ReadFile(sourceFile)
if err != nil {
log.Fatal(err)
return
}
var backupFile = sourceFile + "." + time.Now().Format(time.RFC3339)
if err := ioutil.WriteFile(backupFile, input, 0644); err != nil {
fmt.Println("Error creating", backupFile)
log.Fatal(err)
return
}
}
func checkFlags(config Config) error {
if config.Path == "" {
return errors.New("required flag \"path\" not set")
}
if config.InsertBefore != "" && config.InsertAfter != "" {
return errors.New("only one of these flags can be used at a time [markerbegin|markerend]")
}
return nil
}
// If path is relative, add working directory as prefix to path; otherwise, return the existing full path
func getFullPath(path string) string {
if strings.HasPrefix(path, string(os.PathSeparator)) {
return path
}
wd, _ := os.Getwd()
return wd + string(os.PathSeparator) + path
}
func replaceTextBetweenMarkersInFile(config Config) {
// Read entire file content, giving us little control but
// making it very simple. No need to close the file.
content, err := ioutil.ReadFile(config.Path)
if err != nil {
log.Fatal(err)
}
f, err := os.OpenFile(config.Path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)
if err != nil {
log.Fatal(err)
}
_, err = f.WriteString(replaceTextBetweenMarkers(string(content), config))
defer f.Close()
}
func removeExistingBlock(sourceText, beginMarker, endMarker string) string {
// Add \n because markers could have similar prefix, \n will make sure match to end of line
beginIndex := strings.LastIndex(sourceText, beginMarker+"\n")
if beginIndex >= 0 {
sourceText = removeLeadingSpacesOfBlock(sourceText, beginIndex)
// After removing leading spaces, reset beginIndex
beginIndex := strings.LastIndex(sourceText, beginMarker+"\n")
endIndex := strings.LastIndex(sourceText, endMarker) + len(endMarker) + 1
return sourceText[:beginIndex] + sourceText[endIndex:]
}
return sourceText
}
func removeLeadingSpacesOfBlock(sourceText string, beginIndex int) string {
// Remove any leading spaces of block
beginNonSpaceIndex := beginIndex
for nonSpaceIndex := beginIndex - 1; nonSpaceIndex >= 0; nonSpaceIndex-- {
if sourceText[nonSpaceIndex] != ' ' {
break
}
beginNonSpaceIndex = nonSpaceIndex
}
sourceText = sourceText[:beginNonSpaceIndex] + sourceText[beginIndex:]
return sourceText
}
func replaceTextBetweenMarkers(sourceText string, config Config) string {
reAddSpaces := regexp.MustCompile(`\r?\n`)
paddedBeginMarker := fmt.Sprintf("%s%s", strings.Repeat(" ", config.Indent), config.BeginMarker)
paddedEndMarker := fmt.Sprintf("%s%s", strings.Repeat(" ", config.Indent), config.EndMarker)
paddedReplaceText := fmt.Sprintf("%s%s", strings.Repeat(" ", config.Indent),
reAddSpaces.ReplaceAllString(config.Block, "\n"+strings.Repeat(" ", config.Indent)))
switch {
case !config.State:
return removeExistingBlock(sourceText, config.BeginMarker, config.EndMarker)
case config.InsertBefore != "":
sourceText = removeExistingBlock(sourceText, config.BeginMarker, config.EndMarker)
var index = strings.LastIndex(sourceText, config.InsertBefore)
// Not found, insert at EOF
if index < 0 {
return fmt.Sprintf("%s%s\n%s\n%s\n",
sourceText,
paddedBeginMarker,
paddedReplaceText,
paddedEndMarker)
}
// Insert before
return fmt.Sprintf("%s%s\n%s\n%s\n%s",
sourceText[:index],
paddedBeginMarker,
paddedReplaceText,
paddedEndMarker,
sourceText[index:])
case config.InsertAfter != "":
sourceText = removeExistingBlock(sourceText, config.BeginMarker, config.EndMarker)
var index = strings.LastIndex(sourceText, config.InsertAfter)
// Not found, insert at EOF
if index < 0 {
return fmt.Sprintf("%s%s\n%s\n%s\n",
sourceText,
paddedBeginMarker,
paddedReplaceText,
paddedEndMarker)
}
// Insert after
index = index + len(config.InsertAfter)
return fmt.Sprintf("%s\n%s\n%s\n%s%s",
sourceText[:index],
paddedBeginMarker,
paddedReplaceText,
paddedEndMarker,
sourceText[index:])
case strings.Contains(sourceText, config.BeginMarker+"\n"):
// Remove any leading spaces before replacing the block in case indentation changed
beginIndex := strings.LastIndex(sourceText, config.BeginMarker+"\n")
sourceText = removeLeadingSpacesOfBlock(sourceText, beginIndex)
// Replace existing block
reReplaceMarker := regexp.MustCompile(fmt.Sprintf("(?s)%s(.*?)%s", config.BeginMarker+"\n", config.EndMarker))
return reReplaceMarker.ReplaceAllString(sourceText,
fmt.Sprintf("%s\n%s\n%s",
paddedBeginMarker,
paddedReplaceText,
paddedEndMarker),
)
default:
// Not found, add to EOF
return fmt.Sprintf("%s%s\n%s\n%s\n",
sourceText,
paddedBeginMarker,
paddedReplaceText,
paddedEndMarker)
}
}
func updateBlockInFile(config Config) {
if err := checkFlags(config); err != nil {
log.Fatal(err)
}
// Make sure file exists by touching it
if err := touchFile(config.Path); err != nil {
log.Fatal(err)
}
if config.Backup {
backupFile(config.Path)
}
replaceTextBetweenMarkersInFile(config)
}
func touchFile(path string) error {
file, err := os.OpenFile(path, os.O_RDONLY|os.O_CREATE, 0644)
if err != nil {
return err
}
defer file.Close()
return nil
}