Debian Codegraph @

tools/dir_walker.go

raw symbols SCIP
1 package tools
2
3 import (
4 "os"
5 "strings"
6
7 "github.com/git-lfs/git-lfs/v3/errors"
8 "github.com/git-lfs/git-lfs/v3/tr"
9 )
10
11 var (
12 errInvalidDir = errors.New(tr.Tr.Get("invalid directory"))
13 errNotDir = errors.New(tr.Tr.Get("not a directory"))
14 )
15
16 type DirWalker struct {
17 parentPath string
18 path string
19 config repositoryPermissionFetcher
20 }
21
22 // The parentPath parameter is assumed to be a valid path to a directory
23 // in the filesystem.
24 //
25 // The filePath parameter must be a relative file path as provided by Git,
26 // with only the "/" character as a separator and no empty or "." or ".."
27 // path segments. Absolute paths are not supported.
28 func NewDirWalkerForFile(parentPath string, filePath string, config repositoryPermissionFetcher) *DirWalker {
29 var path string
30 i := strings.LastIndexByte(filePath, '/')
31 if i >= 0 {
32 path = filePath[0:i]
33 }
34
35 return &DirWalker{
36 parentPath: parentPath,
37 path: path,
38 config: config,
39 }
40 }
41
42 // walk() checks each directory in a relative path, starting from the
43 // initial parent path, and optionally creates any missing directories
44 // in the path.
45 //
46 // If an existing file or something else other than a directory conflicts
47 // with a directory in the path, walk() returns an error.
48 //
49 // If the create option is false, walk() returns ErrNotExist when a
50 // directory is not found.
51 //
52 // Note that for performance reasons and to be consistent with Git's
53 // implementation, walk() does not guard against TOCTOU (time-of-check/
54 // time-of-use) races, as the methods of the os.Root type do.
55 func (w *DirWalker) walk(create bool) error {
56 currentPath := w.parentPath
57
58 n := len(w.path)
59 for n > 0 {
60 currentDir := w.path
61 nextDirIndex := n
62 i := strings.IndexByte(w.path, '/')
63 if i >= 0 {
64 currentDir = w.path[0:i]
65 nextDirIndex = i + 1
66 }
67
68 // These should never occur in Git paths.
69 if currentDir == "" || currentDir == "." || currentDir == ".." {
70 return errors.Join(errors.New(tr.Tr.Get("invalid directory %q in path: %q", currentDir, w.path)), errInvalidDir)
71 }
72
73 if currentPath == "" {
74 currentPath = currentDir
75 } else {
76 currentPath += "/" + currentDir
77 }
78
79 stat, err := os.Lstat(currentPath)
80 if err != nil {
81 if !os.IsNotExist(err) || !create {
82 return err
83 }
84
85 err = Mkdir(currentPath, w.config)
86 if err != nil {
87 return err
88 }
89 } else if !stat.Mode().IsDir() {
90 return errors.Join(errors.New(tr.Tr.Get("not a directory: %q", currentPath)), errNotDir)
91 }
92
93 w.parentPath = currentPath
94 w.path = w.path[nextDirIndex:]
95 n -= nextDirIndex
96 }
97
98 return nil
99 }
100
101 func (w *DirWalker) Walk() error {
102 return w.walk(false)
103 }
104
105 func (w *DirWalker) WalkAndCreate() error {
106 return w.walk(true)
107 }