Debian Codegraph @

hardlinks.go

raw symbols SCIP
1 package fsutil
2
3 import (
4 "context"
5 "io"
6 gofs "io/fs"
7 "os"
8 "syscall"
9
10 "github.com/pkg/errors"
11 "github.com/tonistiigi/fsutil/types"
12 )
13
14 // Hardlinks validates that all targets for links were part of the changes
15
16 type Hardlinks struct {
17 seenFiles map[string]struct{}
18 }
19
20 func (v *Hardlinks) HandleChange(kind ChangeKind, p string, fi os.FileInfo, err error) error {
21 if err != nil {
22 return err
23 }
24
25 if v.seenFiles == nil {
26 v.seenFiles = make(map[string]struct{})
27 }
28
29 if kind == ChangeKindDelete {
30 return nil
31 }
32
33 stat, ok := fi.Sys().(*types.Stat)
34 if !ok {
35 return errors.WithStack(&os.PathError{Path: p, Err: syscall.EBADMSG, Op: "change without stat info"})
36 }
37
38 if fi.IsDir() || fi.Mode()&os.ModeSymlink != 0 {
39 return nil
40 }
41
42 if len(stat.Linkname) > 0 {
43 if _, ok := v.seenFiles[stat.Linkname]; !ok {
44 return errors.Errorf("invalid link %s to unknown path: %q", p, stat.Linkname)
45 }
46 } else {
47 v.seenFiles[p] = struct{}{}
48 }
49
50 return nil
51 }
52
53 // WithHardlinkReset returns a FS that fixes hardlinks for FS that has been filtered
54 // so that original hardlink sources might be missing
55 func WithHardlinkReset(fs FS) FS {
56 return &hardlinkFilter{fs: fs}
57 }
58
59 type hardlinkFilter struct {
60 fs FS
61 }
62
63 var _ FS = &hardlinkFilter{}
64
65 func (r *hardlinkFilter) Walk(ctx context.Context, target string, fn gofs.WalkDirFunc) error {
66 seenFiles := make(map[string]string)
67 return r.fs.Walk(ctx, target, func(path string, entry gofs.DirEntry, err error) error {
68 if err != nil {
69 return err
70 }
71
72 fi, err := entry.Info()
73 if err != nil {
74 return err
75 }
76
77 if fi.IsDir() || fi.Mode()&os.ModeSymlink != 0 {
78 return fn(path, entry, nil)
79 }
80
81 stat, ok := fi.Sys().(*types.Stat)
82 if !ok {
83 return errors.WithStack(&os.PathError{Path: path, Err: syscall.EBADMSG, Op: "fileinfo without stat info"})
84 }
85
86 if stat.Linkname != "" {
87 if v, ok := seenFiles[stat.Linkname]; !ok {
88 seenFiles[stat.Linkname] = stat.Path
89 stat.Linkname = ""
90 entry = &dirEntryWithStat{DirEntry: entry, stat: stat}
91 } else {
92 if v != stat.Path {
93 stat.Linkname = v
94 entry = &dirEntryWithStat{DirEntry: entry, stat: stat}
95 }
96 }
97 }
98
99 seenFiles[path] = stat.Path
100
101 return fn(path, entry, nil)
102 })
103 }
104
105 func (r *hardlinkFilter) Open(p string) (io.ReadCloser, error) {
106 return r.fs.Open(p)
107 }
108
109 type dirEntryWithStat struct {
110 gofs.DirEntry
111 stat *types.Stat
112 }
113
114 func (d *dirEntryWithStat) Info() (gofs.FileInfo, error) {
115 return &StatInfo{d.stat}, nil
116 }