-
Notifications
You must be signed in to change notification settings - Fork 1
/
apply.go
145 lines (112 loc) · 2.54 KB
/
apply.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
package main
import (
"bufio"
"fmt"
"io"
"os"
"strconv"
"strings"
"github.com/urfave/cli/v2"
)
var (
applyConfig struct {
bak string
}
applyFlags = []cli.Flag{
&cli.StringFlag{
Name: "bak",
Aliases: []string{"i"},
Destination: &applyConfig.bak,
Usage: "if not empty, backup originals with given suffix",
Category: "apply",
},
}
)
func apply(r io.Reader) error {
s := bufio.NewScanner(r)
acc := struct {
path string
data map[int]string
}{
data: make(map[int]string),
}
flush := func() error {
if len(acc.data) == 0 {
return nil
}
if err := apply1(acc.path, acc.data); err != nil {
return fmt.Errorf("%s: %w", acc.path, err)
}
acc.path = ""
acc.data = make(map[int]string)
return nil
}
for i := 0; s.Scan(); i++ {
text := strings.TrimLeft(s.Text(), " \t")
if !commonConfig.nowd && strings.HasPrefix(text, wdprefix) {
expectedwd := text[len(wdprefix):]
wd, err := os.Getwd()
if err != nil {
return fmt.Errorf("getwd: %w", err)
}
if wd != expectedwd {
return fmt.Errorf("current wd %s != expected %s, use --nowd to suppress", wd, expectedwd)
}
continue
}
if len(text) == 0 || text[0] == '#' {
continue
}
if commonConfig.print {
fmt.Fprintln(os.Stderr, text)
}
invErr := func() error { return fmt.Errorf("invalid input line %d", i) }
parts := strings.SplitN(text, ":", 3)
if len(parts) != 3 {
return invErr()
}
lineNum, err := strconv.ParseInt(parts[1], 10, 32)
if err != nil || lineNum <= 0 {
return invErr()
}
if path := parts[0]; acc.path != path {
if err := flush(); err != nil {
return err
}
acc.path = path
}
acc.data[int(lineNum)] = parts[2]
}
if err := flush(); err != nil {
return err
}
return nil
}
// TODO: all contents is read into memory. Need to do it piecewise.
func apply1(path string, data map[int]string) error {
content, err := os.ReadFile(path)
if err != nil {
return fmt.Errorf("%s: %w", path, err)
}
if bak := applyConfig.bak; len(bak) > 0 {
if err := os.WriteFile(path+bak, content, 0755); err != nil {
return fmt.Errorf("backup %s%s: %w", path, bak, err)
}
}
f, err := os.Create(path)
if err != nil {
return fmt.Errorf("create %s: %w", path, err)
}
defer f.Close()
s := bufio.NewScanner(strings.NewReader(string(content)))
for lineNum := 1; s.Scan(); lineNum++ {
out, ok := data[lineNum]
if !ok {
out = s.Text()
}
if _, err := f.WriteString(out + "\n"); err != nil {
return fmt.Errorf("write %s: %w", path, err)
}
}
return nil
}