-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathengine.go
More file actions
725 lines (646 loc) · 17.6 KB
/
engine.go
File metadata and controls
725 lines (646 loc) · 17.6 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
package engine
import (
"bufio"
"bytes"
"context"
"crypto/sha256"
"errors"
"fmt"
"io"
"os"
"path"
"path/filepath"
"sort"
"strings"
"github.com/satococoa/git-worktreeinclude/internal/exitcode"
"github.com/satococoa/git-worktreeinclude/internal/gitexec"
)
type Action struct {
Op string `json:"op"`
Path string `json:"path"`
Status string `json:"status"`
}
type Summary struct {
Matched int `json:"matched"`
Copied int `json:"copied,omitempty"`
CopyPlanned int `json:"copy_planned,omitempty"`
SkippedSame int `json:"skipped_same"`
SkippedMissingSrc int `json:"skipped_missing_src"`
Conflicts int `json:"conflicts"`
Errors int `json:"errors"`
}
type Result struct {
DryRun bool `json:"dry_run"`
From string `json:"from"`
To string `json:"to"`
IncludeFile string `json:"include_file"`
Summary Summary `json:"summary"`
Actions []Action `json:"actions"`
// Non-JSON metadata for human-readable CLI output.
ResolvedIncludePath string `json:"-"`
IncludeFound bool `json:"-"`
IncludeOrigin string `json:"-"`
IncludeMissingHint string `json:"-"`
TargetIncludePath string `json:"-"`
PatternCount int `json:"-"`
}
type ApplyOptions struct {
From string
Include string
DryRun bool
Force bool
}
type Engine struct {
git *gitexec.Runner
}
type CLIError struct {
Code int
Msg string
Err error
}
func (e *CLIError) Error() string {
if e == nil {
return ""
}
if e.Err == nil {
return e.Msg
}
if e.Msg == "" {
return e.Err.Error()
}
return e.Msg + ": " + e.Err.Error()
}
func (e *CLIError) Unwrap() error {
if e == nil {
return nil
}
return e.Err
}
func NewEngine() *Engine {
return &Engine{git: gitexec.NewRunner()}
}
type prepared struct {
targetRoot string
sourceRoot string
fromMode string
includeArg string
includePath string
includeFound bool
includeOrigin string
includeMissingHint string
targetIncludePath string
patternCount int
matched []string
}
const (
IncludeOriginSource = "source"
IncludeOriginExplicit = "explicit"
IncludeMissingHintSourceMissing = "source_missing"
IncludeMissingHintSourceMissingTargetExists = "source_missing_target_exists"
)
func (e *Engine) Apply(ctx context.Context, cwd string, opts ApplyOptions) (Result, int, error) {
prep, err := e.prepare(ctx, cwd, opts.From, opts.Include)
if err != nil {
return Result{}, errorCode(err), err
}
result, code := e.executePrepared(prep, opts.DryRun, opts.Force)
return result, code, nil
}
func (e *Engine) executePrepared(prep prepared, dryRun, force bool) (Result, int) {
result := Result{
DryRun: dryRun,
From: prep.sourceRoot,
To: prep.targetRoot,
IncludeFile: prep.includeArg,
ResolvedIncludePath: prep.includePath,
IncludeFound: prep.includeFound,
IncludeOrigin: prep.includeOrigin,
IncludeMissingHint: prep.includeMissingHint,
TargetIncludePath: prep.targetIncludePath,
PatternCount: prep.patternCount,
Summary: Summary{
Matched: len(prep.matched),
},
Actions: make([]Action, 0, len(prep.matched)),
}
if !prep.includeFound {
return result, exitcode.OK
}
executeCopies := !dryRun
for _, rel := range prep.matched {
srcPath, err := secureJoin(prep.sourceRoot, rel)
if err != nil {
result.Actions = append(result.Actions, Action{Op: "skip", Path: rel, Status: "error"})
result.Summary.Errors++
continue
}
dstPath, err := secureJoin(prep.targetRoot, rel)
if err != nil {
result.Actions = append(result.Actions, Action{Op: "skip", Path: rel, Status: "error"})
result.Summary.Errors++
continue
}
srcInfo, err := os.Lstat(srcPath)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
result.Actions = append(result.Actions, Action{Op: "skip", Path: rel, Status: "missing_src"})
result.Summary.SkippedMissingSrc++
continue
}
result.Actions = append(result.Actions, Action{Op: "skip", Path: rel, Status: "error"})
result.Summary.Errors++
continue
}
if srcInfo.Mode()&os.ModeSymlink != 0 {
result.Actions = append(result.Actions, Action{Op: "skip", Path: rel, Status: "symlink"})
result.Summary.SkippedMissingSrc++
continue
}
if !srcInfo.Mode().IsRegular() {
result.Actions = append(result.Actions, Action{Op: "skip", Path: rel, Status: "missing_src"})
result.Summary.SkippedMissingSrc++
continue
}
dstInfo, err := os.Lstat(dstPath)
if err != nil && !errors.Is(err, os.ErrNotExist) {
result.Actions = append(result.Actions, Action{Op: "skip", Path: rel, Status: "error"})
result.Summary.Errors++
continue
}
if errors.Is(err, os.ErrNotExist) {
status := "planned"
if executeCopies {
if err := copyFileAtomic(prep.targetRoot, srcPath, dstPath, srcInfo.Mode().Perm()); err != nil {
result.Actions = append(result.Actions, Action{Op: "copy", Path: rel, Status: "error"})
result.Summary.Errors++
continue
}
status = "done"
}
result.Actions = append(result.Actions, Action{Op: "copy", Path: rel, Status: status})
if dryRun {
result.Summary.CopyPlanned++
} else {
result.Summary.Copied++
}
continue
}
if dstInfo.IsDir() {
result.Actions = append(result.Actions, Action{Op: "conflict", Path: rel, Status: "diff"})
result.Summary.Conflicts++
continue
}
if dstInfo.Mode()&os.ModeSymlink == 0 {
same, err := filesSame(srcPath, dstPath)
if err != nil {
result.Actions = append(result.Actions, Action{Op: "skip", Path: rel, Status: "error"})
result.Summary.Errors++
continue
}
if same {
result.Actions = append(result.Actions, Action{Op: "skip", Path: rel, Status: "same"})
result.Summary.SkippedSame++
continue
}
}
if !force {
result.Actions = append(result.Actions, Action{Op: "conflict", Path: rel, Status: "diff"})
result.Summary.Conflicts++
continue
}
status := "planned"
if executeCopies {
if err := copyFileAtomic(prep.targetRoot, srcPath, dstPath, srcInfo.Mode().Perm()); err != nil {
result.Actions = append(result.Actions, Action{Op: "copy", Path: rel, Status: "error"})
result.Summary.Errors++
continue
}
status = "done"
}
result.Actions = append(result.Actions, Action{Op: "copy", Path: rel, Status: status})
if dryRun {
result.Summary.CopyPlanned++
} else {
result.Summary.Copied++
}
}
if result.Summary.Errors > 0 {
return result, exitcode.Internal
}
if result.Summary.Conflicts > 0 && !force {
return result, exitcode.Conflict
}
return result, exitcode.OK
}
func (e *Engine) prepare(ctx context.Context, cwd, fromOpt, includeOpt string) (prepared, error) {
targetRoot, err := e.repoRoot(ctx, cwd)
if err != nil {
return prepared{}, err
}
includeArg := includeOpt
if includeArg == "" {
includeArg = ".worktreeinclude"
}
fromMode := fromOpt
if fromMode == "" {
fromMode = "auto"
}
sourceRoot, err := e.resolveSourceRoot(ctx, targetRoot, cwd, fromMode)
if err != nil {
return prepared{}, err
}
if err := e.assertSameRepository(ctx, targetRoot, sourceRoot); err != nil {
return prepared{}, err
}
prep := prepared{
targetRoot: targetRoot,
sourceRoot: sourceRoot,
fromMode: fromMode,
includeArg: includeArg,
}
includePath := includeArg
if !filepath.IsAbs(includePath) {
includePath = filepath.Join(sourceRoot, includePath)
prep.includeOrigin = IncludeOriginSource
prep.targetIncludePath = filepath.Clean(filepath.Join(targetRoot, includeArg))
} else {
prep.includeOrigin = IncludeOriginExplicit
}
includePath = filepath.Clean(includePath)
if err := ensurePathWithinRoot(sourceRoot, includePath); err != nil {
return prepared{}, &CLIError{Code: exitcode.Env, Msg: "include path must be inside source repository root", Err: err}
}
prep.includePath = includePath
info, err := os.Stat(includePath)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
prep.includeMissingHint = IncludeMissingHintSourceMissing
if prep.includeOrigin == IncludeOriginSource && prep.targetIncludePath != "" {
if targetInfo, targetErr := os.Lstat(prep.targetIncludePath); targetErr == nil && !targetInfo.IsDir() {
prep.includeMissingHint = IncludeMissingHintSourceMissingTargetExists
}
}
return prep, nil
}
return prepared{}, &CLIError{Code: exitcode.Env, Msg: "failed to read include file", Err: err}
}
if info.IsDir() {
return prepared{}, &CLIError{Code: exitcode.Env, Msg: "include path is a directory", Err: nil}
}
patternCount, err := countPatterns(includePath)
if err != nil {
return prepared{}, &CLIError{Code: exitcode.Env, Msg: "failed to parse include file", Err: err}
}
prep.patternCount = patternCount
prep.includeFound = true
ignored, err := e.listIgnored(ctx, sourceRoot, "", true)
if err != nil {
return prepared{}, err
}
included, err := e.listIgnored(ctx, sourceRoot, includePath, false)
if err != nil {
return prepared{}, err
}
prep.matched = intersectPaths(ignored, included)
return prep, nil
}
func (e *Engine) repoRoot(ctx context.Context, cwd string) (string, error) {
root, err := e.git.RunText(ctx, cwd, "rev-parse", "--show-toplevel")
if err != nil {
return "", &CLIError{Code: exitcode.Env, Msg: "not inside a git repository", Err: err}
}
return root, nil
}
func (e *Engine) resolveSourceRoot(ctx context.Context, targetRoot, cwd, from string) (string, error) {
if from == "auto" {
out, err := e.git.Run(ctx, targetRoot, "worktree", "list", "--porcelain", "-z")
if err != nil {
return "", &CLIError{Code: exitcode.Env, Msg: "failed to list worktrees", Err: err}
}
worktrees, err := parseWorktreePorcelainZ(out)
if err != nil {
return "", &CLIError{Code: exitcode.Env, Msg: "failed to parse worktree list", Err: err}
}
for _, wt := range worktrees {
if wt.Bare {
continue
}
if wt.Path == "" {
continue
}
return filepath.Clean(wt.Path), nil
}
return "", &CLIError{Code: exitcode.Env, Msg: "no non-bare worktree found for --from auto", Err: nil}
}
sourcePath := from
if !filepath.IsAbs(sourcePath) {
sourcePath = filepath.Join(cwd, sourcePath)
}
sourcePath = filepath.Clean(sourcePath)
sourceRoot, err := e.repoRoot(ctx, sourcePath)
if err != nil {
return "", &CLIError{Code: exitcode.Env, Msg: "invalid --from path", Err: err}
}
return sourceRoot, nil
}
func (e *Engine) assertSameRepository(ctx context.Context, targetRoot, sourceRoot string) error {
targetCommon, err := e.git.RunText(ctx, targetRoot, "rev-parse", "--path-format=absolute", "--git-common-dir")
if err != nil {
return &CLIError{Code: exitcode.Env, Msg: "failed to resolve target git common dir", Err: err}
}
sourceCommon, err := e.git.RunText(ctx, sourceRoot, "rev-parse", "--path-format=absolute", "--git-common-dir")
if err != nil {
return &CLIError{Code: exitcode.Env, Msg: "failed to resolve source git common dir", Err: err}
}
if filepath.Clean(targetCommon) != filepath.Clean(sourceCommon) {
return &CLIError{Code: exitcode.Env, Msg: "source and target are not from the same repository", Err: nil}
}
return nil
}
func (e *Engine) listIgnored(ctx context.Context, repoRoot, includePath string, excludeStandard bool) ([]string, error) {
args := []string{"ls-files", "-o", "-i", "-z"}
if excludeStandard {
args = append(args, "--exclude-standard")
}
if includePath != "" {
args = append(args, "-X", includePath)
}
out, err := e.git.Run(ctx, repoRoot, args...)
if err != nil {
msg := "failed to list ignored files"
if includePath != "" {
msg = "failed to apply include patterns"
}
return nil, &CLIError{Code: exitcode.Env, Msg: msg, Err: err}
}
paths, err := parseNULPaths(out)
if err != nil {
return nil, &CLIError{Code: exitcode.Env, Msg: "failed to parse ignored file list", Err: err}
}
return paths, nil
}
func countPatterns(includePath string) (int, error) {
f, err := os.Open(includePath)
if err != nil {
return 0, err
}
defer func() {
_ = f.Close()
}()
s := bufio.NewScanner(f)
s.Buffer(make([]byte, 0, 64*1024), 1024*1024)
count := 0
for s.Scan() {
line := strings.TrimSpace(s.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
count++
}
if err := s.Err(); err != nil {
return 0, err
}
return count, nil
}
type worktreeEntry struct {
Path string
Bare bool
}
func parseWorktreePorcelainZ(out []byte) ([]worktreeEntry, error) {
parts := bytes.Split(out, []byte{0})
entries := make([]worktreeEntry, 0)
current := worktreeEntry{}
hasCurrent := false
for _, raw := range parts {
if len(raw) == 0 {
if hasCurrent {
entries = append(entries, current)
current = worktreeEntry{}
hasCurrent = false
}
continue
}
hasCurrent = true
line := string(raw)
switch {
case strings.HasPrefix(line, "worktree "):
current.Path = strings.TrimPrefix(line, "worktree ")
case line == "bare":
current.Bare = true
}
}
if hasCurrent {
entries = append(entries, current)
}
if len(entries) == 0 {
return nil, fmt.Errorf("worktree list is empty")
}
return entries, nil
}
func parseNULPaths(out []byte) ([]string, error) {
parts := bytes.Split(out, []byte{0})
seen := make(map[string]struct{}, len(parts))
paths := make([]string, 0, len(parts))
for _, raw := range parts {
if len(raw) == 0 {
continue
}
norm, err := normalizeRepoPath(string(raw))
if err != nil {
return nil, err
}
if _, ok := seen[norm]; ok {
continue
}
seen[norm] = struct{}{}
paths = append(paths, norm)
}
return paths, nil
}
func normalizeRepoPath(raw string) (string, error) {
if strings.ContainsRune(raw, '\x00') {
return "", fmt.Errorf("path contains NUL")
}
rel := raw
if os.PathSeparator == '\\' {
rel = strings.ReplaceAll(rel, "\\", "/")
}
rel = path.Clean(rel)
rel = strings.TrimPrefix(rel, "./")
if rel == "" || rel == "." {
return "", fmt.Errorf("path is empty")
}
if strings.HasPrefix(rel, "/") || rel == ".." || strings.HasPrefix(rel, "../") {
return "", fmt.Errorf("unsafe relative path: %s", raw)
}
return rel, nil
}
func secureJoin(root, rel string) (string, error) {
norm, err := normalizeRepoPath(rel)
if err != nil {
return "", err
}
absRoot, err := filepath.Abs(root)
if err != nil {
return "", err
}
joined := filepath.Join(absRoot, filepath.FromSlash(norm))
joined, err = filepath.Abs(joined)
if err != nil {
return "", err
}
if joined != absRoot && !strings.HasPrefix(joined, absRoot+string(os.PathSeparator)) {
return "", fmt.Errorf("path escapes repository root: %s", rel)
}
return joined, nil
}
func intersectPaths(a, b []string) []string {
set := make(map[string]struct{}, len(a))
for _, p := range a {
set[p] = struct{}{}
}
outSet := make(map[string]struct{})
for _, p := range b {
if _, ok := set[p]; ok {
outSet[p] = struct{}{}
}
}
out := make([]string, 0, len(outSet))
for p := range outSet {
out = append(out, p)
}
sort.Strings(out)
return out
}
func filesSame(srcPath, dstPath string) (bool, error) {
srcInfo, err := os.Stat(srcPath)
if err != nil {
return false, err
}
dstInfo, err := os.Stat(dstPath)
if err != nil {
return false, err
}
if !srcInfo.Mode().IsRegular() || !dstInfo.Mode().IsRegular() {
return false, nil
}
if srcInfo.Size() != dstInfo.Size() {
return false, nil
}
srcHash, err := hashFile(srcPath)
if err != nil {
return false, err
}
dstHash, err := hashFile(dstPath)
if err != nil {
return false, err
}
return bytes.Equal(srcHash[:], dstHash[:]), nil
}
func hashFile(filePath string) ([32]byte, error) {
var zero [32]byte
f, err := os.Open(filePath)
if err != nil {
return zero, err
}
defer func() {
_ = f.Close()
}()
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return zero, err
}
var sum [32]byte
copy(sum[:], h.Sum(nil))
return sum, nil
}
func copyFileAtomic(targetRoot, srcPath, dstPath string, perm os.FileMode) error {
parent := filepath.Dir(dstPath)
if err := os.MkdirAll(parent, 0o755); err != nil {
return err
}
if err := ensurePathWithinRoot(targetRoot, parent); err != nil {
return err
}
tmp, err := os.CreateTemp(parent, ".git-worktreeinclude-*")
if err != nil {
return err
}
tmpName := tmp.Name()
cleanup := func() {
_ = os.Remove(tmpName)
}
src, err := os.Open(srcPath)
if err != nil {
_ = tmp.Close()
cleanup()
return err
}
if _, err := io.Copy(tmp, src); err != nil {
_ = src.Close()
_ = tmp.Close()
cleanup()
return err
}
if err := src.Close(); err != nil {
_ = tmp.Close()
cleanup()
return err
}
if err := tmp.Chmod(perm); err != nil {
_ = tmp.Close()
cleanup()
return err
}
if err := tmp.Close(); err != nil {
cleanup()
return err
}
if err := os.Rename(tmpName, dstPath); err != nil {
cleanup()
return err
}
return nil
}
func ensurePathWithinRoot(root, candidate string) error {
rootAbs, err := filepath.Abs(root)
if err != nil {
return err
}
candAbs, err := filepath.Abs(candidate)
if err != nil {
return err
}
rootCanonical := rootAbs
if realRoot, err := filepath.EvalSymlinks(rootAbs); err == nil {
rootCanonical = realRoot
}
candCanonical := candAbs
if realCand, err := filepath.EvalSymlinks(candAbs); err == nil {
candCanonical = realCand
}
rel, err := filepath.Rel(rootCanonical, candCanonical)
if err != nil {
return err
}
if rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {
return fmt.Errorf("path escapes repository root")
}
if rel == "" || rel == "." {
return nil
}
if strings.HasPrefix(rel, "."+string(os.PathSeparator)) {
return nil
}
if filepath.IsAbs(rel) {
return fmt.Errorf("path escapes repository root")
}
return nil
}
func errorCode(err error) int {
var coded *CLIError
if errors.As(err, &coded) {
return coded.Code
}
return exitcode.Internal
}