]> Cypherpunks.ru repositories - gostls13.git/blob - src/path/filepath/path.go
io/fs, path/filepath, cmd/gofmt: replace statDirEntry with fs.FileInfoToDirEntry
[gostls13.git] / src / path / filepath / path.go
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package filepath implements utility routines for manipulating filename paths
6 // in a way compatible with the target operating system-defined file paths.
7 //
8 // The filepath package uses either forward slashes or backslashes,
9 // depending on the operating system. To process paths such as URLs
10 // that always use forward slashes regardless of the operating
11 // system, see the [path] package.
12 package filepath
13
14 import (
15         "errors"
16         "io/fs"
17         "os"
18         "runtime"
19         "slices"
20         "sort"
21         "strings"
22 )
23
24 // A lazybuf is a lazily constructed path buffer.
25 // It supports append, reading previously appended bytes,
26 // and retrieving the final string. It does not allocate a buffer
27 // to hold the output until that output diverges from s.
28 type lazybuf struct {
29         path       string
30         buf        []byte
31         w          int
32         volAndPath string
33         volLen     int
34 }
35
36 func (b *lazybuf) index(i int) byte {
37         if b.buf != nil {
38                 return b.buf[i]
39         }
40         return b.path[i]
41 }
42
43 func (b *lazybuf) append(c byte) {
44         if b.buf == nil {
45                 if b.w < len(b.path) && b.path[b.w] == c {
46                         b.w++
47                         return
48                 }
49                 b.buf = make([]byte, len(b.path))
50                 copy(b.buf, b.path[:b.w])
51         }
52         b.buf[b.w] = c
53         b.w++
54 }
55
56 func (b *lazybuf) prepend(prefix ...byte) {
57         b.buf = slices.Insert(b.buf, 0, prefix...)
58         b.w += len(prefix)
59 }
60
61 func (b *lazybuf) string() string {
62         if b.buf == nil {
63                 return b.volAndPath[:b.volLen+b.w]
64         }
65         return b.volAndPath[:b.volLen] + string(b.buf[:b.w])
66 }
67
68 const (
69         Separator     = os.PathSeparator
70         ListSeparator = os.PathListSeparator
71 )
72
73 // Clean returns the shortest path name equivalent to path
74 // by purely lexical processing. It applies the following rules
75 // iteratively until no further processing can be done:
76 //
77 //  1. Replace multiple Separator elements with a single one.
78 //  2. Eliminate each . path name element (the current directory).
79 //  3. Eliminate each inner .. path name element (the parent directory)
80 //     along with the non-.. element that precedes it.
81 //  4. Eliminate .. elements that begin a rooted path:
82 //     that is, replace "/.." by "/" at the beginning of a path,
83 //     assuming Separator is '/'.
84 //
85 // The returned path ends in a slash only if it represents a root directory,
86 // such as "/" on Unix or `C:\` on Windows.
87 //
88 // Finally, any occurrences of slash are replaced by Separator.
89 //
90 // If the result of this process is an empty string, Clean
91 // returns the string ".".
92 //
93 // On Windows, Clean does not modify the volume name other than to replace
94 // occurrences of "/" with `\`.
95 // For example, Clean("//host/share/../x") returns `\\host\share\x`.
96 //
97 // See also Rob Pike, “Lexical File Names in Plan 9 or
98 // Getting Dot-Dot Right,”
99 // https://9p.io/sys/doc/lexnames.html
100 func Clean(path string) string {
101         originalPath := path
102         volLen := volumeNameLen(path)
103         path = path[volLen:]
104         if path == "" {
105                 if volLen > 1 && os.IsPathSeparator(originalPath[0]) && os.IsPathSeparator(originalPath[1]) {
106                         // should be UNC
107                         return FromSlash(originalPath)
108                 }
109                 return originalPath + "."
110         }
111         rooted := os.IsPathSeparator(path[0])
112
113         // Invariants:
114         //      reading from path; r is index of next byte to process.
115         //      writing to buf; w is index of next byte to write.
116         //      dotdot is index in buf where .. must stop, either because
117         //              it is the leading slash or it is a leading ../../.. prefix.
118         n := len(path)
119         out := lazybuf{path: path, volAndPath: originalPath, volLen: volLen}
120         r, dotdot := 0, 0
121         if rooted {
122                 out.append(Separator)
123                 r, dotdot = 1, 1
124         }
125
126         for r < n {
127                 switch {
128                 case os.IsPathSeparator(path[r]):
129                         // empty path element
130                         r++
131                 case path[r] == '.' && (r+1 == n || os.IsPathSeparator(path[r+1])):
132                         // . element
133                         r++
134                 case path[r] == '.' && path[r+1] == '.' && (r+2 == n || os.IsPathSeparator(path[r+2])):
135                         // .. element: remove to last separator
136                         r += 2
137                         switch {
138                         case out.w > dotdot:
139                                 // can backtrack
140                                 out.w--
141                                 for out.w > dotdot && !os.IsPathSeparator(out.index(out.w)) {
142                                         out.w--
143                                 }
144                         case !rooted:
145                                 // cannot backtrack, but not rooted, so append .. element.
146                                 if out.w > 0 {
147                                         out.append(Separator)
148                                 }
149                                 out.append('.')
150                                 out.append('.')
151                                 dotdot = out.w
152                         }
153                 default:
154                         // real path element.
155                         // add slash if needed
156                         if rooted && out.w != 1 || !rooted && out.w != 0 {
157                                 out.append(Separator)
158                         }
159                         // copy element
160                         for ; r < n && !os.IsPathSeparator(path[r]); r++ {
161                                 out.append(path[r])
162                         }
163                 }
164         }
165
166         // Turn empty string into "."
167         if out.w == 0 {
168                 out.append('.')
169         }
170
171         if runtime.GOOS == "windows" && out.volLen == 0 && out.buf != nil {
172                 // If a ':' appears in the path element at the start of a Windows path,
173                 // insert a .\ at the beginning to avoid converting relative paths
174                 // like a/../c: into c:.
175                 for _, c := range out.buf {
176                         if os.IsPathSeparator(c) {
177                                 break
178                         }
179                         if c == ':' {
180                                 out.prepend('.', Separator)
181                                 break
182                         }
183                 }
184         }
185
186         return FromSlash(out.string())
187 }
188
189 // IsLocal reports whether path, using lexical analysis only, has all of these properties:
190 //
191 //   - is within the subtree rooted at the directory in which path is evaluated
192 //   - is not an absolute path
193 //   - is not empty
194 //   - on Windows, is not a reserved name such as "NUL"
195 //
196 // If IsLocal(path) returns true, then
197 // Join(base, path) will always produce a path contained within base and
198 // Clean(path) will always produce an unrooted path with no ".." path elements.
199 //
200 // IsLocal is a purely lexical operation.
201 // In particular, it does not account for the effect of any symbolic links
202 // that may exist in the filesystem.
203 func IsLocal(path string) bool {
204         return isLocal(path)
205 }
206
207 func unixIsLocal(path string) bool {
208         if IsAbs(path) || path == "" {
209                 return false
210         }
211         hasDots := false
212         for p := path; p != ""; {
213                 var part string
214                 part, p, _ = strings.Cut(p, "/")
215                 if part == "." || part == ".." {
216                         hasDots = true
217                         break
218                 }
219         }
220         if hasDots {
221                 path = Clean(path)
222         }
223         if path == ".." || strings.HasPrefix(path, "../") {
224                 return false
225         }
226         return true
227 }
228
229 // ToSlash returns the result of replacing each separator character
230 // in path with a slash ('/') character. Multiple separators are
231 // replaced by multiple slashes.
232 func ToSlash(path string) string {
233         if Separator == '/' {
234                 return path
235         }
236         return strings.ReplaceAll(path, string(Separator), "/")
237 }
238
239 // FromSlash returns the result of replacing each slash ('/') character
240 // in path with a separator character. Multiple slashes are replaced
241 // by multiple separators.
242 func FromSlash(path string) string {
243         if Separator == '/' {
244                 return path
245         }
246         return strings.ReplaceAll(path, "/", string(Separator))
247 }
248
249 // SplitList splits a list of paths joined by the OS-specific ListSeparator,
250 // usually found in PATH or GOPATH environment variables.
251 // Unlike strings.Split, SplitList returns an empty slice when passed an empty
252 // string.
253 func SplitList(path string) []string {
254         return splitList(path)
255 }
256
257 // Split splits path immediately following the final Separator,
258 // separating it into a directory and file name component.
259 // If there is no Separator in path, Split returns an empty dir
260 // and file set to path.
261 // The returned values have the property that path = dir+file.
262 func Split(path string) (dir, file string) {
263         vol := VolumeName(path)
264         i := len(path) - 1
265         for i >= len(vol) && !os.IsPathSeparator(path[i]) {
266                 i--
267         }
268         return path[:i+1], path[i+1:]
269 }
270
271 // Join joins any number of path elements into a single path,
272 // separating them with an OS specific Separator. Empty elements
273 // are ignored. The result is Cleaned. However, if the argument
274 // list is empty or all its elements are empty, Join returns
275 // an empty string.
276 // On Windows, the result will only be a UNC path if the first
277 // non-empty element is a UNC path.
278 func Join(elem ...string) string {
279         return join(elem)
280 }
281
282 // Ext returns the file name extension used by path.
283 // The extension is the suffix beginning at the final dot
284 // in the final element of path; it is empty if there is
285 // no dot.
286 func Ext(path string) string {
287         for i := len(path) - 1; i >= 0 && !os.IsPathSeparator(path[i]); i-- {
288                 if path[i] == '.' {
289                         return path[i:]
290                 }
291         }
292         return ""
293 }
294
295 // EvalSymlinks returns the path name after the evaluation of any symbolic
296 // links.
297 // If path is relative the result will be relative to the current directory,
298 // unless one of the components is an absolute symbolic link.
299 // EvalSymlinks calls Clean on the result.
300 func EvalSymlinks(path string) (string, error) {
301         return evalSymlinks(path)
302 }
303
304 // Abs returns an absolute representation of path.
305 // If the path is not absolute it will be joined with the current
306 // working directory to turn it into an absolute path. The absolute
307 // path name for a given file is not guaranteed to be unique.
308 // Abs calls Clean on the result.
309 func Abs(path string) (string, error) {
310         return abs(path)
311 }
312
313 func unixAbs(path string) (string, error) {
314         if IsAbs(path) {
315                 return Clean(path), nil
316         }
317         wd, err := os.Getwd()
318         if err != nil {
319                 return "", err
320         }
321         return Join(wd, path), nil
322 }
323
324 // Rel returns a relative path that is lexically equivalent to targpath when
325 // joined to basepath with an intervening separator. That is,
326 // Join(basepath, Rel(basepath, targpath)) is equivalent to targpath itself.
327 // On success, the returned path will always be relative to basepath,
328 // even if basepath and targpath share no elements.
329 // An error is returned if targpath can't be made relative to basepath or if
330 // knowing the current working directory would be necessary to compute it.
331 // Rel calls Clean on the result.
332 func Rel(basepath, targpath string) (string, error) {
333         baseVol := VolumeName(basepath)
334         targVol := VolumeName(targpath)
335         base := Clean(basepath)
336         targ := Clean(targpath)
337         if sameWord(targ, base) {
338                 return ".", nil
339         }
340         base = base[len(baseVol):]
341         targ = targ[len(targVol):]
342         if base == "." {
343                 base = ""
344         } else if base == "" && volumeNameLen(baseVol) > 2 /* isUNC */ {
345                 // Treat any targetpath matching `\\host\share` basepath as absolute path.
346                 base = string(Separator)
347         }
348
349         // Can't use IsAbs - `\a` and `a` are both relative in Windows.
350         baseSlashed := len(base) > 0 && base[0] == Separator
351         targSlashed := len(targ) > 0 && targ[0] == Separator
352         if baseSlashed != targSlashed || !sameWord(baseVol, targVol) {
353                 return "", errors.New("Rel: can't make " + targpath + " relative to " + basepath)
354         }
355         // Position base[b0:bi] and targ[t0:ti] at the first differing elements.
356         bl := len(base)
357         tl := len(targ)
358         var b0, bi, t0, ti int
359         for {
360                 for bi < bl && base[bi] != Separator {
361                         bi++
362                 }
363                 for ti < tl && targ[ti] != Separator {
364                         ti++
365                 }
366                 if !sameWord(targ[t0:ti], base[b0:bi]) {
367                         break
368                 }
369                 if bi < bl {
370                         bi++
371                 }
372                 if ti < tl {
373                         ti++
374                 }
375                 b0 = bi
376                 t0 = ti
377         }
378         if base[b0:bi] == ".." {
379                 return "", errors.New("Rel: can't make " + targpath + " relative to " + basepath)
380         }
381         if b0 != bl {
382                 // Base elements left. Must go up before going down.
383                 seps := strings.Count(base[b0:bl], string(Separator))
384                 size := 2 + seps*3
385                 if tl != t0 {
386                         size += 1 + tl - t0
387                 }
388                 buf := make([]byte, size)
389                 n := copy(buf, "..")
390                 for i := 0; i < seps; i++ {
391                         buf[n] = Separator
392                         copy(buf[n+1:], "..")
393                         n += 3
394                 }
395                 if t0 != tl {
396                         buf[n] = Separator
397                         copy(buf[n+1:], targ[t0:])
398                 }
399                 return string(buf), nil
400         }
401         return targ[t0:], nil
402 }
403
404 // SkipDir is used as a return value from WalkFuncs to indicate that
405 // the directory named in the call is to be skipped. It is not returned
406 // as an error by any function.
407 var SkipDir error = fs.SkipDir
408
409 // SkipAll is used as a return value from WalkFuncs to indicate that
410 // all remaining files and directories are to be skipped. It is not returned
411 // as an error by any function.
412 var SkipAll error = fs.SkipAll
413
414 // WalkFunc is the type of the function called by Walk to visit each
415 // file or directory.
416 //
417 // The path argument contains the argument to Walk as a prefix.
418 // That is, if Walk is called with root argument "dir" and finds a file
419 // named "a" in that directory, the walk function will be called with
420 // argument "dir/a".
421 //
422 // The directory and file are joined with Join, which may clean the
423 // directory name: if Walk is called with the root argument "x/../dir"
424 // and finds a file named "a" in that directory, the walk function will
425 // be called with argument "dir/a", not "x/../dir/a".
426 //
427 // The info argument is the fs.FileInfo for the named path.
428 //
429 // The error result returned by the function controls how Walk continues.
430 // If the function returns the special value SkipDir, Walk skips the
431 // current directory (path if info.IsDir() is true, otherwise path's
432 // parent directory). If the function returns the special value SkipAll,
433 // Walk skips all remaining files and directories. Otherwise, if the function
434 // returns a non-nil error, Walk stops entirely and returns that error.
435 //
436 // The err argument reports an error related to path, signaling that Walk
437 // will not walk into that directory. The function can decide how to
438 // handle that error; as described earlier, returning the error will
439 // cause Walk to stop walking the entire tree.
440 //
441 // Walk calls the function with a non-nil err argument in two cases.
442 //
443 // First, if an os.Lstat on the root directory or any directory or file
444 // in the tree fails, Walk calls the function with path set to that
445 // directory or file's path, info set to nil, and err set to the error
446 // from os.Lstat.
447 //
448 // Second, if a directory's Readdirnames method fails, Walk calls the
449 // function with path set to the directory's path, info, set to an
450 // fs.FileInfo describing the directory, and err set to the error from
451 // Readdirnames.
452 type WalkFunc func(path string, info fs.FileInfo, err error) error
453
454 var lstat = os.Lstat // for testing
455
456 // walkDir recursively descends path, calling walkDirFn.
457 func walkDir(path string, d fs.DirEntry, walkDirFn fs.WalkDirFunc) error {
458         if err := walkDirFn(path, d, nil); err != nil || !d.IsDir() {
459                 if err == SkipDir && d.IsDir() {
460                         // Successfully skipped directory.
461                         err = nil
462                 }
463                 return err
464         }
465
466         dirs, err := readDir(path)
467         if err != nil {
468                 // Second call, to report ReadDir error.
469                 err = walkDirFn(path, d, err)
470                 if err != nil {
471                         if err == SkipDir && d.IsDir() {
472                                 err = nil
473                         }
474                         return err
475                 }
476         }
477
478         for _, d1 := range dirs {
479                 path1 := Join(path, d1.Name())
480                 if err := walkDir(path1, d1, walkDirFn); err != nil {
481                         if err == SkipDir {
482                                 break
483                         }
484                         return err
485                 }
486         }
487         return nil
488 }
489
490 // walk recursively descends path, calling walkFn.
491 func walk(path string, info fs.FileInfo, walkFn WalkFunc) error {
492         if !info.IsDir() {
493                 return walkFn(path, info, nil)
494         }
495
496         names, err := readDirNames(path)
497         err1 := walkFn(path, info, err)
498         // If err != nil, walk can't walk into this directory.
499         // err1 != nil means walkFn want walk to skip this directory or stop walking.
500         // Therefore, if one of err and err1 isn't nil, walk will return.
501         if err != nil || err1 != nil {
502                 // The caller's behavior is controlled by the return value, which is decided
503                 // by walkFn. walkFn may ignore err and return nil.
504                 // If walkFn returns SkipDir or SkipAll, it will be handled by the caller.
505                 // So walk should return whatever walkFn returns.
506                 return err1
507         }
508
509         for _, name := range names {
510                 filename := Join(path, name)
511                 fileInfo, err := lstat(filename)
512                 if err != nil {
513                         if err := walkFn(filename, fileInfo, err); err != nil && err != SkipDir {
514                                 return err
515                         }
516                 } else {
517                         err = walk(filename, fileInfo, walkFn)
518                         if err != nil {
519                                 if !fileInfo.IsDir() || err != SkipDir {
520                                         return err
521                                 }
522                         }
523                 }
524         }
525         return nil
526 }
527
528 // WalkDir walks the file tree rooted at root, calling fn for each file or
529 // directory in the tree, including root.
530 //
531 // All errors that arise visiting files and directories are filtered by fn:
532 // see the fs.WalkDirFunc documentation for details.
533 //
534 // The files are walked in lexical order, which makes the output deterministic
535 // but requires WalkDir to read an entire directory into memory before proceeding
536 // to walk that directory.
537 //
538 // WalkDir does not follow symbolic links.
539 //
540 // WalkDir calls fn with paths that use the separator character appropriate
541 // for the operating system. This is unlike [io/fs.WalkDir], which always
542 // uses slash separated paths.
543 func WalkDir(root string, fn fs.WalkDirFunc) error {
544         info, err := os.Lstat(root)
545         if err != nil {
546                 err = fn(root, nil, err)
547         } else {
548                 err = walkDir(root, fs.FileInfoToDirEntry(info), fn)
549         }
550         if err == SkipDir || err == SkipAll {
551                 return nil
552         }
553         return err
554 }
555
556 // Walk walks the file tree rooted at root, calling fn for each file or
557 // directory in the tree, including root.
558 //
559 // All errors that arise visiting files and directories are filtered by fn:
560 // see the WalkFunc documentation for details.
561 //
562 // The files are walked in lexical order, which makes the output deterministic
563 // but requires Walk to read an entire directory into memory before proceeding
564 // to walk that directory.
565 //
566 // Walk does not follow symbolic links.
567 //
568 // Walk is less efficient than WalkDir, introduced in Go 1.16,
569 // which avoids calling os.Lstat on every visited file or directory.
570 func Walk(root string, fn WalkFunc) error {
571         info, err := os.Lstat(root)
572         if err != nil {
573                 err = fn(root, nil, err)
574         } else {
575                 err = walk(root, info, fn)
576         }
577         if err == SkipDir || err == SkipAll {
578                 return nil
579         }
580         return err
581 }
582
583 // readDir reads the directory named by dirname and returns
584 // a sorted list of directory entries.
585 func readDir(dirname string) ([]fs.DirEntry, error) {
586         f, err := os.Open(dirname)
587         if err != nil {
588                 return nil, err
589         }
590         dirs, err := f.ReadDir(-1)
591         f.Close()
592         if err != nil {
593                 return nil, err
594         }
595         sort.Slice(dirs, func(i, j int) bool { return dirs[i].Name() < dirs[j].Name() })
596         return dirs, nil
597 }
598
599 // readDirNames reads the directory named by dirname and returns
600 // a sorted list of directory entry names.
601 func readDirNames(dirname string) ([]string, error) {
602         f, err := os.Open(dirname)
603         if err != nil {
604                 return nil, err
605         }
606         names, err := f.Readdirnames(-1)
607         f.Close()
608         if err != nil {
609                 return nil, err
610         }
611         sort.Strings(names)
612         return names, nil
613 }
614
615 // Base returns the last element of path.
616 // Trailing path separators are removed before extracting the last element.
617 // If the path is empty, Base returns ".".
618 // If the path consists entirely of separators, Base returns a single separator.
619 func Base(path string) string {
620         if path == "" {
621                 return "."
622         }
623         // Strip trailing slashes.
624         for len(path) > 0 && os.IsPathSeparator(path[len(path)-1]) {
625                 path = path[0 : len(path)-1]
626         }
627         // Throw away volume name
628         path = path[len(VolumeName(path)):]
629         // Find the last element
630         i := len(path) - 1
631         for i >= 0 && !os.IsPathSeparator(path[i]) {
632                 i--
633         }
634         if i >= 0 {
635                 path = path[i+1:]
636         }
637         // If empty now, it had only slashes.
638         if path == "" {
639                 return string(Separator)
640         }
641         return path
642 }
643
644 // Dir returns all but the last element of path, typically the path's directory.
645 // After dropping the final element, Dir calls Clean on the path and trailing
646 // slashes are removed.
647 // If the path is empty, Dir returns ".".
648 // If the path consists entirely of separators, Dir returns a single separator.
649 // The returned path does not end in a separator unless it is the root directory.
650 func Dir(path string) string {
651         vol := VolumeName(path)
652         i := len(path) - 1
653         for i >= len(vol) && !os.IsPathSeparator(path[i]) {
654                 i--
655         }
656         dir := Clean(path[len(vol) : i+1])
657         if dir == "." && len(vol) > 2 {
658                 // must be UNC
659                 return vol
660         }
661         return vol + dir
662 }
663
664 // VolumeName returns leading volume name.
665 // Given "C:\foo\bar" it returns "C:" on Windows.
666 // Given "\\host\share\foo" it returns "\\host\share".
667 // On other platforms it returns "".
668 func VolumeName(path string) string {
669         return FromSlash(path[:volumeNameLen(path)])
670 }