cloudflare/pint
Publicmirrored from https://github.com/cloudflare/pintAvailable
internal/discovery/symlinks.go
85lines · modecode
| 1 | package discovery |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "io/fs" |
| 6 | "os" |
| 7 | "path/filepath" |
| 8 | |
| 9 | "github.com/rs/zerolog/log" |
| 10 | ) |
| 11 | |
| 12 | type symlink struct { |
| 13 | from string |
| 14 | to string |
| 15 | } |
| 16 | |
| 17 | func findSymlinks() (slinks []symlink, err error) { |
| 18 | err = filepath.WalkDir(".", |
| 19 | func(path string, d fs.DirEntry, err error) error { |
| 20 | if err != nil { |
| 21 | return err |
| 22 | } |
| 23 | |
| 24 | if d.Type() != fs.ModeSymlink { |
| 25 | return nil |
| 26 | } |
| 27 | |
| 28 | dest, err := filepath.EvalSymlinks(path) |
| 29 | if err != nil { |
| 30 | return fmt.Errorf("%s is a symlink but target file cannot be evaluated: %w", path, err) |
| 31 | } |
| 32 | |
| 33 | info, err := os.Stat(dest) |
| 34 | if err != nil { |
| 35 | return fmt.Errorf("%s is a symlink but target file cannot be read: %w", path, err) |
| 36 | } |
| 37 | |
| 38 | if !info.IsDir() { |
| 39 | slinks = append(slinks, symlink{from: path, to: dest}) |
| 40 | } |
| 41 | |
| 42 | return nil |
| 43 | }) |
| 44 | |
| 45 | return slinks, err |
| 46 | } |
| 47 | |
| 48 | func addSymlinkedEntries(entries []Entry) ([]Entry, error) { |
| 49 | slinks, err := findSymlinks() |
| 50 | if err != nil { |
| 51 | return nil, err |
| 52 | } |
| 53 | |
| 54 | nentries := []Entry{} |
| 55 | for _, entry := range entries { |
| 56 | if entry.State == Removed { |
| 57 | continue |
| 58 | } |
| 59 | if entry.PathError != nil { |
| 60 | continue |
| 61 | } |
| 62 | if entry.Rule.Error.Err != nil { |
| 63 | continue |
| 64 | } |
| 65 | if entry.SourcePath != entry.ReportedPath { |
| 66 | continue |
| 67 | } |
| 68 | |
| 69 | for _, sl := range slinks { |
| 70 | if sl.to == entry.SourcePath { |
| 71 | log.Debug().Str("to", sl.to).Str("from", sl.from).Msg("Found a symlink") |
| 72 | nentries = append(nentries, Entry{ |
| 73 | ReportedPath: sl.to, |
| 74 | SourcePath: sl.from, |
| 75 | ModifiedLines: entry.ModifiedLines, |
| 76 | Rule: entry.Rule, |
| 77 | Owner: entry.Owner, |
| 78 | DisabledChecks: entry.DisabledChecks, |
| 79 | }) |
| 80 | } |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | return nentries, nil |
| 85 | } |
| 86 | |