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.
5 // Package filepath implements utility routines for manipulating filename paths
6 // in a way compatible with the target operating system-defined file paths.
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.
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.
36 func (b *lazybuf) index(i int) byte {
43 func (b *lazybuf) append(c byte) {
45 if b.w < len(b.path) && b.path[b.w] == c {
49 b.buf = make([]byte, len(b.path))
50 copy(b.buf, b.path[:b.w])
56 func (b *lazybuf) prepend(prefix ...byte) {
57 b.buf = slices.Insert(b.buf, 0, prefix...)
61 func (b *lazybuf) string() string {
63 return b.volAndPath[:b.volLen+b.w]
65 return b.volAndPath[:b.volLen] + string(b.buf[:b.w])
69 Separator = os.PathSeparator
70 ListSeparator = os.PathListSeparator
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:
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 '/'.
85 // The returned path ends in a slash only if it represents a root directory,
86 // such as "/" on Unix or `C:\` on Windows.
88 // Finally, any occurrences of slash are replaced by Separator.
90 // If the result of this process is an empty string, Clean
91 // returns the string ".".
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`.
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 {
102 volLen := volumeNameLen(path)
105 if volLen > 1 && os.IsPathSeparator(originalPath[0]) && os.IsPathSeparator(originalPath[1]) {
107 return FromSlash(originalPath)
109 return originalPath + "."
111 rooted := os.IsPathSeparator(path[0])
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.
119 out := lazybuf{path: path, volAndPath: originalPath, volLen: volLen}
122 out.append(Separator)
128 case os.IsPathSeparator(path[r]):
129 // empty path element
131 case path[r] == '.' && (r+1 == n || os.IsPathSeparator(path[r+1])):
134 case path[r] == '.' && path[r+1] == '.' && (r+2 == n || os.IsPathSeparator(path[r+2])):
135 // .. element: remove to last separator
141 for out.w > dotdot && !os.IsPathSeparator(out.index(out.w)) {
145 // cannot backtrack, but not rooted, so append .. element.
147 out.append(Separator)
154 // real path element.
155 // add slash if needed
156 if rooted && out.w != 1 || !rooted && out.w != 0 {
157 out.append(Separator)
160 for ; r < n && !os.IsPathSeparator(path[r]); r++ {
166 // Turn empty string into "."
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) {
180 out.prepend('.', Separator)
186 return FromSlash(out.string())
189 // IsLocal reports whether path, using lexical analysis only, has all of these properties:
191 // - is within the subtree rooted at the directory in which path is evaluated
192 // - is not an absolute path
194 // - on Windows, is not a reserved name such as "NUL"
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.
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 {
207 func unixIsLocal(path string) bool {
208 if IsAbs(path) || path == "" {
212 for p := path; p != ""; {
214 part, p, _ = strings.Cut(p, "/")
215 if part == "." || part == ".." {
223 if path == ".." || strings.HasPrefix(path, "../") {
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 == '/' {
236 return strings.ReplaceAll(path, string(Separator), "/")
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 == '/' {
246 return strings.ReplaceAll(path, "/", string(Separator))
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
253 func SplitList(path string) []string {
254 return splitList(path)
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)
265 for i >= len(vol) && !os.IsPathSeparator(path[i]) {
268 return path[:i+1], path[i+1:]
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
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 {
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
286 func Ext(path string) string {
287 for i := len(path) - 1; i >= 0 && !os.IsPathSeparator(path[i]); i-- {
295 // EvalSymlinks returns the path name after the evaluation of any symbolic
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)
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) {
313 func unixAbs(path string) (string, error) {
315 return Clean(path), nil
317 wd, err := os.Getwd()
321 return Join(wd, path), nil
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) {
340 base = base[len(baseVol):]
341 targ = targ[len(targVol):]
344 } else if base == "" && volumeNameLen(baseVol) > 2 /* isUNC */ {
345 // Treat any targetpath matching `\\host\share` basepath as absolute path.
346 base = string(Separator)
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)
355 // Position base[b0:bi] and targ[t0:ti] at the first differing elements.
358 var b0, bi, t0, ti int
360 for bi < bl && base[bi] != Separator {
363 for ti < tl && targ[ti] != Separator {
366 if !sameWord(targ[t0:ti], base[b0:bi]) {
378 if base[b0:bi] == ".." {
379 return "", errors.New("Rel: can't make " + targpath + " relative to " + basepath)
382 // Base elements left. Must go up before going down.
383 seps := strings.Count(base[b0:bl], string(Separator))
388 buf := make([]byte, size)
390 for i := 0; i < seps; i++ {
392 copy(buf[n+1:], "..")
397 copy(buf[n+1:], targ[t0:])
399 return string(buf), nil
401 return targ[t0:], nil
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
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
414 // WalkFunc is the type of the function called by Walk to visit each
415 // file or directory.
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
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".
427 // The info argument is the fs.FileInfo for the named path.
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.
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.
441 // Walk calls the function with a non-nil err argument in two cases.
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
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
452 type WalkFunc func(path string, info fs.FileInfo, err error) error
454 var lstat = os.Lstat // for testing
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.
466 dirs, err := readDir(path)
468 // Second call, to report ReadDir error.
469 err = walkDirFn(path, d, err)
471 if err == SkipDir && d.IsDir() {
478 for _, d1 := range dirs {
479 path1 := Join(path, d1.Name())
480 if err := walkDir(path1, d1, walkDirFn); err != nil {
490 // walk recursively descends path, calling walkFn.
491 func walk(path string, info fs.FileInfo, walkFn WalkFunc) error {
493 return walkFn(path, info, nil)
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.
509 for _, name := range names {
510 filename := Join(path, name)
511 fileInfo, err := lstat(filename)
513 if err := walkFn(filename, fileInfo, err); err != nil && err != SkipDir {
517 err = walk(filename, fileInfo, walkFn)
519 if !fileInfo.IsDir() || err != SkipDir {
528 // WalkDir walks the file tree rooted at root, calling fn for each file or
529 // directory in the tree, including root.
531 // All errors that arise visiting files and directories are filtered by fn:
532 // see the fs.WalkDirFunc documentation for details.
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.
538 // WalkDir does not follow symbolic links.
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)
546 err = fn(root, nil, err)
548 err = walkDir(root, fs.FileInfoToDirEntry(info), fn)
550 if err == SkipDir || err == SkipAll {
556 // Walk walks the file tree rooted at root, calling fn for each file or
557 // directory in the tree, including root.
559 // All errors that arise visiting files and directories are filtered by fn:
560 // see the WalkFunc documentation for details.
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.
566 // Walk does not follow symbolic links.
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)
573 err = fn(root, nil, err)
575 err = walk(root, info, fn)
577 if err == SkipDir || err == SkipAll {
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)
590 dirs, err := f.ReadDir(-1)
595 sort.Slice(dirs, func(i, j int) bool { return dirs[i].Name() < dirs[j].Name() })
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)
606 names, err := f.Readdirnames(-1)
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 {
623 // Strip trailing slashes.
624 for len(path) > 0 && os.IsPathSeparator(path[len(path)-1]) {
625 path = path[0 : len(path)-1]
627 // Throw away volume name
628 path = path[len(VolumeName(path)):]
629 // Find the last element
631 for i >= 0 && !os.IsPathSeparator(path[i]) {
637 // If empty now, it had only slashes.
639 return string(Separator)
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)
653 for i >= len(vol) && !os.IsPathSeparator(path[i]) {
656 dir := Clean(path[len(vol) : i+1])
657 if dir == "." && len(vol) > 2 {
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)])