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.
23 // A lazybuf is a lazily constructed path buffer.
24 // It supports append, reading previously appended bytes,
25 // and retrieving the final string. It does not allocate a buffer
26 // to hold the output until that output diverges from s.
35 func (b *lazybuf) index(i int) byte {
42 func (b *lazybuf) append(c byte) {
44 if b.w < len(b.path) && b.path[b.w] == c {
48 b.buf = make([]byte, len(b.path))
49 copy(b.buf, b.path[:b.w])
55 func (b *lazybuf) prepend(prefix ...byte) {
56 b.buf = slices.Insert(b.buf, 0, prefix...)
60 func (b *lazybuf) string() string {
62 return b.volAndPath[:b.volLen+b.w]
64 return b.volAndPath[:b.volLen] + string(b.buf[:b.w])
68 Separator = os.PathSeparator
69 ListSeparator = os.PathListSeparator
72 // Clean returns the shortest path name equivalent to path
73 // by purely lexical processing. It applies the following rules
74 // iteratively until no further processing can be done:
76 // 1. Replace multiple Separator elements with a single one.
77 // 2. Eliminate each . path name element (the current directory).
78 // 3. Eliminate each inner .. path name element (the parent directory)
79 // along with the non-.. element that precedes it.
80 // 4. Eliminate .. elements that begin a rooted path:
81 // that is, replace "/.." by "/" at the beginning of a path,
82 // assuming Separator is '/'.
84 // The returned path ends in a slash only if it represents a root directory,
85 // such as "/" on Unix or `C:\` on Windows.
87 // Finally, any occurrences of slash are replaced by Separator.
89 // If the result of this process is an empty string, Clean
90 // returns the string ".".
92 // On Windows, Clean does not modify the volume name other than to replace
93 // occurrences of "/" with `\`.
94 // For example, Clean("//host/share/../x") returns `\\host\share\x`.
96 // See also Rob Pike, “Lexical File Names in Plan 9 or
97 // Getting Dot-Dot Right,”
98 // https://9p.io/sys/doc/lexnames.html
99 func Clean(path string) string {
101 volLen := volumeNameLen(path)
104 if volLen > 1 && os.IsPathSeparator(originalPath[0]) && os.IsPathSeparator(originalPath[1]) {
106 return FromSlash(originalPath)
108 return originalPath + "."
110 rooted := os.IsPathSeparator(path[0])
113 // reading from path; r is index of next byte to process.
114 // writing to buf; w is index of next byte to write.
115 // dotdot is index in buf where .. must stop, either because
116 // it is the leading slash or it is a leading ../../.. prefix.
118 out := lazybuf{path: path, volAndPath: originalPath, volLen: volLen}
121 out.append(Separator)
127 case os.IsPathSeparator(path[r]):
128 // empty path element
130 case path[r] == '.' && (r+1 == n || os.IsPathSeparator(path[r+1])):
133 case path[r] == '.' && path[r+1] == '.' && (r+2 == n || os.IsPathSeparator(path[r+2])):
134 // .. element: remove to last separator
140 for out.w > dotdot && !os.IsPathSeparator(out.index(out.w)) {
144 // cannot backtrack, but not rooted, so append .. element.
146 out.append(Separator)
153 // real path element.
154 // add slash if needed
155 if rooted && out.w != 1 || !rooted && out.w != 0 {
156 out.append(Separator)
159 for ; r < n && !os.IsPathSeparator(path[r]); r++ {
165 // Turn empty string into "."
170 postClean(&out) // avoid creating absolute paths on Windows
171 return FromSlash(out.string())
174 // IsLocal reports whether path, using lexical analysis only, has all of these properties:
176 // - is within the subtree rooted at the directory in which path is evaluated
177 // - is not an absolute path
179 // - on Windows, is not a reserved name such as "NUL"
181 // If IsLocal(path) returns true, then
182 // Join(base, path) will always produce a path contained within base and
183 // Clean(path) will always produce an unrooted path with no ".." path elements.
185 // IsLocal is a purely lexical operation.
186 // In particular, it does not account for the effect of any symbolic links
187 // that may exist in the filesystem.
188 func IsLocal(path string) bool {
192 func unixIsLocal(path string) bool {
193 if IsAbs(path) || path == "" {
197 for p := path; p != ""; {
199 part, p, _ = strings.Cut(p, "/")
200 if part == "." || part == ".." {
208 if path == ".." || strings.HasPrefix(path, "../") {
214 // ToSlash returns the result of replacing each separator character
215 // in path with a slash ('/') character. Multiple separators are
216 // replaced by multiple slashes.
217 func ToSlash(path string) string {
218 if Separator == '/' {
221 return strings.ReplaceAll(path, string(Separator), "/")
224 // FromSlash returns the result of replacing each slash ('/') character
225 // in path with a separator character. Multiple slashes are replaced
226 // by multiple separators.
227 func FromSlash(path string) string {
228 if Separator == '/' {
231 return strings.ReplaceAll(path, "/", string(Separator))
234 // SplitList splits a list of paths joined by the OS-specific ListSeparator,
235 // usually found in PATH or GOPATH environment variables.
236 // Unlike strings.Split, SplitList returns an empty slice when passed an empty
238 func SplitList(path string) []string {
239 return splitList(path)
242 // Split splits path immediately following the final Separator,
243 // separating it into a directory and file name component.
244 // If there is no Separator in path, Split returns an empty dir
245 // and file set to path.
246 // The returned values have the property that path = dir+file.
247 func Split(path string) (dir, file string) {
248 vol := VolumeName(path)
250 for i >= len(vol) && !os.IsPathSeparator(path[i]) {
253 return path[:i+1], path[i+1:]
256 // Join joins any number of path elements into a single path,
257 // separating them with an OS specific Separator. Empty elements
258 // are ignored. The result is Cleaned. However, if the argument
259 // list is empty or all its elements are empty, Join returns
261 // On Windows, the result will only be a UNC path if the first
262 // non-empty element is a UNC path.
263 func Join(elem ...string) string {
267 // Ext returns the file name extension used by path.
268 // The extension is the suffix beginning at the final dot
269 // in the final element of path; it is empty if there is
271 func Ext(path string) string {
272 for i := len(path) - 1; i >= 0 && !os.IsPathSeparator(path[i]); i-- {
280 // EvalSymlinks returns the path name after the evaluation of any symbolic
282 // If path is relative the result will be relative to the current directory,
283 // unless one of the components is an absolute symbolic link.
284 // EvalSymlinks calls Clean on the result.
285 func EvalSymlinks(path string) (string, error) {
286 return evalSymlinks(path)
289 // Abs returns an absolute representation of path.
290 // If the path is not absolute it will be joined with the current
291 // working directory to turn it into an absolute path. The absolute
292 // path name for a given file is not guaranteed to be unique.
293 // Abs calls Clean on the result.
294 func Abs(path string) (string, error) {
298 func unixAbs(path string) (string, error) {
300 return Clean(path), nil
302 wd, err := os.Getwd()
306 return Join(wd, path), nil
309 // Rel returns a relative path that is lexically equivalent to targpath when
310 // joined to basepath with an intervening separator. That is,
311 // Join(basepath, Rel(basepath, targpath)) is equivalent to targpath itself.
312 // On success, the returned path will always be relative to basepath,
313 // even if basepath and targpath share no elements.
314 // An error is returned if targpath can't be made relative to basepath or if
315 // knowing the current working directory would be necessary to compute it.
316 // Rel calls Clean on the result.
317 func Rel(basepath, targpath string) (string, error) {
318 baseVol := VolumeName(basepath)
319 targVol := VolumeName(targpath)
320 base := Clean(basepath)
321 targ := Clean(targpath)
322 if sameWord(targ, base) {
325 base = base[len(baseVol):]
326 targ = targ[len(targVol):]
329 } else if base == "" && volumeNameLen(baseVol) > 2 /* isUNC */ {
330 // Treat any targetpath matching `\\host\share` basepath as absolute path.
331 base = string(Separator)
334 // Can't use IsAbs - `\a` and `a` are both relative in Windows.
335 baseSlashed := len(base) > 0 && base[0] == Separator
336 targSlashed := len(targ) > 0 && targ[0] == Separator
337 if baseSlashed != targSlashed || !sameWord(baseVol, targVol) {
338 return "", errors.New("Rel: can't make " + targpath + " relative to " + basepath)
340 // Position base[b0:bi] and targ[t0:ti] at the first differing elements.
343 var b0, bi, t0, ti int
345 for bi < bl && base[bi] != Separator {
348 for ti < tl && targ[ti] != Separator {
351 if !sameWord(targ[t0:ti], base[b0:bi]) {
363 if base[b0:bi] == ".." {
364 return "", errors.New("Rel: can't make " + targpath + " relative to " + basepath)
367 // Base elements left. Must go up before going down.
368 seps := strings.Count(base[b0:bl], string(Separator))
373 buf := make([]byte, size)
375 for i := 0; i < seps; i++ {
377 copy(buf[n+1:], "..")
382 copy(buf[n+1:], targ[t0:])
384 return string(buf), nil
386 return targ[t0:], nil
389 // SkipDir is used as a return value from WalkFuncs to indicate that
390 // the directory named in the call is to be skipped. It is not returned
391 // as an error by any function.
392 var SkipDir error = fs.SkipDir
394 // SkipAll is used as a return value from WalkFuncs to indicate that
395 // all remaining files and directories are to be skipped. It is not returned
396 // as an error by any function.
397 var SkipAll error = fs.SkipAll
399 // WalkFunc is the type of the function called by Walk to visit each
400 // file or directory.
402 // The path argument contains the argument to Walk as a prefix.
403 // That is, if Walk is called with root argument "dir" and finds a file
404 // named "a" in that directory, the walk function will be called with
407 // The directory and file are joined with Join, which may clean the
408 // directory name: if Walk is called with the root argument "x/../dir"
409 // and finds a file named "a" in that directory, the walk function will
410 // be called with argument "dir/a", not "x/../dir/a".
412 // The info argument is the fs.FileInfo for the named path.
414 // The error result returned by the function controls how Walk continues.
415 // If the function returns the special value SkipDir, Walk skips the
416 // current directory (path if info.IsDir() is true, otherwise path's
417 // parent directory). If the function returns the special value SkipAll,
418 // Walk skips all remaining files and directories. Otherwise, if the function
419 // returns a non-nil error, Walk stops entirely and returns that error.
421 // The err argument reports an error related to path, signaling that Walk
422 // will not walk into that directory. The function can decide how to
423 // handle that error; as described earlier, returning the error will
424 // cause Walk to stop walking the entire tree.
426 // Walk calls the function with a non-nil err argument in two cases.
428 // First, if an os.Lstat on the root directory or any directory or file
429 // in the tree fails, Walk calls the function with path set to that
430 // directory or file's path, info set to nil, and err set to the error
433 // Second, if a directory's Readdirnames method fails, Walk calls the
434 // function with path set to the directory's path, info, set to an
435 // fs.FileInfo describing the directory, and err set to the error from
437 type WalkFunc func(path string, info fs.FileInfo, err error) error
439 var lstat = os.Lstat // for testing
441 // walkDir recursively descends path, calling walkDirFn.
442 func walkDir(path string, d fs.DirEntry, walkDirFn fs.WalkDirFunc) error {
443 if err := walkDirFn(path, d, nil); err != nil || !d.IsDir() {
444 if err == SkipDir && d.IsDir() {
445 // Successfully skipped directory.
451 dirs, err := os.ReadDir(path)
453 // Second call, to report ReadDir error.
454 err = walkDirFn(path, d, err)
456 if err == SkipDir && d.IsDir() {
463 for _, d1 := range dirs {
464 path1 := Join(path, d1.Name())
465 if err := walkDir(path1, d1, walkDirFn); err != nil {
475 // walk recursively descends path, calling walkFn.
476 func walk(path string, info fs.FileInfo, walkFn WalkFunc) error {
478 return walkFn(path, info, nil)
481 names, err := readDirNames(path)
482 err1 := walkFn(path, info, err)
483 // If err != nil, walk can't walk into this directory.
484 // err1 != nil means walkFn want walk to skip this directory or stop walking.
485 // Therefore, if one of err and err1 isn't nil, walk will return.
486 if err != nil || err1 != nil {
487 // The caller's behavior is controlled by the return value, which is decided
488 // by walkFn. walkFn may ignore err and return nil.
489 // If walkFn returns SkipDir or SkipAll, it will be handled by the caller.
490 // So walk should return whatever walkFn returns.
494 for _, name := range names {
495 filename := Join(path, name)
496 fileInfo, err := lstat(filename)
498 if err := walkFn(filename, fileInfo, err); err != nil && err != SkipDir {
502 err = walk(filename, fileInfo, walkFn)
504 if !fileInfo.IsDir() || err != SkipDir {
513 // WalkDir walks the file tree rooted at root, calling fn for each file or
514 // directory in the tree, including root.
516 // All errors that arise visiting files and directories are filtered by fn:
517 // see the fs.WalkDirFunc documentation for details.
519 // The files are walked in lexical order, which makes the output deterministic
520 // but requires WalkDir to read an entire directory into memory before proceeding
521 // to walk that directory.
523 // WalkDir does not follow symbolic links.
525 // WalkDir calls fn with paths that use the separator character appropriate
526 // for the operating system. This is unlike [io/fs.WalkDir], which always
527 // uses slash separated paths.
528 func WalkDir(root string, fn fs.WalkDirFunc) error {
529 info, err := os.Lstat(root)
531 err = fn(root, nil, err)
533 err = walkDir(root, fs.FileInfoToDirEntry(info), fn)
535 if err == SkipDir || err == SkipAll {
541 // Walk walks the file tree rooted at root, calling fn for each file or
542 // directory in the tree, including root.
544 // All errors that arise visiting files and directories are filtered by fn:
545 // see the WalkFunc documentation for details.
547 // The files are walked in lexical order, which makes the output deterministic
548 // but requires Walk to read an entire directory into memory before proceeding
549 // to walk that directory.
551 // Walk does not follow symbolic links.
553 // Walk is less efficient than WalkDir, introduced in Go 1.16,
554 // which avoids calling os.Lstat on every visited file or directory.
555 func Walk(root string, fn WalkFunc) error {
556 info, err := os.Lstat(root)
558 err = fn(root, nil, err)
560 err = walk(root, info, fn)
562 if err == SkipDir || err == SkipAll {
568 // readDirNames reads the directory named by dirname and returns
569 // a sorted list of directory entry names.
570 func readDirNames(dirname string) ([]string, error) {
571 f, err := os.Open(dirname)
575 names, err := f.Readdirnames(-1)
584 // Base returns the last element of path.
585 // Trailing path separators are removed before extracting the last element.
586 // If the path is empty, Base returns ".".
587 // If the path consists entirely of separators, Base returns a single separator.
588 func Base(path string) string {
592 // Strip trailing slashes.
593 for len(path) > 0 && os.IsPathSeparator(path[len(path)-1]) {
594 path = path[0 : len(path)-1]
596 // Throw away volume name
597 path = path[len(VolumeName(path)):]
598 // Find the last element
600 for i >= 0 && !os.IsPathSeparator(path[i]) {
606 // If empty now, it had only slashes.
608 return string(Separator)
613 // Dir returns all but the last element of path, typically the path's directory.
614 // After dropping the final element, Dir calls Clean on the path and trailing
615 // slashes are removed.
616 // If the path is empty, Dir returns ".".
617 // If the path consists entirely of separators, Dir returns a single separator.
618 // The returned path does not end in a separator unless it is the root directory.
619 func Dir(path string) string {
620 vol := VolumeName(path)
622 for i >= len(vol) && !os.IsPathSeparator(path[i]) {
625 dir := Clean(path[len(vol) : i+1])
626 if dir == "." && len(vol) > 2 {
633 // VolumeName returns leading volume name.
634 // Given "C:\foo\bar" it returns "C:" on Windows.
635 // Given "\\host\share\foo" it returns "\\host\share".
636 // On other platforms it returns "".
637 func VolumeName(path string) string {
638 return FromSlash(path[:volumeNameLen(path)])