-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathprogram.go
More file actions
438 lines (404 loc) · 12.7 KB
/
Copy pathprogram.go
File metadata and controls
438 lines (404 loc) · 12.7 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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
package hpatch
import (
"errors"
"fmt"
"path/filepath"
"regexp"
"strconv"
"strings"
"github.com/yusing/hpatch/internal/hpatchsyntax"
)
var (
positiveDecimalPattern = regexp.MustCompile(`^[1-9][0-9]*$`)
rowPattern = regexp.MustCompile(`^([1-9][0-9]*):([0-9a-f]{4})$`)
)
type targetKind uint8
const (
targetNone targetKind = iota
targetLine
targetRange
targetText
)
type rowReference struct {
line int
hash string
}
type targetSpec struct {
kind targetKind
start rowReference
end rowReference
literal string
count int
}
func (t targetSpec) variant() targetVariant {
switch t.kind {
case targetLine:
return targetVariantLine
case targetRange:
return targetVariantRange
case targetText:
if t.count > 1 {
return targetVariantTextMultiple
}
return targetVariantTextSingle
default:
return targetVariantNone
}
}
type instruction struct {
attempt commandAttempt
source string
line int
operation string
path string
target targetSpec
text string
valueStart int
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
GeneratedLine int
GeneratedColumn int
ValueLine int
// 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)
}
if int(e.Reason) < len(failureReasonNames) {
context = append(context, "reason "+failureReasonNames[e.Reason])
}
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 != "":
header := strings.TrimSuffix(line, " <<PATCH")
if header == "type" {
command = instruction{line: sourceLine, operation: "type", text: frame.Body}
} else {
command, err = parseInstructionWithValue(sourceLine, header, frame.Body, true)
}
default:
command, err = parseInstruction(sourceLine, line)
}
if err != nil {
message := err.Error()
if sourceError, ok := errors.AsType[*commandError](err); ok {
message = sourceError.Message
}
operation := ""
if fields := strings.Fields(line); len(fields) != 0 {
operation = fields[0]
}
failures = append(failures, &commandError{
Attempt: attempt,
Reason: reasonOf(err, reasonSyntax),
Command: commandIndex,
Line: sourceLine,
Operation: operation,
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":
return commandAttempt{recognized: true}
case "type", "type-", "type+":
attempt := commandAttempt{recognized: true}
if len(fields) > 1 {
attempt.target = recognizeTargetVariant(strings.TrimPrefix(line, fields[0]+" "))
}
return attempt
default:
return commandAttempt{}
}
}
func recognizeTargetVariant(operands string) targetVariant {
token, trailing := firstToken(operands)
if strings.Contains(token, "..") {
return targetVariantRange
}
if !rowPattern.MatchString(token) {
return targetVariantNone
}
trailing = strings.TrimSpace(trailing)
if !strings.HasPrefix(trailing, `"`) {
return targetVariantLine
}
_, rest, err := hpatchsyntax.DecodeQuoted(trailing)
if err != nil || strings.TrimSpace(rest) == "" {
return targetVariantLine
}
rest = strings.TrimSpace(rest)
if strings.HasPrefix(rest, `"`) || strings.HasPrefix(rest, "<<PATCH") {
return targetVariantTextSingle
}
return targetVariantTextMultiple
}
func attemptForInstruction(command instruction) commandAttempt {
return commandAttempt{recognized: true, target: command.target.variant()}
}
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" {
return instruction{line: sourceLine, operation: line}, nil
}
operation, _, ok := strings.Cut(line, " ")
if !ok {
return instruction{}, scriptError(sourceLine, "unknown or malformed command")
}
switch operation {
case "type", "type-", "type+":
return parseInstructionWithValue(sourceLine, line, "", false)
default:
return instruction{}, scriptError(sourceLine, "unknown or malformed command")
}
}
func parseInstructionWithValue(sourceLine int, line, heredocValue string, heredoc bool) (instruction, error) {
operation, operands, ok := strings.Cut(line, " ")
if !ok || (operation != "type" && operation != "type-" && operation != "type+") {
return instruction{}, scriptError(sourceLine, "heredoc is valid only for type, type-, or type+")
}
if operation == "type" && strings.HasPrefix(operands, `"`) {
if heredoc {
return instruction{}, scriptError(sourceLine, "targetless heredoc type must not have an inline operand")
}
value, trailing, err := hpatchsyntax.DecodeQuoted(operands)
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 initializer")
}
return instruction{line: sourceLine, operation: operation, text: value, valueStart: len(line) - len(operands)}, nil
}
if heredoc && operation == "type" && strings.TrimSpace(operands) == "" {
return instruction{line: sourceLine, operation: operation, text: heredocValue}, nil
}
target, trailing, err := parseTarget(sourceLine, operands, !heredoc)
if err != nil {
return instruction{}, err
}
value := heredocValue
valueStart := 0
if heredoc {
if strings.TrimSpace(trailing) != "" {
return instruction{}, scriptError(sourceLine, "trailing text before heredoc value")
}
} else {
trailing = strings.TrimLeft(trailing, " \t")
if trailing == "" {
return instruction{}, scriptError(sourceLine, operation+" requires a value")
}
valueStart = len(line) - len(trailing)
value, trailing, err = hpatchsyntax.DecodeQuoted(trailing)
if err != nil {
return instruction{}, scriptError(sourceLine, "invalid quoted string for "+operation+": "+err.Error())
}
if !onlyOperandWhitespace(trailing) {
return instruction{}, scriptError(sourceLine, "trailing text after "+operation+" value")
}
}
return instruction{line: sourceLine, operation: operation, target: target, text: value, valueStart: valueStart}, nil
}
// parseTarget parses a target prefix. When finalValueFollows is false, a quoted
// operand after ROW is the target literal. When true, a lone quoted operand is
// the mutation value and therefore leaves a line target.
func parseTarget(sourceLine int, operands string, finalValueFollows bool) (targetSpec, string, error) {
token, trailing := firstToken(operands)
if token == "" {
return targetSpec{}, "", scriptError(sourceLine, "target must not be empty")
}
if startText, endText, rangeTarget := strings.Cut(token, ".."); rangeTarget {
if strings.Contains(endText, "..") {
return targetSpec{}, "", scriptError(sourceLine, "range target must contain exactly two rows")
}
start, err := parseRowReference(sourceLine, startText)
if err != nil {
return targetSpec{}, "", err
}
end, err := parseRowReference(sourceLine, endText)
if err != nil {
return targetSpec{}, "", err
}
return targetSpec{kind: targetRange, start: start, end: end}, trailing, nil
}
row, err := parseRowReference(sourceLine, token)
if err != nil {
return targetSpec{}, "", err
}
trimmed := strings.TrimLeft(trailing, " \t")
if !strings.HasPrefix(trimmed, `"`) {
return targetSpec{kind: targetLine, start: row}, trailing, nil
}
literal, rest, err := hpatchsyntax.DecodeQuoted(trimmed)
if err != nil {
return targetSpec{}, "", scriptError(sourceLine, "invalid quoted target literal: "+err.Error())
}
if finalValueFollows && strings.TrimSpace(rest) == "" {
return targetSpec{kind: targetLine, start: row}, trimmed, nil
}
if literal == "" {
return targetSpec{}, "", scriptError(sourceLine, "target literal must not be empty")
}
if strings.ContainsAny(literal, "\r\n") {
return targetSpec{}, "", scriptError(sourceLine, "target literal must stay on one line")
}
for _, character := range literal {
if character < 0x20 && character != '\t' {
return targetSpec{}, "", scriptError(sourceLine, "target literal contains a forbidden control character")
}
}
count := 1
rest = strings.TrimLeft(rest, " \t")
if rest != "" && !strings.HasPrefix(rest, `"`) {
countText, afterCount := firstToken(rest)
if !positiveDecimalPattern.MatchString(countText) {
return targetSpec{}, "", scriptFailure(sourceLine, reasonInvalidCount, "invalid target count")
}
count, err = strconv.Atoi(countText)
if err != nil {
return targetSpec{}, "", scriptFailure(sourceLine, reasonInvalidCount, "target count is out of range")
}
rest = afterCount
}
return targetSpec{kind: targetText, start: row, literal: literal, count: count}, rest, nil
}
func firstToken(value string) (string, string) {
value = strings.TrimLeft(value, " \t")
for index := range len(value) {
if value[index] == ' ' || value[index] == '\t' || value[index] == '\r' || value[index] == '\n' {
return value[:index], value[index:]
}
}
return value, ""
}
func parseRowReference(sourceLine int, value string) (rowReference, error) {
match := rowPattern.FindStringSubmatch(value)
if match == nil {
return rowReference{}, scriptError(sourceLine, fmt.Sprintf("invalid row reference %q; expected LINE:HASH", value))
}
line, err := strconv.Atoi(match[1])
if err != nil {
return rowReference{}, scriptError(sourceLine, "row line is out of range")
}
return rowReference{line: line, hash: match[2]}, 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 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}
}