github.com/bgentry/go@v0.0.0-20150121062915-6cf5a733d54d/src/path/filepath/path.go (about)

     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  package filepath
     8  
     9  import (
    10  	"errors"
    11  	"os"
    12  	"sort"
    13  	"strings"
    14  )
    15  
    16  // A lazybuf is a lazily constructed path buffer.
    17  // It supports append, reading previously appended bytes,
    18  // and retrieving the final string. It does not allocate a buffer
    19  // to hold the output until that output diverges from s.
    20  type lazybuf struct {
    21  	path       string
    22  	buf        []byte
    23  	w          int
    24  	volAndPath string
    25  	volLen     int
    26  }
    27  
    28  func (b *lazybuf) index(i int) byte {
    29  	if b.buf != nil {
    30  		return b.buf[i]
    31  	}
    32  	return b.path[i]
    33  }
    34  
    35  func (b *lazybuf) append(c byte) {
    36  	if b.buf == nil {
    37  		if b.w < len(b.path) && b.path[b.w] == c {
    38  			b.w++
    39  			return
    40  		}
    41  		b.buf = make([]byte, len(b.path))
    42  		copy(b.buf, b.path[:b.w])
    43  	}
    44  	b.buf[b.w] = c
    45  	b.w++
    46  }
    47  
    48  func (b *lazybuf) string() string {
    49  	if b.buf == nil {
    50  		return b.volAndPath[:b.volLen+b.w]
    51  	}
    52  	return b.volAndPath[:b.volLen] + string(b.buf[:b.w])
    53  }
    54  
    55  const (
    56  	Separator     = os.PathSeparator
    57  	ListSeparator = os.PathListSeparator
    58  )
    59  
    60  // Clean returns the shortest path name equivalent to path
    61  // by purely lexical processing.  It applies the following rules
    62  // iteratively until no further processing can be done:
    63  //
    64  //	1. Replace multiple Separator elements with a single one.
    65  //	2. Eliminate each . path name element (the current directory).
    66  //	3. Eliminate each inner .. path name element (the parent directory)
    67  //	   along with the non-.. element that precedes it.
    68  //	4. Eliminate .. elements that begin a rooted path:
    69  //	   that is, replace "/.." by "/" at the beginning of a path,
    70  //	   assuming Separator is '/'.
    71  //
    72  // The returned path ends in a slash only if it represents a root directory,
    73  // such as "/" on Unix or `C:\` on Windows.
    74  //
    75  // If the result of this process is an empty string, Clean
    76  // returns the string ".".
    77  //
    78  // See also Rob Pike, ``Lexical File Names in Plan 9 or
    79  // Getting Dot-Dot Right,''
    80  // http://plan9.bell-labs.com/sys/doc/lexnames.html
    81  func Clean(path string) string {
    82  	originalPath := path
    83  	volLen := volumeNameLen(path)
    84  	path = path[volLen:]
    85  	if path == "" {
    86  		if volLen > 1 && originalPath[1] != ':' {
    87  			// should be UNC
    88  			return FromSlash(originalPath)
    89  		}
    90  		return originalPath + "."
    91  	}
    92  	rooted := os.IsPathSeparator(path[0])
    93  
    94  	// Invariants:
    95  	//	reading from path; r is index of next byte to process.
    96  	//	writing to buf; w is index of next byte to write.
    97  	//	dotdot is index in buf where .. must stop, either because
    98  	//		it is the leading slash or it is a leading ../../.. prefix.
    99  	n := len(path)
   100  	out := lazybuf{path: path, volAndPath: originalPath, volLen: volLen}
   101  	r, dotdot := 0, 0
   102  	if rooted {
   103  		out.append(Separator)
   104  		r, dotdot = 1, 1
   105  	}
   106  
   107  	for r < n {
   108  		switch {
   109  		case os.IsPathSeparator(path[r]):
   110  			// empty path element
   111  			r++
   112  		case path[r] == '.' && (r+1 == n || os.IsPathSeparator(path[r+1])):
   113  			// . element
   114  			r++
   115  		case path[r] == '.' && path[r+1] == '.' && (r+2 == n || os.IsPathSeparator(path[r+2])):
   116  			// .. element: remove to last separator
   117  			r += 2
   118  			switch {
   119  			case out.w > dotdot:
   120  				// can backtrack
   121  				out.w--
   122  				for out.w > dotdot && !os.IsPathSeparator(out.index(out.w)) {
   123  					out.w--
   124  				}
   125  			case !rooted:
   126  				// cannot backtrack, but not rooted, so append .. element.
   127  				if out.w > 0 {
   128  					out.append(Separator)
   129  				}
   130  				out.append('.')
   131  				out.append('.')
   132  				dotdot = out.w
   133  			}
   134  		default:
   135  			// real path element.
   136  			// add slash if needed
   137  			if rooted && out.w != 1 || !rooted && out.w != 0 {
   138  				out.append(Separator)
   139  			}
   140  			// copy element
   141  			for ; r < n && !os.IsPathSeparator(path[r]); r++ {
   142  				out.append(path[r])
   143  			}
   144  		}
   145  	}
   146  
   147  	// Turn empty string into "."
   148  	if out.w == 0 {
   149  		out.append('.')
   150  	}
   151  
   152  	return FromSlash(out.string())
   153  }
   154  
   155  // ToSlash returns the result of replacing each separator character
   156  // in path with a slash ('/') character. Multiple separators are
   157  // replaced by multiple slashes.
   158  func ToSlash(path string) string {
   159  	if Separator == '/' {
   160  		return path
   161  	}
   162  	return strings.Replace(path, string(Separator), "/", -1)
   163  }
   164  
   165  // FromSlash returns the result of replacing each slash ('/') character
   166  // in path with a separator character. Multiple slashes are replaced
   167  // by multiple separators.
   168  func FromSlash(path string) string {
   169  	if Separator == '/' {
   170  		return path
   171  	}
   172  	return strings.Replace(path, "/", string(Separator), -1)
   173  }
   174  
   175  // SplitList splits a list of paths joined by the OS-specific ListSeparator,
   176  // usually found in PATH or GOPATH environment variables.
   177  // Unlike strings.Split, SplitList returns an empty slice when passed an empty string.
   178  func SplitList(path string) []string {
   179  	return splitList(path)
   180  }
   181  
   182  // Split splits path immediately following the final Separator,
   183  // separating it into a directory and file name component.
   184  // If there is no Separator in path, Split returns an empty dir
   185  // and file set to path.
   186  // The returned values have the property that path = dir+file.
   187  func Split(path string) (dir, file string) {
   188  	vol := VolumeName(path)
   189  	i := len(path) - 1
   190  	for i >= len(vol) && !os.IsPathSeparator(path[i]) {
   191  		i--
   192  	}
   193  	return path[:i+1], path[i+1:]
   194  }
   195  
   196  // Join joins any number of path elements into a single path, adding
   197  // a Separator if necessary. The result is Cleaned, in particular
   198  // all empty strings are ignored.
   199  // On Windows, the result is a UNC path if and only if the first path
   200  // element is a UNC path.
   201  func Join(elem ...string) string {
   202  	return join(elem)
   203  }
   204  
   205  // Ext returns the file name extension used by path.
   206  // The extension is the suffix beginning at the final dot
   207  // in the final element of path; it is empty if there is
   208  // no dot.
   209  func Ext(path string) string {
   210  	for i := len(path) - 1; i >= 0 && !os.IsPathSeparator(path[i]); i-- {
   211  		if path[i] == '.' {
   212  			return path[i:]
   213  		}
   214  	}
   215  	return ""
   216  }
   217  
   218  // EvalSymlinks returns the path name after the evaluation of any symbolic
   219  // links.
   220  // If path is relative the result will be relative to the current directory,
   221  // unless one of the components is an absolute symbolic link.
   222  func EvalSymlinks(path string) (string, error) {
   223  	return evalSymlinks(path)
   224  }
   225  
   226  // Abs returns an absolute representation of path.
   227  // If the path is not absolute it will be joined with the current
   228  // working directory to turn it into an absolute path.  The absolute
   229  // path name for a given file is not guaranteed to be unique.
   230  func Abs(path string) (string, error) {
   231  	return abs(path)
   232  }
   233  
   234  func unixAbs(path string) (string, error) {
   235  	if IsAbs(path) {
   236  		return Clean(path), nil
   237  	}
   238  	wd, err := os.Getwd()
   239  	if err != nil {
   240  		return "", err
   241  	}
   242  	return Join(wd, path), nil
   243  }
   244  
   245  // Rel returns a relative path that is lexically equivalent to targpath when
   246  // joined to basepath with an intervening separator. That is,
   247  // Join(basepath, Rel(basepath, targpath)) is equivalent to targpath itself.
   248  // On success, the returned path will always be relative to basepath,
   249  // even if basepath and targpath share no elements.
   250  // An error is returned if targpath can't be made relative to basepath or if
   251  // knowing the current working directory would be necessary to compute it.
   252  func Rel(basepath, targpath string) (string, error) {
   253  	baseVol := VolumeName(basepath)
   254  	targVol := VolumeName(targpath)
   255  	base := Clean(basepath)
   256  	targ := Clean(targpath)
   257  	if targ == base {
   258  		return ".", nil
   259  	}
   260  	base = base[len(baseVol):]
   261  	targ = targ[len(targVol):]
   262  	if base == "." {
   263  		base = ""
   264  	}
   265  	// Can't use IsAbs - `\a` and `a` are both relative in Windows.
   266  	baseSlashed := len(base) > 0 && base[0] == Separator
   267  	targSlashed := len(targ) > 0 && targ[0] == Separator
   268  	if baseSlashed != targSlashed || baseVol != targVol {
   269  		return "", errors.New("Rel: can't make " + targ + " relative to " + base)
   270  	}
   271  	// Position base[b0:bi] and targ[t0:ti] at the first differing elements.
   272  	bl := len(base)
   273  	tl := len(targ)
   274  	var b0, bi, t0, ti int
   275  	for {
   276  		for bi < bl && base[bi] != Separator {
   277  			bi++
   278  		}
   279  		for ti < tl && targ[ti] != Separator {
   280  			ti++
   281  		}
   282  		if targ[t0:ti] != base[b0:bi] {
   283  			break
   284  		}
   285  		if bi < bl {
   286  			bi++
   287  		}
   288  		if ti < tl {
   289  			ti++
   290  		}
   291  		b0 = bi
   292  		t0 = ti
   293  	}
   294  	if base[b0:bi] == ".." {
   295  		return "", errors.New("Rel: can't make " + targ + " relative to " + base)
   296  	}
   297  	if b0 != bl {
   298  		// Base elements left. Must go up before going down.
   299  		seps := strings.Count(base[b0:bl], string(Separator))
   300  		size := 2 + seps*3
   301  		if tl != t0 {
   302  			size += 1 + tl - t0
   303  		}
   304  		buf := make([]byte, size)
   305  		n := copy(buf, "..")
   306  		for i := 0; i < seps; i++ {
   307  			buf[n] = Separator
   308  			copy(buf[n+1:], "..")
   309  			n += 3
   310  		}
   311  		if t0 != tl {
   312  			buf[n] = Separator
   313  			copy(buf[n+1:], targ[t0:])
   314  		}
   315  		return string(buf), nil
   316  	}
   317  	return targ[t0:], nil
   318  }
   319  
   320  // SkipDir is used as a return value from WalkFuncs to indicate that
   321  // the directory named in the call is to be skipped. It is not returned
   322  // as an error by any function.
   323  var SkipDir = errors.New("skip this directory")
   324  
   325  // WalkFunc is the type of the function called for each file or directory
   326  // visited by Walk. The path argument contains the argument to Walk as a
   327  // prefix; that is, if Walk is called with "dir", which is a directory
   328  // containing the file "a", the walk function will be called with argument
   329  // "dir/a". The info argument is the os.FileInfo for the named path.
   330  //
   331  // If there was a problem walking to the file or directory named by path, the
   332  // incoming error will describe the problem and the function can decide how
   333  // to handle that error (and Walk will not descend into that directory). If
   334  // an error is returned, processing stops. The sole exception is that if path
   335  // is a directory and the function returns the special value SkipDir, the
   336  // contents of the directory are skipped and processing continues as usual on
   337  // the next file.
   338  type WalkFunc func(path string, info os.FileInfo, err error) error
   339  
   340  var lstat = os.Lstat // for testing
   341  
   342  // walk recursively descends path, calling w.
   343  func walk(path string, info os.FileInfo, walkFn WalkFunc) error {
   344  	err := walkFn(path, info, nil)
   345  	if err != nil {
   346  		if info.IsDir() && err == SkipDir {
   347  			return nil
   348  		}
   349  		return err
   350  	}
   351  
   352  	if !info.IsDir() {
   353  		return nil
   354  	}
   355  
   356  	names, err := readDirNames(path)
   357  	if err != nil {
   358  		return walkFn(path, info, err)
   359  	}
   360  
   361  	for _, name := range names {
   362  		filename := Join(path, name)
   363  		fileInfo, err := lstat(filename)
   364  		if err != nil {
   365  			if err := walkFn(filename, fileInfo, err); err != nil && err != SkipDir {
   366  				return err
   367  			}
   368  		} else {
   369  			err = walk(filename, fileInfo, walkFn)
   370  			if err != nil {
   371  				if !fileInfo.IsDir() || err != SkipDir {
   372  					return err
   373  				}
   374  			}
   375  		}
   376  	}
   377  	return nil
   378  }
   379  
   380  // Walk walks the file tree rooted at root, calling walkFn for each file or
   381  // directory in the tree, including root. All errors that arise visiting files
   382  // and directories are filtered by walkFn. The files are walked in lexical
   383  // order, which makes the output deterministic but means that for very
   384  // large directories Walk can be inefficient.
   385  // Walk does not follow symbolic links.
   386  func Walk(root string, walkFn WalkFunc) error {
   387  	info, err := os.Lstat(root)
   388  	if err != nil {
   389  		return walkFn(root, nil, err)
   390  	}
   391  	return walk(root, info, walkFn)
   392  }
   393  
   394  // readDirNames reads the directory named by dirname and returns
   395  // a sorted list of directory entries.
   396  func readDirNames(dirname string) ([]string, error) {
   397  	f, err := os.Open(dirname)
   398  	if err != nil {
   399  		return nil, err
   400  	}
   401  	names, err := f.Readdirnames(-1)
   402  	f.Close()
   403  	if err != nil {
   404  		return nil, err
   405  	}
   406  	sort.Strings(names)
   407  	return names, nil
   408  }
   409  
   410  // Base returns the last element of path.
   411  // Trailing path separators are removed before extracting the last element.
   412  // If the path is empty, Base returns ".".
   413  // If the path consists entirely of separators, Base returns a single separator.
   414  func Base(path string) string {
   415  	if path == "" {
   416  		return "."
   417  	}
   418  	// Strip trailing slashes.
   419  	for len(path) > 0 && os.IsPathSeparator(path[len(path)-1]) {
   420  		path = path[0 : len(path)-1]
   421  	}
   422  	// Throw away volume name
   423  	path = path[len(VolumeName(path)):]
   424  	// Find the last element
   425  	i := len(path) - 1
   426  	for i >= 0 && !os.IsPathSeparator(path[i]) {
   427  		i--
   428  	}
   429  	if i >= 0 {
   430  		path = path[i+1:]
   431  	}
   432  	// If empty now, it had only slashes.
   433  	if path == "" {
   434  		return string(Separator)
   435  	}
   436  	return path
   437  }
   438  
   439  // Dir returns all but the last element of path, typically the path's directory.
   440  // After dropping the final element, the path is Cleaned and trailing
   441  // slashes are removed.
   442  // If the path is empty, Dir returns ".".
   443  // If the path consists entirely of separators, Dir returns a single separator.
   444  // The returned path does not end in a separator unless it is the root directory.
   445  func Dir(path string) string {
   446  	vol := VolumeName(path)
   447  	i := len(path) - 1
   448  	for i >= len(vol) && !os.IsPathSeparator(path[i]) {
   449  		i--
   450  	}
   451  	dir := Clean(path[len(vol) : i+1])
   452  	return vol + dir
   453  }
   454  
   455  // VolumeName returns leading volume name.
   456  // Given "C:\foo\bar" it returns "C:" on Windows.
   457  // Given "\\host\share\foo" it returns "\\host\share".
   458  // On other platforms it returns "".
   459  func VolumeName(path string) string {
   460  	return path[:volumeNameLen(path)]
   461  }