-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathprogram.go
More file actions
342 lines (311 loc) · 9.14 KB
/
Copy pathprogram.go
File metadata and controls
342 lines (311 loc) · 9.14 KB
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
package hpatch
import (
"errors"
"fmt"
"path/filepath"
"regexp"
"strconv"
"strings"
"github.com/yusing/hpatch/internal/hpatchsyntax"
)
var (
absoluteLinePattern = regexp.MustCompile(`^[1-9][0-9]*$`)
textSelectPattern = regexp.MustCompile(`^tsel (\S+) (.+)$`)
hashRangePattern = regexp.MustCompile(`^rsel (\S+) (\S+)$`)
)
type instruction struct {
attempt commandAttempt
source string
line int
operation string
path string
lineHash string
endHash string
count int
text string
delimiter string
lineTerminator string
}
type program struct {
instructions []instruction
}
type commandGroupError struct {
commands []*commandError
}
func (e *commandGroupError) Error() string {
messages := make([]string, len(e.commands))
for index, command := range e.commands {
messages[index] = command.Error()
}
return strings.Join(messages, "\n")
}
func (e *commandGroupError) Unwrap() []error {
failures := make([]error, len(e.commands))
for index, command := range e.commands {
failures[index] = command
}
return failures
}
func commandsOf(err error) []*commandError {
if failures, ok := errors.AsType[*commandGroupError](err); ok {
return failures.commands
}
if command, ok := errors.AsType[*commandError](err); ok {
return []*commandError{command}
}
return nil
}
type commandError struct {
Attempt commandAttempt
Reason failureReason
Command int
Line int
Operation string
Path string
Category string
Source string
Message string
// Repair is multi-line baseline context that a retry needs in order to
// correct this command. It is excluded from Error, whose result is
// sanitized onto one line, and is emitted separately.
Repair string
Correction string
}
func (e *commandError) Error() string {
var context []string
if e.Command != 0 {
context = append(context, fmt.Sprintf("command %d", e.Command))
}
context = append(context, fmt.Sprintf("source line %d", e.Line))
if e.Operation != "" {
context = append(context, fmt.Sprintf("operation %q", e.Operation))
}
if e.Path != "" {
context = append(context, fmt.Sprintf("path %q", e.Path))
}
if e.Category != "" {
context = append(context, "category "+e.Category)
}
return fmt.Sprintf("%s: %s", strings.Join(context, ", "), e.Message)
}
func parse(source string) (*program, error) {
program := &program{}
var failures []*commandError
commandIndex := 0
lines := hpatchsyntax.SplitPhysicalLines(source)
for index := 0; index < len(lines); {
headerIndex := index
line := lines[headerIndex].Text
index++
if strings.TrimSpace(line) == "" {
continue
}
commandIndex++
sourceLine := headerIndex + 1
attempt := recognizeCommandAttempt(line)
frame, frameErr := hpatchsyntax.FrameCommand(lines, headerIndex, line)
index = frame.Next
var command instruction
var err error
switch {
case frameErr != nil:
err = scriptError(sourceLine, frameErr.Error())
case frame.Delimiter != "":
command = instruction{line: sourceLine, operation: "type", text: frame.Body}
default:
command, err = parseInstruction(sourceLine, line)
}
if err != nil {
message := err.Error()
if sourceError, ok := errors.AsType[*commandError](err); ok {
message = sourceError.Message
}
failures = append(failures, &commandError{
Attempt: attempt,
Reason: reasonOf(err, reasonSyntax),
Command: commandIndex,
Line: sourceLine,
Operation: strings.Fields(line)[0],
Category: "syntax",
Source: line,
Message: message,
})
continue
}
command.source = line
command.delimiter = frame.Delimiter
command.lineTerminator = lines[headerIndex].Terminator
command.attempt = attemptForInstruction(command)
program.instructions = append(program.instructions, command)
}
if len(failures) != 0 {
return nil, &commandGroupError{commands: failures}
}
return program, nil
}
func recognizeCommandAttempt(line string) commandAttempt {
fields := strings.Fields(line)
if len(fields) == 0 {
return commandAttempt{}
}
switch fields[0] {
case "in", "new", "mv", "rm", "type", "del", "copy", "cut", "paste", "commit":
return commandAttempt{recognized: true}
case "rsel":
return commandAttempt{recognized: len(fields) >= 3 && isLowerHexHash(fields[1]) && isLowerHexHash(fields[2])}
case "tsel":
span := recognizeTextSpanVariant(line)
if len(fields) < 2 || !isLowerHexHash(fields[1]) || span == textSpanNone {
return commandAttempt{}
}
return commandAttempt{recognized: true, textSpan: span}
default:
return commandAttempt{}
}
}
func isLowerHexHash(value string) bool {
if len(value) != lineHashLength {
return false
}
for _, character := range value {
if (character < '0' || character > '9') && (character < 'a' || character > 'f') {
return false
}
}
return true
}
func recognizeTextSpanVariant(line string) textSpanVariant {
match := textSelectPattern.FindStringSubmatch(line)
if match == nil {
return textSpanNone
}
_, trailing, err := hpatchsyntax.DecodeQuoted(match[2])
if err != nil {
return textSpanNone
}
trailing = strings.TrimSpace(trailing)
if trailing != "" && trailing != "1" {
return textSpanMultiple
}
return textSpanSingle
}
func attemptForInstruction(command instruction) commandAttempt {
attempt := commandAttempt{recognized: true}
if command.operation == "tsel" {
attempt.textSpan = textSpanSingle
if command.count > 1 {
attempt.textSpan = textSpanMultiple
}
}
return attempt
}
func parseInstruction(sourceLine int, line string) (instruction, error) {
for _, operation := range []string{"in", "new", "mv"} {
if path, ok := strings.CutPrefix(line, operation+" "); ok {
if path == "" {
return instruction{}, scriptError(sourceLine, "path must not be empty")
}
return instruction{line: sourceLine, operation: operation, path: filepath.Clean(path)}, nil
}
}
if line == "rm" || line == "del" || line == "copy" || line == "cut" || line == "paste" || line == "commit" {
return instruction{line: sourceLine, operation: line}, nil
}
if match := textSelectPattern.FindStringSubmatch(line); match != nil {
hash, err := parseLineHash(sourceLine, match[1])
if err != nil {
return instruction{}, err
}
value, count, err := decodeTextSelection(match[2])
if err != nil {
return instruction{}, scriptFailure(sourceLine, reasonOf(err, reasonSyntax), err.Error())
}
if value == "" {
return instruction{}, scriptError(sourceLine, "tsel text must not be empty")
}
if strings.ContainsAny(value, "\r\n") {
return instruction{}, scriptError(sourceLine, "tsel text must stay on one line")
}
return instruction{
line: sourceLine,
operation: "tsel",
lineHash: hash,
count: count,
text: value,
}, nil
}
if match := hashRangePattern.FindStringSubmatch(line); match != nil {
startHash, err := parseLineHash(sourceLine, match[1])
if err != nil {
return instruction{}, err
}
endHash, err := parseLineHash(sourceLine, match[2])
if err != nil {
return instruction{}, err
}
return instruction{
line: sourceLine,
operation: "rsel",
lineHash: startHash,
endHash: endHash,
}, nil
}
if valueText, ok := strings.CutPrefix(line, "type "); ok {
value, trailing, err := hpatchsyntax.DecodeQuoted(valueText)
if err != nil {
return instruction{}, scriptError(sourceLine, "invalid quoted string for type: "+err.Error())
}
if !onlyOperandWhitespace(trailing) {
return instruction{}, scriptError(sourceLine, "trailing text after type string")
}
return instruction{line: sourceLine, operation: "type", text: value}, nil
}
return instruction{}, scriptError(sourceLine, "unknown or malformed command")
}
func decodeTextSelection(encoded string) (string, int, error) {
text, trailing, err := hpatchsyntax.DecodeQuoted(encoded)
if err != nil {
return "", 0, fmt.Errorf("invalid quoted string for tsel: %w", err)
}
if trailing == "" {
return text, 1, nil
}
if !isOperandWhitespace(trailing[0]) {
return "", 0, withReason(reasonInvalidCount, errors.New("tsel count must be separated by whitespace"))
}
countText := strings.Trim(trailing, " \t\r\n")
if countText == "" {
return text, 1, nil
}
if !absoluteLinePattern.MatchString(countText) {
return "", 0, withReason(reasonInvalidCount, errors.New("invalid tsel count"))
}
count, err := strconv.Atoi(countText)
if err != nil {
return "", 0, withReason(reasonInvalidCount, errors.New("tsel count is out of range"))
}
return text, count, nil
}
func onlyOperandWhitespace(value string) bool {
for index := range len(value) {
if !isOperandWhitespace(value[index]) {
return false
}
}
return true
}
func isOperandWhitespace(character byte) bool {
return character == ' ' || character == '\t' || character == '\r' || character == '\n'
}
func parseLineHash(sourceLine int, value string) (string, error) {
if !isLowerHexHash(value) {
return "", scriptError(sourceLine, fmt.Sprintf("invalid hashline reference %q", value))
}
return value, nil
}
func scriptError(line int, message string) *commandError {
return scriptFailure(line, reasonSyntax, message)
}
func scriptFailure(line int, reason failureReason, message string) *commandError {
return &commandError{Line: line, Reason: reason, Message: message}
}