-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun.go
More file actions
729 lines (681 loc) · 25 KB
/
Copy pathrun.go
File metadata and controls
729 lines (681 loc) · 25 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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
package hpatch
import (
"context"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"unicode"
"github.com/yusing/hpatch/internal/hpatchsyntax"
"github.com/yusing/hpatch/internal/verifiedrow"
)
// Workspace is the filesystem authority for one hpatch operation. Root should
// be opened from its canonical absolute path; absolute script paths are matched
// against that name. CWD is root-relative and defaults to ".".
// Callers coordinate writers to overlapping files and lifecycle paths, from the
// reads used to author an edit through application and any rollback. Sharing a
// Root does not serialize operations or provide a filesystem snapshot.
type Workspace struct {
Root *os.Root
CWD string
}
// EditText applies target-bearing HPATCH mutations to an in-memory immutable
// baseline. It performs no filesystem access, language validation, formatting,
// indentation correction, or whitespace cleanup.
func EditText(ctx context.Context, baseline, script string) (string, error) {
if ctx == nil {
return "", fmt.Errorf("context is nil")
}
if err := ctx.Err(); err != nil {
return "", err
}
program, err := parse(script)
if err != nil {
return "", err
}
target := &editor{baseline: baseline}
for index, command := range program.instructions {
if err := ctx.Err(); err != nil {
return "", err
}
if command.target.kind == targetNone ||
(command.operation != "type" && command.operation != "add") {
return "", textEditCommandError(
command,
index+1,
reasonSyntax,
"text edit accepts only target-bearing type or add",
)
}
origin := editOrigin{
command: index + 1,
line: command.line,
operation: command.operation,
target: command.target.variant(),
targetSpec: command.target,
multilineValue: command.delimiter != "",
}
if err := target.applyMutation(command.operation, command.target, command.text, origin, command, ""); err != nil {
return "", textEditCommandError(command, index+1, reasonOf(err, reasonOther), err.Error())
}
}
return target.content(), nil
}
// TargetIdentity is the comparable semantic identity of one HPATCH target.
// Its representation is intentionally opaque so target syntax remains owned by
// the root parser.
type TargetIdentity struct {
target targetSpec
}
// ParseTargetIdentity parses the target prefix in source and returns the
// unconsumed source. mutationValueFollows disambiguates a quoted value after a
// row from an anchored literal target. Single-row ranges share a line target's
// identity, and omitted occurrence counts share an explicit count of one.
func ParseTargetIdentity(source string, mutationValueFollows bool) (TargetIdentity, string, error) {
target, trailing, err := parseTarget(1, source, mutationValueFollows)
if err != nil {
return TargetIdentity{}, "", err
}
if target.kind == targetEOF {
return TargetIdentity{}, "", fmt.Errorf("EOF is an add destination, not a target")
}
if target.kind == targetRange && target.start == target.end {
target.kind = targetLine
target.end = rowReference{}
}
return TargetIdentity{target: target}, trailing, nil
}
// textEditCommandError creates a command error for text editing failures.
func textEditCommandError(command instruction, index int, reason failureReason, message string) *commandError {
return &commandError{
Target: command.target.variant(),
Reason: reason,
Command: index,
Line: command.line,
Operation: command.operation,
Category: "edit",
Source: command.source,
Message: message,
}
}
// TextLineCount returns the number of targetable logical rows in text.
func TextLineCount(text string) int {
return verifiedrow.Count(text)
}
// TextReferences renders current LINE:HASH references for valid requested rows.
// Repeated and out-of-range row numbers are omitted.
func TextReferences(text string, rows ...int) string {
lines := logicalLines(text)
seen := make(map[int]struct{}, len(rows))
var output strings.Builder
for _, number := range rows {
if number < 1 || number > len(lines) {
continue
}
if _, exists := seen[number]; exists {
continue
}
seen[number] = struct{}{}
content := lineContent(text, lines[number-1])
writeHashLine(&output, number, content, previewTextLimit(content, repairPreviewLimit))
}
return output.String()
}
// TargetAlias maps a target from one successful script to the rendered region
// that replaced it. Hosts may retain aliases only after the translated patch
// was applied successfully.
type TargetAlias struct {
Path string
Before string
After string
}
// TargetAliasRelation describes an emitted row target's coordinate relation to
// a confirmed prior replacement target on the same path. It contains no row
// hashes or target text.
type TargetAliasRelation string
const (
TargetAliasRelationNone TargetAliasRelation = "none"
TargetAliasRelationExact TargetAliasRelation = "exact"
TargetAliasRelationContains TargetAliasRelation = "contains"
TargetAliasRelationContained TargetAliasRelation = "contained"
TargetAliasRelationOverlap TargetAliasRelation = "overlap"
)
// TargetAliasDiagnostic is transient alias-rewrite evidence for one row-target
// command. Rewritten is true only when the complete target, including hashes,
// followed a confirmed alias. Relation compares inclusive row coordinates only.
type TargetAliasDiagnostic struct {
Command int
Rewritten bool
Relation TargetAliasRelation
}
// RewriteTargetAliases updates exact line and range targets through successful
// prior replacements. It preserves values and framing and performs no filesystem access.
func RewriteTargetAliases(script string, aliases []TargetAlias) (string, error) {
rewritten, _, err := RewriteTargetAliasesWithCommands(script, aliases)
return rewritten, err
}
// RewriteTargetAliasesWithCommands also returns the 1-based command numbers
// whose targets changed. The command numbers let hosts attribute evaluator
// rejections without retaining target content.
func RewriteTargetAliasesWithCommands(script string, aliases []TargetAlias) (string, []int, error) {
rewritten, diagnostics, err := RewriteTargetAliasesWithDiagnostics(script, aliases)
if err != nil {
return "", nil, err
}
commands := make([]int, 0, len(diagnostics))
for _, diagnostic := range diagnostics {
if diagnostic.Rewritten {
commands = append(commands, diagnostic.Command)
}
}
return rewritten, commands, nil
}
// RewriteTargetAliasesWithDiagnostics also returns privacy-safe, transient
// coordinate relations for row-target commands. It does not retain paths,
// targets, hashes, values, or other script content.
func RewriteTargetAliasesWithDiagnostics(script string, aliases []TargetAlias) (string, []TargetAliasDiagnostic, error) {
if len(aliases) == 0 {
return script, nil, nil
}
program, err := parse(script)
if err != nil {
return "", nil, err
}
lines := hpatchsyntax.SplitPhysicalLines(script)
activePath := ""
var diagnostics []TargetAliasDiagnostic
for commandIndex, command := range program.instructions {
switch command.operation {
case "in", "new":
activePath = command.path
case "mv":
activePath = command.path
case "rm":
activePath = ""
case "type", "add":
if command.target.kind != targetLine && command.target.kind != targetRange {
continue
}
diagnostic := TargetAliasDiagnostic{
Command: commandIndex + 1,
Relation: targetAliasRelation(activePath, command.target, aliases),
}
before := renderRowTarget(command.target)
after := before
for _, alias := range aliases {
if alias.Path == activePath && alias.Before == after {
after = alias.After
}
}
if after == before {
diagnostics = append(diagnostics, diagnostic)
continue
}
diagnostic.Rewritten = true
lineIndex := command.line - 1
if lineIndex < 0 || lineIndex >= len(lines) {
return "", nil, fmt.Errorf("command source line %d is outside script", command.line)
}
header := lines[lineIndex].Text
operationEnd := len(command.operation)
if len(header) <= operationEnd || header[operationEnd] != ' ' {
return "", nil, fmt.Errorf("command source line %d has unexpected framing", command.line)
}
operand := operationEnd + 1
if !strings.HasPrefix(header[operand:], before) {
return "", nil, fmt.Errorf("command source line %d target changed during parsing", command.line)
}
boundary := operand + len(before)
if boundary < len(header) && header[boundary] != ' ' && header[boundary] != '\t' {
return "", nil, fmt.Errorf("command source line %d target boundary is invalid", command.line)
}
lines[lineIndex].Text = header[:operand] + after + header[boundary:]
diagnostics = append(diagnostics, diagnostic)
}
}
var rewritten strings.Builder
for _, line := range lines {
rewritten.WriteString(line.Text)
rewritten.WriteString(line.Terminator)
}
if _, err := parse(rewritten.String()); err != nil {
return "", nil, fmt.Errorf("rewriting target aliases: %w", err)
}
return rewritten.String(), diagnostics, nil
}
// targetAliasRelation determines the relation between a target and prior aliases.
func targetAliasRelation(path string, target targetSpec, aliases []TargetAlias) TargetAliasRelation {
relation := TargetAliasRelationNone
for _, alias := range aliases {
if alias.Path != path {
continue
}
prior, trailing, err := parseTarget(1, alias.Before, false)
if err != nil || strings.TrimSpace(trailing) != "" ||
(prior.kind != targetLine && prior.kind != targetRange) {
continue
}
candidate := rowSpanRelation(target, prior)
if targetAliasRelationRank(candidate) > targetAliasRelationRank(relation) {
relation = candidate
}
}
return relation
}
// rowSpanRelation computes the spatial relation between two row targets.
func rowSpanRelation(target, prior targetSpec) TargetAliasRelation {
targetStart, targetEnd := target.start.line, target.start.line
if target.kind == targetRange {
targetEnd = target.end.line
}
priorStart, priorEnd := prior.start.line, prior.start.line
if prior.kind == targetRange {
priorEnd = prior.end.line
}
if targetEnd < targetStart || priorEnd < priorStart || targetEnd < priorStart || priorEnd < targetStart {
return TargetAliasRelationNone
}
switch {
case targetStart == priorStart && targetEnd == priorEnd:
return TargetAliasRelationExact
case targetStart >= priorStart && targetEnd <= priorEnd:
return TargetAliasRelationContained
case targetStart <= priorStart && targetEnd >= priorEnd:
return TargetAliasRelationContains
default:
return TargetAliasRelationOverlap
}
}
// targetAliasRelationRank returns the priority rank of an alias relation.
func targetAliasRelationRank(relation TargetAliasRelation) int {
switch relation {
case TargetAliasRelationExact:
return 4
case TargetAliasRelationContained:
return 3
case TargetAliasRelationContains:
return 2
case TargetAliasRelationOverlap:
return 1
default:
return 0
}
}
// Apply evaluates the complete script before staging and applying its changes.
// Callers must coordinate writers as described by Workspace. Application uses
// ordered filesystem operations and rollback attempts, not a crash-atomic or
// reader-isolated transaction. An application error does not imply no writes.
func Apply(ctx context.Context, workspace Workspace, script string) error {
changes, filesystem, _, _, err := evaluateScript(ctx, workspace, script)
if err != nil {
return err
}
if len(changes) == 0 {
return nil
}
if err := ctx.Err(); err != nil {
return err
}
return commitChanges(changes, rootFileOperations{root: filesystem.root})
}
// HostRejection is the non-sensitive, structured identity of one rejected
// command. It intentionally excludes source text, diagnostics, and repair
// context so hosts can retain it as telemetry without retaining edit content.
type HostRejection struct {
Command int `json:"command"`
SourceLine int `json:"source_line"`
Operation string `json:"operation"`
Target string `json:"target,omitempty"`
TargetAliasRelation TargetAliasRelation `json:"target_alias_relation,omitempty"`
Reason string `json:"reason"`
Path string `json:"path,omitempty"`
GeneratedLine int `json:"generated_line,omitempty"`
GeneratedColumn int `json:"generated_column,omitempty"`
ValueLine int `json:"value_line,omitempty"`
}
// HostOutcome identifies the furthest lifecycle stage reached by one host request.
type HostOutcome struct {
Stage string `json:"stage"`
Status string `json:"status"`
}
// HostChange summarizes the requested workspace effect.
type HostChange struct {
Files int `json:"files"`
AlreadySatisfied bool `json:"already_satisfied"`
Applied bool `json:"applied"`
}
// HostFailure is actionable host-facing failure context. Unlike HostRejection,
// it may contain bounded repair text and is not suitable for durable telemetry.
type HostFailure struct {
Command int `json:"command,omitempty"`
Path string `json:"path,omitempty"`
Reason string `json:"reason"`
Scope string `json:"scope"`
Suggestion string `json:"suggestion,omitempty"`
}
// HostPatchSummary describes a translated patch without duplicating its content.
type HostPatchSummary struct {
Files int `json:"files"`
Bytes int `json:"bytes"`
}
// HostTranslation contains the complete result needed by an in-process host.
// Diagnostic contains a rejection diagnostic or non-fatal hook warnings.
type HostTranslation struct {
Patch []byte
Report string
TargetAliases []TargetAlias
Diagnostic string
Outcome HostOutcome
Change HostChange
Attempt AttemptMetadata
Failures []HostFailure
PatchSummary HostPatchSummary
Rejections []HostRejection
}
// TranslateForHostAt evaluates a host script relative to directory without
// imposing filesystem confinement. The host executor remains responsible for
// authorizing and applying the translated patch. The caller coordinates writers
// from the reads used to author the edit through translation and host application;
// the returned patch and report do not reserve the evaluated filesystem state.
func TranslateForHostAt(ctx context.Context, directory, script, dataDirectory string) (HostTranslation, error) {
changes, _, report, aliases, err := evaluateScriptAt(ctx, directory, script)
result := hostTranslationResult(changes, report, aliases, err == nil)
failureStage := ""
if err != nil {
failureStage = "evaluated"
} else if err = translateHostResult(ctx, changes, &result); err != nil {
failureStage = "translated"
}
return finishHostChange(ctx, dataDirectory, script, result, failureStage, err, false)
}
// ApplyForHost applies a script with the same caller-coordination and commit
// guarantees as Apply, while returning host diagnostics. A late cancellation
// can be returned after changes have been applied.
func ApplyForHost(ctx context.Context, workspace Workspace, script, dataDirectory string) (HostTranslation, error) {
changes, filesystem, report, aliases, err := evaluateScript(ctx, workspace, script)
result := hostTranslationResult(changes, report, aliases, err == nil)
failureStage := ""
if err != nil {
failureStage = "evaluated"
} else if err = ctx.Err(); err == nil && len(changes) != 0 {
if err = commitChanges(changes, rootFileOperations{root: filesystem.root}); err != nil {
err = fmt.Errorf("changing %s: %w", describePaths(changes), err)
failureStage = "applied"
}
}
return finishHostChange(ctx, dataDirectory, script, result, failureStage, err, true)
}
// ApplyForHostRoot evaluates and applies a script within root. It is intended
// for hosts that own a confined private filesystem and coordinate its writers
// under the same contract as ApplyForHost.
func ApplyForHostRoot(ctx context.Context, root *os.Root, script, dataDirectory string) (HostTranslation, error) {
return ApplyForHost(ctx, Workspace{Root: root}, script, dataDirectory)
}
// finishHostChange completes a host translation with outcome metadata and hooks.
func finishHostChange(ctx context.Context, dataDirectory, script string, result HostTranslation, failureStage string, err error, applied bool) (HostTranslation, error) {
result.Attempt, _ = attemptMetadataFromContext(ctx)
if err != nil {
result.Rejections = hostRejectionsOf(err)
result.Failures = hostFailuresOf(err, failureStage)
status := "failed"
if failureStage == "evaluated" {
status = "rejected"
}
result.Outcome = HostOutcome{Stage: failureStage, Status: status}
if ctx.Err() == nil {
result.Diagnostic = evaluationDiagnostic(ctx, err, dataDirectory)
if contextErr := ctx.Err(); contextErr != nil {
result.Diagnostic = ""
return result, contextErr
}
for _, hookErr := range runOutcomeHooks(ctx, dataDirectory, failureStage, status, script, nil, errorHooksTimeout) {
warning := warningDiagnostic(hookErr.Error())
if !strings.Contains(result.Diagnostic, warning) {
result.Diagnostic += warning
}
}
}
if contextErr := ctx.Err(); contextErr != nil {
result.Diagnostic = ""
return result, contextErr
}
return result, err
}
stage, status := "translated", "succeeded"
if result.Change.AlreadySatisfied {
stage, status = "evaluated", "already-satisfied"
} else if applied {
stage, status = "applied", "succeeded"
result.Change.Applied = true
}
result.Outcome = HostOutcome{Stage: stage, Status: status}
for _, hookErr := range runOutcomeHooks(ctx, dataDirectory, stage, status, script, result.Patch, errorHooksTimeout) {
result.Diagnostic += warningDiagnostic(hookErr.Error())
}
if err := ctx.Err(); err != nil {
result.Diagnostic = ""
return result, err
}
return result, nil
}
// hostTranslationResult initializes a host translation result from evaluation output.
func hostTranslationResult(changes []change, report string, aliases []TargetAlias, evaluated bool) HostTranslation {
files := len(changes)
return HostTranslation{
Report: report,
TargetAliases: slices.Clone(aliases),
Change: HostChange{Files: files, AlreadySatisfied: evaluated && files == 0},
}
}
// translateHostResult translates changes to a patch and updates the result.
func translateHostResult(ctx context.Context, changes []change, result *HostTranslation) error {
if err := ctx.Err(); err != nil {
return err
}
patch, err := translate(changes)
if err != nil {
return err
}
result.Patch = []byte(patch)
result.PatchSummary = HostPatchSummary{Files: len(changes), Bytes: len(patch)}
return nil
}
type filesystemWorkspace struct {
root *os.Root
cwd string
}
// evaluateScript evaluates a script in the given workspace.
func evaluateScript(ctx context.Context, workspace Workspace, script string) ([]change, filesystemWorkspace, string, []TargetAlias, error) {
filesystem, err := validateWorkspace(ctx, workspace)
if err != nil {
return nil, filesystemWorkspace{}, "", nil, err
}
return evaluateScriptInFilesystem(ctx, filesystem, script)
}
// evaluateScriptAt evaluates a script in the given directory.
func evaluateScriptAt(ctx context.Context, directory, script string) ([]change, filesystemWorkspace, string, []TargetAlias, error) {
filesystem, err := validateHostDirectory(ctx, directory)
if err != nil {
return nil, filesystemWorkspace{}, "", nil, err
}
return evaluateScriptInFilesystem(ctx, filesystem, script)
}
// evaluateScriptInFilesystem evaluates a script against a filesystem workspace.
func evaluateScriptInFilesystem(ctx context.Context, filesystem filesystemWorkspace, script string) ([]change, filesystemWorkspace, string, []TargetAlias, error) {
program, err := parse(script)
if err != nil {
return nil, filesystemWorkspace{}, "", nil, err
}
load := func(path string) (loadedFile, error) {
return filesystem.readFile(ctx, path)
}
exists := func(path string) (fs.FileMode, bool, error) {
if err := ctx.Err(); err != nil {
return 0, false, err
}
info, err := filesystem.stat(path)
if err == nil {
return info.Mode(), true, nil
}
if errors.Is(err, fs.ErrNotExist) {
return 0, false, nil
}
return 0, false, err
}
changes, report, aliases, err := program.evaluate(ctx, filesystem.resolvePath, load, exists)
if err != nil {
return nil, filesystemWorkspace{}, "", nil, err
}
return changes, filesystem, report, aliases, nil
}
// validateWorkspace validates and normalizes a workspace configuration.
func validateWorkspace(ctx context.Context, workspace Workspace) (filesystemWorkspace, error) {
if ctx == nil {
return filesystemWorkspace{}, fmt.Errorf("context is nil")
}
if err := ctx.Err(); err != nil {
return filesystemWorkspace{}, err
}
if workspace.Root == nil {
return filesystemWorkspace{}, fmt.Errorf("workspace root is nil")
}
cwd := workspace.CWD
if cwd == "" {
cwd = "."
}
cwd = filepath.Clean(cwd)
if !filepath.IsLocal(cwd) {
return filesystemWorkspace{}, fmt.Errorf("workspace cwd %q is not root-relative", workspace.CWD)
}
info, err := workspace.Root.Stat(cwd)
if err != nil {
return filesystemWorkspace{}, fmt.Errorf("validating workspace cwd %q: %w", cwd, err)
}
if !info.IsDir() {
return filesystemWorkspace{}, fmt.Errorf("workspace cwd %q is not a directory", cwd)
}
return filesystemWorkspace{root: workspace.Root, cwd: cwd}, nil
}
// validateHostDirectory validates and normalizes a host directory path.
func validateHostDirectory(ctx context.Context, directory string) (filesystemWorkspace, error) {
if ctx == nil {
return filesystemWorkspace{}, fmt.Errorf("context is nil")
}
if err := ctx.Err(); err != nil {
return filesystemWorkspace{}, err
}
if directory == "" {
return filesystemWorkspace{}, nil
}
directory, err := filepath.Abs(directory)
if err != nil {
return filesystemWorkspace{}, fmt.Errorf("resolving host directory: %w", err)
}
directory = filepath.Clean(directory)
info, err := os.Stat(directory)
if err != nil {
return filesystemWorkspace{}, fmt.Errorf("validating host directory %q: %w", directory, err)
}
if !info.IsDir() {
return filesystemWorkspace{}, fmt.Errorf("host directory %q is not a directory", directory)
}
return filesystemWorkspace{cwd: directory}, nil
}
// resolvePath resolves a script path against the workspace root.
func (w filesystemWorkspace) resolvePath(path string) (string, error) {
if w.root == nil {
path = filepath.Clean(path)
if w.cwd == "" && !filepath.IsAbs(path) {
return "", fmt.Errorf("relative path requires a host directory")
}
return path, nil
}
if filepath.IsAbs(path) {
if !filepath.IsAbs(w.root.Name()) {
return "", fmt.Errorf("absolute path requires an absolute workspace root")
}
relative, err := filepath.Rel(w.root.Name(), filepath.Clean(path))
if err != nil {
return "", fmt.Errorf("resolving path against workspace root: %w", err)
}
path = relative
} else {
path = filepath.Join(w.cwd, path)
}
path = filepath.Clean(path)
if !filepath.IsLocal(path) {
return "", fmt.Errorf("path resolves outside workspace root")
}
return path, nil
}
// hostPath converts a resolved path to a host filesystem path.
func (w filesystemWorkspace) hostPath(path string) string {
if filepath.IsAbs(path) {
return path
}
return filepath.Join(w.cwd, path)
}
// stat returns file information for the given path.
func (w filesystemWorkspace) stat(path string) (fs.FileInfo, error) {
if w.root == nil {
return os.Stat(w.hostPath(path))
}
return w.root.Stat(path)
}
// open opens the file at the given path.
func (w filesystemWorkspace) open(path string) (*os.File, error) {
if w.root == nil {
return os.Open(w.hostPath(path))
}
return w.root.Open(path)
}
// sanitizeDiagnostic sanitizes a diagnostic message for safe display.
func sanitizeDiagnostic(message string) string {
var sanitized strings.Builder
for _, character := range message {
switch {
case character == '\n':
sanitized.WriteString("; ")
case unicode.IsControl(character):
escaped := strconv.QuoteRune(character)
sanitized.WriteString(escaped[1 : len(escaped)-1])
default:
sanitized.WriteRune(character)
}
}
return sanitized.String()
}
// failureDiagnostic formats a failure message as a diagnostic.
func failureDiagnostic(message string) string {
return fmt.Sprintf("hpatch: %s\n", sanitizeDiagnostic(message))
}
// evaluationDiagnostic formats an evaluation error as a diagnostic with repair context.
func evaluationDiagnostic(ctx context.Context, err error, dataDirectory string) string {
commands := commandsOf(err)
if len(commands) == 0 {
return failureDiagnostic(err.Error())
}
var output strings.Builder
var diagnostic strings.Builder
for _, command := range commands {
diagnostic.WriteString(sanitizeDiagnostic(command.Error()))
diagnostic.WriteByte('\n')
diagnostic.WriteString(command.Repair)
}
output.WriteString(diagnostic.String())
if _, routed := attemptMetadataFromContext(ctx); !routed {
for _, hookErr := range runCommandErrorHooks(ctx, dataDirectory, commands, diagnostic.String(), errorHooksTimeout) {
output.WriteString(warningDiagnostic(hookErr.Error()))
}
}
return output.String()
}
// warningDiagnostic formats a warning message as a diagnostic.
func warningDiagnostic(message string) string {
message = sanitizeDiagnostic(message)
return fmt.Sprintf("hpatch: warning: %s\n", message)
}