Source file src/path/filepath/path_test.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_test
     6  
     7  import (
     8  	"errors"
     9  	"fmt"
    10  	"internal/testenv"
    11  	"io/fs"
    12  	"os"
    13  	"path/filepath"
    14  	"reflect"
    15  	"runtime"
    16  	"sort"
    17  	"strings"
    18  	"syscall"
    19  	"testing"
    20  )
    21  
    22  type PathTest struct {
    23  	path, result string
    24  }
    25  
    26  var cleantests = []PathTest{
    27  	// Already clean
    28  	{"abc", "abc"},
    29  	{"abc/def", "abc/def"},
    30  	{"a/b/c", "a/b/c"},
    31  	{".", "."},
    32  	{"..", ".."},
    33  	{"../..", "../.."},
    34  	{"../../abc", "../../abc"},
    35  	{"/abc", "/abc"},
    36  	{"/", "/"},
    37  
    38  	// Empty is current dir
    39  	{"", "."},
    40  
    41  	// Remove trailing slash
    42  	{"abc/", "abc"},
    43  	{"abc/def/", "abc/def"},
    44  	{"a/b/c/", "a/b/c"},
    45  	{"./", "."},
    46  	{"../", ".."},
    47  	{"../../", "../.."},
    48  	{"/abc/", "/abc"},
    49  
    50  	// Remove doubled slash
    51  	{"abc//def//ghi", "abc/def/ghi"},
    52  	{"//abc", "/abc"},
    53  	{"///abc", "/abc"},
    54  	{"//abc//", "/abc"},
    55  	{"abc//", "abc"},
    56  
    57  	// Remove . elements
    58  	{"abc/./def", "abc/def"},
    59  	{"/./abc/def", "/abc/def"},
    60  	{"abc/.", "abc"},
    61  
    62  	// Remove .. elements
    63  	{"abc/def/ghi/../jkl", "abc/def/jkl"},
    64  	{"abc/def/../ghi/../jkl", "abc/jkl"},
    65  	{"abc/def/..", "abc"},
    66  	{"abc/def/../..", "."},
    67  	{"/abc/def/../..", "/"},
    68  	{"abc/def/../../..", ".."},
    69  	{"/abc/def/../../..", "/"},
    70  	{"abc/def/../../../ghi/jkl/../../../mno", "../../mno"},
    71  	{"/../abc", "/abc"},
    72  
    73  	// Combinations
    74  	{"abc/./../def", "def"},
    75  	{"abc//./../def", "def"},
    76  	{"abc/../../././../def", "../../def"},
    77  }
    78  
    79  var wincleantests = []PathTest{
    80  	{`c:`, `c:.`},
    81  	{`c:\`, `c:\`},
    82  	{`c:\abc`, `c:\abc`},
    83  	{`c:abc\..\..\.\.\..\def`, `c:..\..\def`},
    84  	{`c:\abc\def\..\..`, `c:\`},
    85  	{`c:\..\abc`, `c:\abc`},
    86  	{`c:..\abc`, `c:..\abc`},
    87  	{`\`, `\`},
    88  	{`/`, `\`},
    89  	{`\\i\..\c$`, `\c$`},
    90  	{`\\i\..\i\c$`, `\i\c$`},
    91  	{`\\i\..\I\c$`, `\I\c$`},
    92  	{`\\host\share\foo\..\bar`, `\\host\share\bar`},
    93  	{`//host/share/foo/../baz`, `\\host\share\baz`},
    94  	{`\\a\b\..\c`, `\\a\b\c`},
    95  	{`\\a\b`, `\\a\b`},
    96  }
    97  
    98  func TestClean(t *testing.T) {
    99  	tests := cleantests
   100  	if runtime.GOOS == "windows" {
   101  		for i := range tests {
   102  			tests[i].result = filepath.FromSlash(tests[i].result)
   103  		}
   104  		tests = append(tests, wincleantests...)
   105  	}
   106  	for _, test := range tests {
   107  		if s := filepath.Clean(test.path); s != test.result {
   108  			t.Errorf("Clean(%q) = %q, want %q", test.path, s, test.result)
   109  		}
   110  		if s := filepath.Clean(test.result); s != test.result {
   111  			t.Errorf("Clean(%q) = %q, want %q", test.result, s, test.result)
   112  		}
   113  	}
   114  
   115  	if testing.Short() {
   116  		t.Skip("skipping malloc count in short mode")
   117  	}
   118  	if runtime.GOMAXPROCS(0) > 1 {
   119  		t.Log("skipping AllocsPerRun checks; GOMAXPROCS>1")
   120  		return
   121  	}
   122  
   123  	for _, test := range tests {
   124  		allocs := testing.AllocsPerRun(100, func() { filepath.Clean(test.result) })
   125  		if allocs > 0 {
   126  			t.Errorf("Clean(%q): %v allocs, want zero", test.result, allocs)
   127  		}
   128  	}
   129  }
   130  
   131  const sep = filepath.Separator
   132  
   133  var slashtests = []PathTest{
   134  	{"", ""},
   135  	{"/", string(sep)},
   136  	{"/a/b", string([]byte{sep, 'a', sep, 'b'})},
   137  	{"a//b", string([]byte{'a', sep, sep, 'b'})},
   138  }
   139  
   140  func TestFromAndToSlash(t *testing.T) {
   141  	for _, test := range slashtests {
   142  		if s := filepath.FromSlash(test.path); s != test.result {
   143  			t.Errorf("FromSlash(%q) = %q, want %q", test.path, s, test.result)
   144  		}
   145  		if s := filepath.ToSlash(test.result); s != test.path {
   146  			t.Errorf("ToSlash(%q) = %q, want %q", test.result, s, test.path)
   147  		}
   148  	}
   149  }
   150  
   151  type SplitListTest struct {
   152  	list   string
   153  	result []string
   154  }
   155  
   156  const lsep = filepath.ListSeparator
   157  
   158  var splitlisttests = []SplitListTest{
   159  	{"", []string{}},
   160  	{string([]byte{'a', lsep, 'b'}), []string{"a", "b"}},
   161  	{string([]byte{lsep, 'a', lsep, 'b'}), []string{"", "a", "b"}},
   162  }
   163  
   164  var winsplitlisttests = []SplitListTest{
   165  	// quoted
   166  	{`"a"`, []string{`a`}},
   167  
   168  	// semicolon
   169  	{`";"`, []string{`;`}},
   170  	{`"a;b"`, []string{`a;b`}},
   171  	{`";";`, []string{`;`, ``}},
   172  	{`;";"`, []string{``, `;`}},
   173  
   174  	// partially quoted
   175  	{`a";"b`, []string{`a;b`}},
   176  	{`a; ""b`, []string{`a`, ` b`}},
   177  	{`"a;b`, []string{`a;b`}},
   178  	{`""a;b`, []string{`a`, `b`}},
   179  	{`"""a;b`, []string{`a;b`}},
   180  	{`""""a;b`, []string{`a`, `b`}},
   181  	{`a";b`, []string{`a;b`}},
   182  	{`a;b";c`, []string{`a`, `b;c`}},
   183  	{`"a";b";c`, []string{`a`, `b;c`}},
   184  }
   185  
   186  func TestSplitList(t *testing.T) {
   187  	tests := splitlisttests
   188  	if runtime.GOOS == "windows" {
   189  		tests = append(tests, winsplitlisttests...)
   190  	}
   191  	for _, test := range tests {
   192  		if l := filepath.SplitList(test.list); !reflect.DeepEqual(l, test.result) {
   193  			t.Errorf("SplitList(%#q) = %#q, want %#q", test.list, l, test.result)
   194  		}
   195  	}
   196  }
   197  
   198  type SplitTest struct {
   199  	path, dir, file string
   200  }
   201  
   202  var unixsplittests = []SplitTest{
   203  	{"a/b", "a/", "b"},
   204  	{"a/b/", "a/b/", ""},
   205  	{"a/", "a/", ""},
   206  	{"a", "", "a"},
   207  	{"/", "/", ""},
   208  }
   209  
   210  var winsplittests = []SplitTest{
   211  	{`c:`, `c:`, ``},
   212  	{`c:/`, `c:/`, ``},
   213  	{`c:/foo`, `c:/`, `foo`},
   214  	{`c:/foo/bar`, `c:/foo/`, `bar`},
   215  	{`//host/share`, `//host/share`, ``},
   216  	{`//host/share/`, `//host/share/`, ``},
   217  	{`//host/share/foo`, `//host/share/`, `foo`},
   218  	{`\\host\share`, `\\host\share`, ``},
   219  	{`\\host\share\`, `\\host\share\`, ``},
   220  	{`\\host\share\foo`, `\\host\share\`, `foo`},
   221  }
   222  
   223  func TestSplit(t *testing.T) {
   224  	var splittests []SplitTest
   225  	splittests = unixsplittests
   226  	if runtime.GOOS == "windows" {
   227  		splittests = append(splittests, winsplittests...)
   228  	}
   229  	for _, test := range splittests {
   230  		if d, f := filepath.Split(test.path); d != test.dir || f != test.file {
   231  			t.Errorf("Split(%q) = %q, %q, want %q, %q", test.path, d, f, test.dir, test.file)
   232  		}
   233  	}
   234  }
   235  
   236  type JoinTest struct {
   237  	elem []string
   238  	path string
   239  }
   240  
   241  var jointests = []JoinTest{
   242  	// zero parameters
   243  	{[]string{}, ""},
   244  
   245  	// one parameter
   246  	{[]string{""}, ""},
   247  	{[]string{"/"}, "/"},
   248  	{[]string{"a"}, "a"},
   249  
   250  	// two parameters
   251  	{[]string{"a", "b"}, "a/b"},
   252  	{[]string{"a", ""}, "a"},
   253  	{[]string{"", "b"}, "b"},
   254  	{[]string{"/", "a"}, "/a"},
   255  	{[]string{"/", "a/b"}, "/a/b"},
   256  	{[]string{"/", ""}, "/"},
   257  	{[]string{"//", "a"}, "/a"},
   258  	{[]string{"/a", "b"}, "/a/b"},
   259  	{[]string{"a/", "b"}, "a/b"},
   260  	{[]string{"a/", ""}, "a"},
   261  	{[]string{"", ""}, ""},
   262  
   263  	// three parameters
   264  	{[]string{"/", "a", "b"}, "/a/b"},
   265  }
   266  
   267  var winjointests = []JoinTest{
   268  	{[]string{`directory`, `file`}, `directory\file`},
   269  	{[]string{`C:\Windows\`, `System32`}, `C:\Windows\System32`},
   270  	{[]string{`C:\Windows\`, ``}, `C:\Windows`},
   271  	{[]string{`C:\`, `Windows`}, `C:\Windows`},
   272  	{[]string{`C:`, `a`}, `C:a`},
   273  	{[]string{`C:`, `a\b`}, `C:a\b`},
   274  	{[]string{`C:`, `a`, `b`}, `C:a\b`},
   275  	{[]string{`C:`, ``, `b`}, `C:b`},
   276  	{[]string{`C:`, ``, ``, `b`}, `C:b`},
   277  	{[]string{`C:`, ``}, `C:.`},
   278  	{[]string{`C:`, ``, ``}, `C:.`},
   279  	{[]string{`C:.`, `a`}, `C:a`},
   280  	{[]string{`C:a`, `b`}, `C:a\b`},
   281  	{[]string{`C:a`, `b`, `d`}, `C:a\b\d`},
   282  	{[]string{`\\host\share`, `foo`}, `\\host\share\foo`},
   283  	{[]string{`\\host\share\foo`}, `\\host\share\foo`},
   284  	{[]string{`//host/share`, `foo/bar`}, `\\host\share\foo\bar`},
   285  	{[]string{`\`}, `\`},
   286  	{[]string{`\`, ``}, `\`},
   287  	{[]string{`\`, `a`}, `\a`},
   288  	{[]string{`\\`, `a`}, `\a`},
   289  	{[]string{`\`, `a`, `b`}, `\a\b`},
   290  	{[]string{`\\`, `a`, `b`}, `\a\b`},
   291  	{[]string{`\`, `\\a\b`, `c`}, `\a\b\c`},
   292  	{[]string{`\\a`, `b`, `c`}, `\a\b\c`},
   293  	{[]string{`\\a\`, `b`, `c`}, `\a\b\c`},
   294  }
   295  
   296  func TestJoin(t *testing.T) {
   297  	if runtime.GOOS == "windows" {
   298  		jointests = append(jointests, winjointests...)
   299  	}
   300  	for _, test := range jointests {
   301  		expected := filepath.FromSlash(test.path)
   302  		if p := filepath.Join(test.elem...); p != expected {
   303  			t.Errorf("join(%q) = %q, want %q", test.elem, p, expected)
   304  		}
   305  	}
   306  }
   307  
   308  type ExtTest struct {
   309  	path, ext string
   310  }
   311  
   312  var exttests = []ExtTest{
   313  	{"path.go", ".go"},
   314  	{"path.pb.go", ".go"},
   315  	{"a.dir/b", ""},
   316  	{"a.dir/b.go", ".go"},
   317  	{"a.dir/", ""},
   318  }
   319  
   320  func TestExt(t *testing.T) {
   321  	for _, test := range exttests {
   322  		if x := filepath.Ext(test.path); x != test.ext {
   323  			t.Errorf("Ext(%q) = %q, want %q", test.path, x, test.ext)
   324  		}
   325  	}
   326  }
   327  
   328  type Node struct {
   329  	name    string
   330  	entries []*Node // nil if the entry is a file
   331  	mark    int
   332  }
   333  
   334  var tree = &Node{
   335  	"testdata",
   336  	[]*Node{
   337  		{"a", nil, 0},
   338  		{"b", []*Node{}, 0},
   339  		{"c", nil, 0},
   340  		{
   341  			"d",
   342  			[]*Node{
   343  				{"x", nil, 0},
   344  				{"y", []*Node{}, 0},
   345  				{
   346  					"z",
   347  					[]*Node{
   348  						{"u", nil, 0},
   349  						{"v", nil, 0},
   350  					},
   351  					0,
   352  				},
   353  			},
   354  			0,
   355  		},
   356  	},
   357  	0,
   358  }
   359  
   360  func walkTree(n *Node, path string, f func(path string, n *Node)) {
   361  	f(path, n)
   362  	for _, e := range n.entries {
   363  		walkTree(e, filepath.Join(path, e.name), f)
   364  	}
   365  }
   366  
   367  func makeTree(t *testing.T) {
   368  	walkTree(tree, tree.name, func(path string, n *Node) {
   369  		if n.entries == nil {
   370  			fd, err := os.Create(path)
   371  			if err != nil {
   372  				t.Errorf("makeTree: %v", err)
   373  				return
   374  			}
   375  			fd.Close()
   376  		} else {
   377  			os.Mkdir(path, 0770)
   378  		}
   379  	})
   380  }
   381  
   382  func markTree(n *Node) { walkTree(n, "", func(path string, n *Node) { n.mark++ }) }
   383  
   384  func checkMarks(t *testing.T, report bool) {
   385  	walkTree(tree, tree.name, func(path string, n *Node) {
   386  		if n.mark != 1 && report {
   387  			t.Errorf("node %s mark = %d; expected 1", path, n.mark)
   388  		}
   389  		n.mark = 0
   390  	})
   391  }
   392  
   393  // Assumes that each node name is unique. Good enough for a test.
   394  // If clear is true, any incoming error is cleared before return. The errors
   395  // are always accumulated, though.
   396  func mark(d fs.DirEntry, err error, errors *[]error, clear bool) error {
   397  	name := d.Name()
   398  	walkTree(tree, tree.name, func(path string, n *Node) {
   399  		if n.name == name {
   400  			n.mark++
   401  		}
   402  	})
   403  	if err != nil {
   404  		*errors = append(*errors, err)
   405  		if clear {
   406  			return nil
   407  		}
   408  		return err
   409  	}
   410  	return nil
   411  }
   412  
   413  // chdir changes the current working directory to the named directory,
   414  // and then restore the original working directory at the end of the test.
   415  func chdir(t *testing.T, dir string) {
   416  	olddir, err := os.Getwd()
   417  	if err != nil {
   418  		t.Fatalf("getwd %s: %v", dir, err)
   419  	}
   420  	if err := os.Chdir(dir); err != nil {
   421  		t.Fatalf("chdir %s: %v", dir, err)
   422  	}
   423  
   424  	t.Cleanup(func() {
   425  		if err := os.Chdir(olddir); err != nil {
   426  			t.Errorf("restore original working directory %s: %v", olddir, err)
   427  			os.Exit(1)
   428  		}
   429  	})
   430  }
   431  
   432  func chtmpdir(t *testing.T) (restore func()) {
   433  	oldwd, err := os.Getwd()
   434  	if err != nil {
   435  		t.Fatalf("chtmpdir: %v", err)
   436  	}
   437  	d, err := os.MkdirTemp("", "test")
   438  	if err != nil {
   439  		t.Fatalf("chtmpdir: %v", err)
   440  	}
   441  	if err := os.Chdir(d); err != nil {
   442  		t.Fatalf("chtmpdir: %v", err)
   443  	}
   444  	return func() {
   445  		if err := os.Chdir(oldwd); err != nil {
   446  			t.Fatalf("chtmpdir: %v", err)
   447  		}
   448  		os.RemoveAll(d)
   449  	}
   450  }
   451  
   452  // tempDirCanonical returns a temporary directory for the test to use, ensuring
   453  // that the returned path does not contain symlinks.
   454  func tempDirCanonical(t *testing.T) string {
   455  	dir := t.TempDir()
   456  
   457  	cdir, err := filepath.EvalSymlinks(dir)
   458  	if err != nil {
   459  		t.Errorf("tempDirCanonical: %v", err)
   460  	}
   461  
   462  	return cdir
   463  }
   464  
   465  func TestWalk(t *testing.T) {
   466  	walk := func(root string, fn fs.WalkDirFunc) error {
   467  		return filepath.Walk(root, func(path string, info fs.FileInfo, err error) error {
   468  			return fn(path, &statDirEntry{info}, err)
   469  		})
   470  	}
   471  	testWalk(t, walk, 1)
   472  }
   473  
   474  type statDirEntry struct {
   475  	info fs.FileInfo
   476  }
   477  
   478  func (d *statDirEntry) Name() string               { return d.info.Name() }
   479  func (d *statDirEntry) IsDir() bool                { return d.info.IsDir() }
   480  func (d *statDirEntry) Type() fs.FileMode          { return d.info.Mode().Type() }
   481  func (d *statDirEntry) Info() (fs.FileInfo, error) { return d.info, nil }
   482  
   483  func TestWalkDir(t *testing.T) {
   484  	testWalk(t, filepath.WalkDir, 2)
   485  }
   486  
   487  func testWalk(t *testing.T, walk func(string, fs.WalkDirFunc) error, errVisit int) {
   488  	if runtime.GOOS == "ios" {
   489  		restore := chtmpdir(t)
   490  		defer restore()
   491  	}
   492  
   493  	tmpDir := t.TempDir()
   494  
   495  	origDir, err := os.Getwd()
   496  	if err != nil {
   497  		t.Fatal("finding working dir:", err)
   498  	}
   499  	if err = os.Chdir(tmpDir); err != nil {
   500  		t.Fatal("entering temp dir:", err)
   501  	}
   502  	defer os.Chdir(origDir)
   503  
   504  	makeTree(t)
   505  	errors := make([]error, 0, 10)
   506  	clear := true
   507  	markFn := func(path string, d fs.DirEntry, err error) error {
   508  		return mark(d, err, &errors, clear)
   509  	}
   510  	// Expect no errors.
   511  	err = walk(tree.name, markFn)
   512  	if err != nil {
   513  		t.Fatalf("no error expected, found: %s", err)
   514  	}
   515  	if len(errors) != 0 {
   516  		t.Fatalf("unexpected errors: %s", errors)
   517  	}
   518  	checkMarks(t, true)
   519  	errors = errors[0:0]
   520  
   521  	t.Run("PermErr", func(t *testing.T) {
   522  		// Test permission errors. Only possible if we're not root
   523  		// and only on some file systems (AFS, FAT).  To avoid errors during
   524  		// all.bash on those file systems, skip during go test -short.
   525  		if runtime.GOOS == "windows" {
   526  			t.Skip("skipping on Windows")
   527  		}
   528  		if os.Getuid() == 0 {
   529  			t.Skip("skipping as root")
   530  		}
   531  		if testing.Short() {
   532  			t.Skip("skipping in short mode")
   533  		}
   534  
   535  		// introduce 2 errors: chmod top-level directories to 0
   536  		os.Chmod(filepath.Join(tree.name, tree.entries[1].name), 0)
   537  		os.Chmod(filepath.Join(tree.name, tree.entries[3].name), 0)
   538  
   539  		// 3) capture errors, expect two.
   540  		// mark respective subtrees manually
   541  		markTree(tree.entries[1])
   542  		markTree(tree.entries[3])
   543  		// correct double-marking of directory itself
   544  		tree.entries[1].mark -= errVisit
   545  		tree.entries[3].mark -= errVisit
   546  		err := walk(tree.name, markFn)
   547  		if err != nil {
   548  			t.Fatalf("expected no error return from Walk, got %s", err)
   549  		}
   550  		if len(errors) != 2 {
   551  			t.Errorf("expected 2 errors, got %d: %s", len(errors), errors)
   552  		}
   553  		// the inaccessible subtrees were marked manually
   554  		checkMarks(t, true)
   555  		errors = errors[0:0]
   556  
   557  		// 4) capture errors, stop after first error.
   558  		// mark respective subtrees manually
   559  		markTree(tree.entries[1])
   560  		markTree(tree.entries[3])
   561  		// correct double-marking of directory itself
   562  		tree.entries[1].mark -= errVisit
   563  		tree.entries[3].mark -= errVisit
   564  		clear = false // error will stop processing
   565  		err = walk(tree.name, markFn)
   566  		if err == nil {
   567  			t.Fatalf("expected error return from Walk")
   568  		}
   569  		if len(errors) != 1 {
   570  			t.Errorf("expected 1 error, got %d: %s", len(errors), errors)
   571  		}
   572  		// the inaccessible subtrees were marked manually
   573  		checkMarks(t, false)
   574  		errors = errors[0:0]
   575  
   576  		// restore permissions
   577  		os.Chmod(filepath.Join(tree.name, tree.entries[1].name), 0770)
   578  		os.Chmod(filepath.Join(tree.name, tree.entries[3].name), 0770)
   579  	})
   580  }
   581  
   582  func touch(t *testing.T, name string) {
   583  	f, err := os.Create(name)
   584  	if err != nil {
   585  		t.Fatal(err)
   586  	}
   587  	if err := f.Close(); err != nil {
   588  		t.Fatal(err)
   589  	}
   590  }
   591  
   592  func TestWalkSkipDirOnFile(t *testing.T) {
   593  	td := t.TempDir()
   594  
   595  	if err := os.MkdirAll(filepath.Join(td, "dir"), 0755); err != nil {
   596  		t.Fatal(err)
   597  	}
   598  	touch(t, filepath.Join(td, "dir/foo1"))
   599  	touch(t, filepath.Join(td, "dir/foo2"))
   600  
   601  	sawFoo2 := false
   602  	walker := func(path string) error {
   603  		if strings.HasSuffix(path, "foo2") {
   604  			sawFoo2 = true
   605  		}
   606  		if strings.HasSuffix(path, "foo1") {
   607  			return filepath.SkipDir
   608  		}
   609  		return nil
   610  	}
   611  	walkFn := func(path string, _ fs.FileInfo, _ error) error { return walker(path) }
   612  	walkDirFn := func(path string, _ fs.DirEntry, _ error) error { return walker(path) }
   613  
   614  	check := func(t *testing.T, walk func(root string) error, root string) {
   615  		t.Helper()
   616  		sawFoo2 = false
   617  		err := walk(root)
   618  		if err != nil {
   619  			t.Fatal(err)
   620  		}
   621  		if sawFoo2 {
   622  			t.Errorf("SkipDir on file foo1 did not block processing of foo2")
   623  		}
   624  	}
   625  
   626  	t.Run("Walk", func(t *testing.T) {
   627  		Walk := func(root string) error { return filepath.Walk(td, walkFn) }
   628  		check(t, Walk, td)
   629  		check(t, Walk, filepath.Join(td, "dir"))
   630  	})
   631  	t.Run("WalkDir", func(t *testing.T) {
   632  		WalkDir := func(root string) error { return filepath.WalkDir(td, walkDirFn) }
   633  		check(t, WalkDir, td)
   634  		check(t, WalkDir, filepath.Join(td, "dir"))
   635  	})
   636  }
   637  
   638  func TestWalkFileError(t *testing.T) {
   639  	td := t.TempDir()
   640  
   641  	touch(t, filepath.Join(td, "foo"))
   642  	touch(t, filepath.Join(td, "bar"))
   643  	dir := filepath.Join(td, "dir")
   644  	if err := os.MkdirAll(filepath.Join(td, "dir"), 0755); err != nil {
   645  		t.Fatal(err)
   646  	}
   647  	touch(t, filepath.Join(dir, "baz"))
   648  	touch(t, filepath.Join(dir, "stat-error"))
   649  	defer func() {
   650  		*filepath.LstatP = os.Lstat
   651  	}()
   652  	statErr := errors.New("some stat error")
   653  	*filepath.LstatP = func(path string) (fs.FileInfo, error) {
   654  		if strings.HasSuffix(path, "stat-error") {
   655  			return nil, statErr
   656  		}
   657  		return os.Lstat(path)
   658  	}
   659  	got := map[string]error{}
   660  	err := filepath.Walk(td, func(path string, fi fs.FileInfo, err error) error {
   661  		rel, _ := filepath.Rel(td, path)
   662  		got[filepath.ToSlash(rel)] = err
   663  		return nil
   664  	})
   665  	if err != nil {
   666  		t.Errorf("Walk error: %v", err)
   667  	}
   668  	want := map[string]error{
   669  		".":              nil,
   670  		"foo":            nil,
   671  		"bar":            nil,
   672  		"dir":            nil,
   673  		"dir/baz":        nil,
   674  		"dir/stat-error": statErr,
   675  	}
   676  	if !reflect.DeepEqual(got, want) {
   677  		t.Errorf("Walked %#v; want %#v", got, want)
   678  	}
   679  }
   680  
   681  var basetests = []PathTest{
   682  	{"", "."},
   683  	{".", "."},
   684  	{"/.", "."},
   685  	{"/", "/"},
   686  	{"////", "/"},
   687  	{"x/", "x"},
   688  	{"abc", "abc"},
   689  	{"abc/def", "def"},
   690  	{"a/b/.x", ".x"},
   691  	{"a/b/c.", "c."},
   692  	{"a/b/c.x", "c.x"},
   693  }
   694  
   695  var winbasetests = []PathTest{
   696  	{`c:\`, `\`},
   697  	{`c:.`, `.`},
   698  	{`c:\a\b`, `b`},
   699  	{`c:a\b`, `b`},
   700  	{`c:a\b\c`, `c`},
   701  	{`\\host\share\`, `\`},
   702  	{`\\host\share\a`, `a`},
   703  	{`\\host\share\a\b`, `b`},
   704  }
   705  
   706  func TestBase(t *testing.T) {
   707  	tests := basetests
   708  	if runtime.GOOS == "windows" {
   709  		// make unix tests work on windows
   710  		for i := range tests {
   711  			tests[i].result = filepath.Clean(tests[i].result)
   712  		}
   713  		// add windows specific tests
   714  		tests = append(tests, winbasetests...)
   715  	}
   716  	for _, test := range tests {
   717  		if s := filepath.Base(test.path); s != test.result {
   718  			t.Errorf("Base(%q) = %q, want %q", test.path, s, test.result)
   719  		}
   720  	}
   721  }
   722  
   723  var dirtests = []PathTest{
   724  	{"", "."},
   725  	{".", "."},
   726  	{"/.", "/"},
   727  	{"/", "/"},
   728  	{"////", "/"},
   729  	{"/foo", "/"},
   730  	{"x/", "x"},
   731  	{"abc", "."},
   732  	{"abc/def", "abc"},
   733  	{"a/b/.x", "a/b"},
   734  	{"a/b/c.", "a/b"},
   735  	{"a/b/c.x", "a/b"},
   736  }
   737  
   738  var windirtests = []PathTest{
   739  	{`c:\`, `c:\`},
   740  	{`c:.`, `c:.`},
   741  	{`c:\a\b`, `c:\a`},
   742  	{`c:a\b`, `c:a`},
   743  	{`c:a\b\c`, `c:a\b`},
   744  	{`\\host\share`, `\\host\share`},
   745  	{`\\host\share\`, `\\host\share\`},
   746  	{`\\host\share\a`, `\\host\share\`},
   747  	{`\\host\share\a\b`, `\\host\share\a`},
   748  }
   749  
   750  func TestDir(t *testing.T) {
   751  	tests := dirtests
   752  	if runtime.GOOS == "windows" {
   753  		// make unix tests work on windows
   754  		for i := range tests {
   755  			tests[i].result = filepath.Clean(tests[i].result)
   756  		}
   757  		// add windows specific tests
   758  		tests = append(tests, windirtests...)
   759  	}
   760  	for _, test := range tests {
   761  		if s := filepath.Dir(test.path); s != test.result {
   762  			t.Errorf("Dir(%q) = %q, want %q", test.path, s, test.result)
   763  		}
   764  	}
   765  }
   766  
   767  type IsAbsTest struct {
   768  	path  string
   769  	isAbs bool
   770  }
   771  
   772  var isabstests = []IsAbsTest{
   773  	{"", false},
   774  	{"/", true},
   775  	{"/usr/bin/gcc", true},
   776  	{"..", false},
   777  	{"/a/../bb", true},
   778  	{".", false},
   779  	{"./", false},
   780  	{"lala", false},
   781  }
   782  
   783  var winisabstests = []IsAbsTest{
   784  	{`C:\`, true},
   785  	{`c\`, false},
   786  	{`c::`, false},
   787  	{`c:`, false},
   788  	{`/`, false},
   789  	{`\`, false},
   790  	{`\Windows`, false},
   791  	{`c:a\b`, false},
   792  	{`c:\a\b`, true},
   793  	{`c:/a/b`, true},
   794  	{`\\host\share`, true},
   795  	{`\\host\share\`, true},
   796  	{`\\host\share\foo`, true},
   797  	{`//host/share/foo/bar`, true},
   798  }
   799  
   800  func TestIsAbs(t *testing.T) {
   801  	var tests []IsAbsTest
   802  	if runtime.GOOS == "windows" {
   803  		tests = append(tests, winisabstests...)
   804  		// All non-windows tests should fail, because they have no volume letter.
   805  		for _, test := range isabstests {
   806  			tests = append(tests, IsAbsTest{test.path, false})
   807  		}
   808  		// All non-windows test should work as intended if prefixed with volume letter.
   809  		for _, test := range isabstests {
   810  			tests = append(tests, IsAbsTest{"c:" + test.path, test.isAbs})
   811  		}
   812  		// Test reserved names.
   813  		tests = append(tests, IsAbsTest{os.DevNull, true})
   814  		tests = append(tests, IsAbsTest{"NUL", true})
   815  		tests = append(tests, IsAbsTest{"nul", true})
   816  		tests = append(tests, IsAbsTest{"CON", true})
   817  	} else {
   818  		tests = isabstests
   819  	}
   820  
   821  	for _, test := range tests {
   822  		if r := filepath.IsAbs(test.path); r != test.isAbs {
   823  			t.Errorf("IsAbs(%q) = %v, want %v", test.path, r, test.isAbs)
   824  		}
   825  	}
   826  }
   827  
   828  type EvalSymlinksTest struct {
   829  	// If dest is empty, the path is created; otherwise the dest is symlinked to the path.
   830  	path, dest string
   831  }
   832  
   833  var EvalSymlinksTestDirs = []EvalSymlinksTest{
   834  	{"test", ""},
   835  	{"test/dir", ""},
   836  	{"test/dir/link3", "../../"},
   837  	{"test/link1", "../test"},
   838  	{"test/link2", "dir"},
   839  	{"test/linkabs", "/"},
   840  	{"test/link4", "../test2"},
   841  	{"test2", "test/dir"},
   842  	// Issue 23444.
   843  	{"src", ""},
   844  	{"src/pool", ""},
   845  	{"src/pool/test", ""},
   846  	{"src/versions", ""},
   847  	{"src/versions/current", "../../version"},
   848  	{"src/versions/v1", ""},
   849  	{"src/versions/v1/modules", ""},
   850  	{"src/versions/v1/modules/test", "../../../pool/test"},
   851  	{"version", "src/versions/v1"},
   852  }
   853  
   854  var EvalSymlinksTests = []EvalSymlinksTest{
   855  	{"test", "test"},
   856  	{"test/dir", "test/dir"},
   857  	{"test/dir/../..", "."},
   858  	{"test/link1", "test"},
   859  	{"test/link2", "test/dir"},
   860  	{"test/link1/dir", "test/dir"},
   861  	{"test/link2/..", "test"},
   862  	{"test/dir/link3", "."},
   863  	{"test/link2/link3/test", "test"},
   864  	{"test/linkabs", "/"},
   865  	{"test/link4/..", "test"},
   866  	{"src/versions/current/modules/test", "src/pool/test"},
   867  }
   868  
   869  // simpleJoin builds a file name from the directory and path.
   870  // It does not use Join because we don't want ".." to be evaluated.
   871  func simpleJoin(dir, path string) string {
   872  	return dir + string(filepath.Separator) + path
   873  }
   874  
   875  func testEvalSymlinks(t *testing.T, path, want string) {
   876  	have, err := filepath.EvalSymlinks(path)
   877  	if err != nil {
   878  		t.Errorf("EvalSymlinks(%q) error: %v", path, err)
   879  		return
   880  	}
   881  	if filepath.Clean(have) != filepath.Clean(want) {
   882  		t.Errorf("EvalSymlinks(%q) returns %q, want %q", path, have, want)
   883  	}
   884  }
   885  
   886  func testEvalSymlinksAfterChdir(t *testing.T, wd, path, want string) {
   887  	cwd, err := os.Getwd()
   888  	if err != nil {
   889  		t.Fatal(err)
   890  	}
   891  	defer func() {
   892  		err := os.Chdir(cwd)
   893  		if err != nil {
   894  			t.Fatal(err)
   895  		}
   896  	}()
   897  
   898  	err = os.Chdir(wd)
   899  	if err != nil {
   900  		t.Fatal(err)
   901  	}
   902  
   903  	have, err := filepath.EvalSymlinks(path)
   904  	if err != nil {
   905  		t.Errorf("EvalSymlinks(%q) in %q directory error: %v", path, wd, err)
   906  		return
   907  	}
   908  	if filepath.Clean(have) != filepath.Clean(want) {
   909  		t.Errorf("EvalSymlinks(%q) in %q directory returns %q, want %q", path, wd, have, want)
   910  	}
   911  }
   912  
   913  func TestEvalSymlinks(t *testing.T) {
   914  	testenv.MustHaveSymlink(t)
   915  
   916  	tmpDir := t.TempDir()
   917  
   918  	// /tmp may itself be a symlink! Avoid the confusion, although
   919  	// it means trusting the thing we're testing.
   920  	var err error
   921  	tmpDir, err = filepath.EvalSymlinks(tmpDir)
   922  	if err != nil {
   923  		t.Fatal("eval symlink for tmp dir:", err)
   924  	}
   925  
   926  	// Create the symlink farm using relative paths.
   927  	for _, d := range EvalSymlinksTestDirs {
   928  		var err error
   929  		path := simpleJoin(tmpDir, d.path)
   930  		if d.dest == "" {
   931  			err = os.Mkdir(path, 0755)
   932  		} else {
   933  			err = os.Symlink(d.dest, path)
   934  		}
   935  		if err != nil {
   936  			t.Fatal(err)
   937  		}
   938  	}
   939  
   940  	// Evaluate the symlink farm.
   941  	for _, test := range EvalSymlinksTests {
   942  		path := simpleJoin(tmpDir, test.path)
   943  
   944  		dest := simpleJoin(tmpDir, test.dest)
   945  		if filepath.IsAbs(test.dest) || os.IsPathSeparator(test.dest[0]) {
   946  			dest = test.dest
   947  		}
   948  		testEvalSymlinks(t, path, dest)
   949  
   950  		// test EvalSymlinks(".")
   951  		testEvalSymlinksAfterChdir(t, path, ".", ".")
   952  
   953  		// test EvalSymlinks("C:.") on Windows
   954  		if runtime.GOOS == "windows" {
   955  			volDot := filepath.VolumeName(tmpDir) + "."
   956  			testEvalSymlinksAfterChdir(t, path, volDot, volDot)
   957  		}
   958  
   959  		// test EvalSymlinks(".."+path)
   960  		dotdotPath := simpleJoin("..", test.dest)
   961  		if filepath.IsAbs(test.dest) || os.IsPathSeparator(test.dest[0]) {
   962  			dotdotPath = test.dest
   963  		}
   964  		testEvalSymlinksAfterChdir(t,
   965  			simpleJoin(tmpDir, "test"),
   966  			simpleJoin("..", test.path),
   967  			dotdotPath)
   968  
   969  		// test EvalSymlinks(p) where p is relative path
   970  		testEvalSymlinksAfterChdir(t, tmpDir, test.path, test.dest)
   971  	}
   972  }
   973  
   974  func TestEvalSymlinksIsNotExist(t *testing.T) {
   975  	testenv.MustHaveSymlink(t)
   976  
   977  	defer chtmpdir(t)()
   978  
   979  	_, err := filepath.EvalSymlinks("notexist")
   980  	if !os.IsNotExist(err) {
   981  		t.Errorf("expected the file is not found, got %v\n", err)
   982  	}
   983  
   984  	err = os.Symlink("notexist", "link")
   985  	if err != nil {
   986  		t.Fatal(err)
   987  	}
   988  	defer os.Remove("link")
   989  
   990  	_, err = filepath.EvalSymlinks("link")
   991  	if !os.IsNotExist(err) {
   992  		t.Errorf("expected the file is not found, got %v\n", err)
   993  	}
   994  }
   995  
   996  func TestIssue13582(t *testing.T) {
   997  	testenv.MustHaveSymlink(t)
   998  
   999  	tmpDir := t.TempDir()
  1000  
  1001  	dir := filepath.Join(tmpDir, "dir")
  1002  	err := os.Mkdir(dir, 0755)
  1003  	if err != nil {
  1004  		t.Fatal(err)
  1005  	}
  1006  	linkToDir := filepath.Join(tmpDir, "link_to_dir")
  1007  	err = os.Symlink(dir, linkToDir)
  1008  	if err != nil {
  1009  		t.Fatal(err)
  1010  	}
  1011  	file := filepath.Join(linkToDir, "file")
  1012  	err = os.WriteFile(file, nil, 0644)
  1013  	if err != nil {
  1014  		t.Fatal(err)
  1015  	}
  1016  	link1 := filepath.Join(linkToDir, "link1")
  1017  	err = os.Symlink(file, link1)
  1018  	if err != nil {
  1019  		t.Fatal(err)
  1020  	}
  1021  	link2 := filepath.Join(linkToDir, "link2")
  1022  	err = os.Symlink(link1, link2)
  1023  	if err != nil {
  1024  		t.Fatal(err)
  1025  	}
  1026  
  1027  	// /tmp may itself be a symlink!
  1028  	realTmpDir, err := filepath.EvalSymlinks(tmpDir)
  1029  	if err != nil {
  1030  		t.Fatal(err)
  1031  	}
  1032  	realDir := filepath.Join(realTmpDir, "dir")
  1033  	realFile := filepath.Join(realDir, "file")
  1034  
  1035  	tests := []struct {
  1036  		path, want string
  1037  	}{
  1038  		{dir, realDir},
  1039  		{linkToDir, realDir},
  1040  		{file, realFile},
  1041  		{link1, realFile},
  1042  		{link2, realFile},
  1043  	}
  1044  	for i, test := range tests {
  1045  		have, err := filepath.EvalSymlinks(test.path)
  1046  		if err != nil {
  1047  			t.Fatal(err)
  1048  		}
  1049  		if have != test.want {
  1050  			t.Errorf("test#%d: EvalSymlinks(%q) returns %q, want %q", i, test.path, have, test.want)
  1051  		}
  1052  	}
  1053  }
  1054  
  1055  // Test directories relative to temporary directory.
  1056  // The tests are run in absTestDirs[0].
  1057  var absTestDirs = []string{
  1058  	"a",
  1059  	"a/b",
  1060  	"a/b/c",
  1061  }
  1062  
  1063  // Test paths relative to temporary directory. $ expands to the directory.
  1064  // The tests are run in absTestDirs[0].
  1065  // We create absTestDirs first.
  1066  var absTests = []string{
  1067  	".",
  1068  	"b",
  1069  	"b/",
  1070  	"../a",
  1071  	"../a/b",
  1072  	"../a/b/./c/../../.././a",
  1073  	"../a/b/./c/../../.././a/",
  1074  	"$",
  1075  	"$/.",
  1076  	"$/a/../a/b",
  1077  	"$/a/b/c/../../.././a",
  1078  	"$/a/b/c/../../.././a/",
  1079  }
  1080  
  1081  func TestAbs(t *testing.T) {
  1082  	root := t.TempDir()
  1083  	wd, err := os.Getwd()
  1084  	if err != nil {
  1085  		t.Fatal("getwd failed: ", err)
  1086  	}
  1087  	err = os.Chdir(root)
  1088  	if err != nil {
  1089  		t.Fatal("chdir failed: ", err)
  1090  	}
  1091  	defer os.Chdir(wd)
  1092  
  1093  	for _, dir := range absTestDirs {
  1094  		err = os.Mkdir(dir, 0777)
  1095  		if err != nil {
  1096  			t.Fatal("Mkdir failed: ", err)
  1097  		}
  1098  	}
  1099  
  1100  	if runtime.GOOS == "windows" {
  1101  		vol := filepath.VolumeName(root)
  1102  		var extra []string
  1103  		for _, path := range absTests {
  1104  			if strings.Contains(path, "$") {
  1105  				continue
  1106  			}
  1107  			path = vol + path
  1108  			extra = append(extra, path)
  1109  		}
  1110  		absTests = append(absTests, extra...)
  1111  	}
  1112  
  1113  	err = os.Chdir(absTestDirs[0])
  1114  	if err != nil {
  1115  		t.Fatal("chdir failed: ", err)
  1116  	}
  1117  
  1118  	for _, path := range absTests {
  1119  		path = strings.ReplaceAll(path, "$", root)
  1120  		info, err := os.Stat(path)
  1121  		if err != nil {
  1122  			t.Errorf("%s: %s", path, err)
  1123  			continue
  1124  		}
  1125  
  1126  		abspath, err := filepath.Abs(path)
  1127  		if err != nil {
  1128  			t.Errorf("Abs(%q) error: %v", path, err)
  1129  			continue
  1130  		}
  1131  		absinfo, err := os.Stat(abspath)
  1132  		if err != nil || !os.SameFile(absinfo, info) {
  1133  			t.Errorf("Abs(%q)=%q, not the same file", path, abspath)
  1134  		}
  1135  		if !filepath.IsAbs(abspath) {
  1136  			t.Errorf("Abs(%q)=%q, not an absolute path", path, abspath)
  1137  		}
  1138  		if filepath.IsAbs(abspath) && abspath != filepath.Clean(abspath) {
  1139  			t.Errorf("Abs(%q)=%q, isn't clean", path, abspath)
  1140  		}
  1141  	}
  1142  }
  1143  
  1144  // Empty path needs to be special-cased on Windows. See golang.org/issue/24441.
  1145  // We test it separately from all other absTests because the empty string is not
  1146  // a valid path, so it can't be used with os.Stat.
  1147  func TestAbsEmptyString(t *testing.T) {
  1148  	root := t.TempDir()
  1149  
  1150  	wd, err := os.Getwd()
  1151  	if err != nil {
  1152  		t.Fatal("getwd failed: ", err)
  1153  	}
  1154  	err = os.Chdir(root)
  1155  	if err != nil {
  1156  		t.Fatal("chdir failed: ", err)
  1157  	}
  1158  	defer os.Chdir(wd)
  1159  
  1160  	info, err := os.Stat(root)
  1161  	if err != nil {
  1162  		t.Fatalf("%s: %s", root, err)
  1163  	}
  1164  
  1165  	abspath, err := filepath.Abs("")
  1166  	if err != nil {
  1167  		t.Fatalf(`Abs("") error: %v`, err)
  1168  	}
  1169  	absinfo, err := os.Stat(abspath)
  1170  	if err != nil || !os.SameFile(absinfo, info) {
  1171  		t.Errorf(`Abs("")=%q, not the same file`, abspath)
  1172  	}
  1173  	if !filepath.IsAbs(abspath) {
  1174  		t.Errorf(`Abs("")=%q, not an absolute path`, abspath)
  1175  	}
  1176  	if filepath.IsAbs(abspath) && abspath != filepath.Clean(abspath) {
  1177  		t.Errorf(`Abs("")=%q, isn't clean`, abspath)
  1178  	}
  1179  }
  1180  
  1181  type RelTests struct {
  1182  	root, path, want string
  1183  }
  1184  
  1185  var reltests = []RelTests{
  1186  	{"a/b", "a/b", "."},
  1187  	{"a/b/.", "a/b", "."},
  1188  	{"a/b", "a/b/.", "."},
  1189  	{"./a/b", "a/b", "."},
  1190  	{"a/b", "./a/b", "."},
  1191  	{"ab/cd", "ab/cde", "../cde"},
  1192  	{"ab/cd", "ab/c", "../c"},
  1193  	{"a/b", "a/b/c/d", "c/d"},
  1194  	{"a/b", "a/b/../c", "../c"},
  1195  	{"a/b/../c", "a/b", "../b"},
  1196  	{"a/b/c", "a/c/d", "../../c/d"},
  1197  	{"a/b", "c/d", "../../c/d"},
  1198  	{"a/b/c/d", "a/b", "../.."},
  1199  	{"a/b/c/d", "a/b/", "../.."},
  1200  	{"a/b/c/d/", "a/b", "../.."},
  1201  	{"a/b/c/d/", "a/b/", "../.."},
  1202  	{"../../a/b", "../../a/b/c/d", "c/d"},
  1203  	{"/a/b", "/a/b", "."},
  1204  	{"/a/b/.", "/a/b", "."},
  1205  	{"/a/b", "/a/b/.", "."},
  1206  	{"/ab/cd", "/ab/cde", "../cde"},
  1207  	{"/ab/cd", "/ab/c", "../c"},
  1208  	{"/a/b", "/a/b/c/d", "c/d"},
  1209  	{"/a/b", "/a/b/../c", "../c"},
  1210  	{"/a/b/../c", "/a/b", "../b"},
  1211  	{"/a/b/c", "/a/c/d", "../../c/d"},
  1212  	{"/a/b", "/c/d", "../../c/d"},
  1213  	{"/a/b/c/d", "/a/b", "../.."},
  1214  	{"/a/b/c/d", "/a/b/", "../.."},
  1215  	{"/a/b/c/d/", "/a/b", "../.."},
  1216  	{"/a/b/c/d/", "/a/b/", "../.."},
  1217  	{"/../../a/b", "/../../a/b/c/d", "c/d"},
  1218  	{".", "a/b", "a/b"},
  1219  	{".", "..", ".."},
  1220  
  1221  	// can't do purely lexically
  1222  	{"..", ".", "err"},
  1223  	{"..", "a", "err"},
  1224  	{"../..", "..", "err"},
  1225  	{"a", "/a", "err"},
  1226  	{"/a", "a", "err"},
  1227  }
  1228  
  1229  var winreltests = []RelTests{
  1230  	{`C:a\b\c`, `C:a/b/d`, `..\d`},
  1231  	{`C:\`, `D:\`, `err`},
  1232  	{`C:`, `D:`, `err`},
  1233  	{`C:\Projects`, `c:\projects\src`, `src`},
  1234  	{`C:\Projects`, `c:\projects`, `.`},
  1235  	{`C:\Projects\a\..`, `c:\projects`, `.`},
  1236  	{`\\host\share`, `\\host\share\file.txt`, `file.txt`},
  1237  }
  1238  
  1239  func TestRel(t *testing.T) {
  1240  	tests := append([]RelTests{}, reltests...)
  1241  	if runtime.GOOS == "windows" {
  1242  		for i := range tests {
  1243  			tests[i].want = filepath.FromSlash(tests[i].want)
  1244  		}
  1245  		tests = append(tests, winreltests...)
  1246  	}
  1247  	for _, test := range tests {
  1248  		got, err := filepath.Rel(test.root, test.path)
  1249  		if test.want == "err" {
  1250  			if err == nil {
  1251  				t.Errorf("Rel(%q, %q)=%q, want error", test.root, test.path, got)
  1252  			}
  1253  			continue
  1254  		}
  1255  		if err != nil {
  1256  			t.Errorf("Rel(%q, %q): want %q, got error: %s", test.root, test.path, test.want, err)
  1257  		}
  1258  		if got != test.want {
  1259  			t.Errorf("Rel(%q, %q)=%q, want %q", test.root, test.path, got, test.want)
  1260  		}
  1261  	}
  1262  }
  1263  
  1264  type VolumeNameTest struct {
  1265  	path string
  1266  	vol  string
  1267  }
  1268  
  1269  var volumenametests = []VolumeNameTest{
  1270  	{`c:/foo/bar`, `c:`},
  1271  	{`c:`, `c:`},
  1272  	{`2:`, ``},
  1273  	{``, ``},
  1274  	{`\\\host`, ``},
  1275  	{`\\\host\`, ``},
  1276  	{`\\\host\share`, ``},
  1277  	{`\\\host\\share`, ``},
  1278  	{`\\host`, ``},
  1279  	{`//host`, ``},
  1280  	{`\\host\`, ``},
  1281  	{`//host/`, ``},
  1282  	{`\\host\share`, `\\host\share`},
  1283  	{`//host/share`, `//host/share`},
  1284  	{`\\host\share\`, `\\host\share`},
  1285  	{`//host/share/`, `//host/share`},
  1286  	{`\\host\share\foo`, `\\host\share`},
  1287  	{`//host/share/foo`, `//host/share`},
  1288  	{`\\host\share\\foo\\\bar\\\\baz`, `\\host\share`},
  1289  	{`//host/share//foo///bar////baz`, `//host/share`},
  1290  	{`\\host\share\foo\..\bar`, `\\host\share`},
  1291  	{`//host/share/foo/../bar`, `//host/share`},
  1292  }
  1293  
  1294  func TestVolumeName(t *testing.T) {
  1295  	if runtime.GOOS != "windows" {
  1296  		return
  1297  	}
  1298  	for _, v := range volumenametests {
  1299  		if vol := filepath.VolumeName(v.path); vol != v.vol {
  1300  			t.Errorf("VolumeName(%q)=%q, want %q", v.path, vol, v.vol)
  1301  		}
  1302  	}
  1303  }
  1304  
  1305  func TestDriveLetterInEvalSymlinks(t *testing.T) {
  1306  	if runtime.GOOS != "windows" {
  1307  		return
  1308  	}
  1309  	wd, _ := os.Getwd()
  1310  	if len(wd) < 3 {
  1311  		t.Errorf("Current directory path %q is too short", wd)
  1312  	}
  1313  	lp := strings.ToLower(wd)
  1314  	up := strings.ToUpper(wd)
  1315  	flp, err := filepath.EvalSymlinks(lp)
  1316  	if err != nil {
  1317  		t.Fatalf("EvalSymlinks(%q) failed: %q", lp, err)
  1318  	}
  1319  	fup, err := filepath.EvalSymlinks(up)
  1320  	if err != nil {
  1321  		t.Fatalf("EvalSymlinks(%q) failed: %q", up, err)
  1322  	}
  1323  	if flp != fup {
  1324  		t.Errorf("Results of EvalSymlinks do not match: %q and %q", flp, fup)
  1325  	}
  1326  }
  1327  
  1328  func TestBug3486(t *testing.T) { // https://golang.org/issue/3486
  1329  	if runtime.GOOS == "ios" {
  1330  		t.Skipf("skipping on %s/%s", runtime.GOOS, runtime.GOARCH)
  1331  	}
  1332  	root, err := filepath.EvalSymlinks(runtime.GOROOT() + "/test")
  1333  	if err != nil {
  1334  		t.Fatal(err)
  1335  	}
  1336  	bugs := filepath.Join(root, "fixedbugs")
  1337  	ken := filepath.Join(root, "ken")
  1338  	seenBugs := false
  1339  	seenKen := false
  1340  	err = filepath.Walk(root, func(pth string, info fs.FileInfo, err error) error {
  1341  		if err != nil {
  1342  			t.Fatal(err)
  1343  		}
  1344  
  1345  		switch pth {
  1346  		case bugs:
  1347  			seenBugs = true
  1348  			return filepath.SkipDir
  1349  		case ken:
  1350  			if !seenBugs {
  1351  				t.Fatal("filepath.Walk out of order - ken before fixedbugs")
  1352  			}
  1353  			seenKen = true
  1354  		}
  1355  		return nil
  1356  	})
  1357  	if err != nil {
  1358  		t.Fatal(err)
  1359  	}
  1360  	if !seenKen {
  1361  		t.Fatalf("%q not seen", ken)
  1362  	}
  1363  }
  1364  
  1365  func testWalkSymlink(t *testing.T, mklink func(target, link string) error) {
  1366  	tmpdir := t.TempDir()
  1367  
  1368  	wd, err := os.Getwd()
  1369  	if err != nil {
  1370  		t.Fatal(err)
  1371  	}
  1372  	defer os.Chdir(wd)
  1373  
  1374  	err = os.Chdir(tmpdir)
  1375  	if err != nil {
  1376  		t.Fatal(err)
  1377  	}
  1378  
  1379  	err = mklink(tmpdir, "link")
  1380  	if err != nil {
  1381  		t.Fatal(err)
  1382  	}
  1383  
  1384  	var visited []string
  1385  	err = filepath.Walk(tmpdir, func(path string, info fs.FileInfo, err error) error {
  1386  		if err != nil {
  1387  			t.Fatal(err)
  1388  		}
  1389  		rel, err := filepath.Rel(tmpdir, path)
  1390  		if err != nil {
  1391  			t.Fatal(err)
  1392  		}
  1393  		visited = append(visited, rel)
  1394  		return nil
  1395  	})
  1396  	if err != nil {
  1397  		t.Fatal(err)
  1398  	}
  1399  	sort.Strings(visited)
  1400  	want := []string{".", "link"}
  1401  	if fmt.Sprintf("%q", visited) != fmt.Sprintf("%q", want) {
  1402  		t.Errorf("unexpected paths visited %q, want %q", visited, want)
  1403  	}
  1404  }
  1405  
  1406  func TestWalkSymlink(t *testing.T) {
  1407  	testenv.MustHaveSymlink(t)
  1408  	testWalkSymlink(t, os.Symlink)
  1409  }
  1410  
  1411  func TestIssue29372(t *testing.T) {
  1412  	tmpDir := t.TempDir()
  1413  
  1414  	path := filepath.Join(tmpDir, "file.txt")
  1415  	err := os.WriteFile(path, nil, 0644)
  1416  	if err != nil {
  1417  		t.Fatal(err)
  1418  	}
  1419  
  1420  	pathSeparator := string(filepath.Separator)
  1421  	tests := []string{
  1422  		path + strings.Repeat(pathSeparator, 1),
  1423  		path + strings.Repeat(pathSeparator, 2),
  1424  		path + strings.Repeat(pathSeparator, 1) + ".",
  1425  		path + strings.Repeat(pathSeparator, 2) + ".",
  1426  		path + strings.Repeat(pathSeparator, 1) + "..",
  1427  		path + strings.Repeat(pathSeparator, 2) + "..",
  1428  	}
  1429  
  1430  	for i, test := range tests {
  1431  		_, err = filepath.EvalSymlinks(test)
  1432  		if err != syscall.ENOTDIR {
  1433  			t.Fatalf("test#%d: want %q, got %q", i, syscall.ENOTDIR, err)
  1434  		}
  1435  	}
  1436  }
  1437  
  1438  // Issue 30520 part 1.
  1439  func TestEvalSymlinksAboveRoot(t *testing.T) {
  1440  	testenv.MustHaveSymlink(t)
  1441  
  1442  	t.Parallel()
  1443  
  1444  	tmpDir := t.TempDir()
  1445  
  1446  	evalTmpDir, err := filepath.EvalSymlinks(tmpDir)
  1447  	if err != nil {
  1448  		t.Fatal(err)
  1449  	}
  1450  
  1451  	if err := os.Mkdir(filepath.Join(evalTmpDir, "a"), 0777); err != nil {
  1452  		t.Fatal(err)
  1453  	}
  1454  	if err := os.Symlink(filepath.Join(evalTmpDir, "a"), filepath.Join(evalTmpDir, "b")); err != nil {
  1455  		t.Fatal(err)
  1456  	}
  1457  	if err := os.WriteFile(filepath.Join(evalTmpDir, "a", "file"), nil, 0666); err != nil {
  1458  		t.Fatal(err)
  1459  	}
  1460  
  1461  	// Count the number of ".." elements to get to the root directory.
  1462  	vol := filepath.VolumeName(evalTmpDir)
  1463  	c := strings.Count(evalTmpDir[len(vol):], string(os.PathSeparator))
  1464  	var dd []string
  1465  	for i := 0; i < c+2; i++ {
  1466  		dd = append(dd, "..")
  1467  	}
  1468  
  1469  	wantSuffix := strings.Join([]string{"a", "file"}, string(os.PathSeparator))
  1470  
  1471  	// Try different numbers of "..".
  1472  	for _, i := range []int{c, c + 1, c + 2} {
  1473  		check := strings.Join([]string{evalTmpDir, strings.Join(dd[:i], string(os.PathSeparator)), evalTmpDir[len(vol)+1:], "b", "file"}, string(os.PathSeparator))
  1474  		resolved, err := filepath.EvalSymlinks(check)
  1475  		switch {
  1476  		case runtime.GOOS == "darwin" && errors.Is(err, fs.ErrNotExist):
  1477  			// On darwin, the temp dir is sometimes cleaned up mid-test (issue 37910).
  1478  			testenv.SkipFlaky(t, 37910)
  1479  		case err != nil:
  1480  			t.Errorf("EvalSymlinks(%q) failed: %v", check, err)
  1481  		case !strings.HasSuffix(resolved, wantSuffix):
  1482  			t.Errorf("EvalSymlinks(%q) = %q does not end with %q", check, resolved, wantSuffix)
  1483  		default:
  1484  			t.Logf("EvalSymlinks(%q) = %q", check, resolved)
  1485  		}
  1486  	}
  1487  }
  1488  
  1489  // Issue 30520 part 2.
  1490  func TestEvalSymlinksAboveRootChdir(t *testing.T) {
  1491  	testenv.MustHaveSymlink(t)
  1492  
  1493  	tmpDir, err := os.MkdirTemp("", "TestEvalSymlinksAboveRootChdir")
  1494  	if err != nil {
  1495  		t.Fatal(err)
  1496  	}
  1497  	defer os.RemoveAll(tmpDir)
  1498  	chdir(t, tmpDir)
  1499  
  1500  	subdir := filepath.Join("a", "b")
  1501  	if err := os.MkdirAll(subdir, 0777); err != nil {
  1502  		t.Fatal(err)
  1503  	}
  1504  	if err := os.Symlink(subdir, "c"); err != nil {
  1505  		t.Fatal(err)
  1506  	}
  1507  	if err := os.WriteFile(filepath.Join(subdir, "file"), nil, 0666); err != nil {
  1508  		t.Fatal(err)
  1509  	}
  1510  
  1511  	subdir = filepath.Join("d", "e", "f")
  1512  	if err := os.MkdirAll(subdir, 0777); err != nil {
  1513  		t.Fatal(err)
  1514  	}
  1515  	if err := os.Chdir(subdir); err != nil {
  1516  		t.Fatal(err)
  1517  	}
  1518  
  1519  	check := filepath.Join("..", "..", "..", "c", "file")
  1520  	wantSuffix := filepath.Join("a", "b", "file")
  1521  	if resolved, err := filepath.EvalSymlinks(check); err != nil {
  1522  		t.Errorf("EvalSymlinks(%q) failed: %v", check, err)
  1523  	} else if !strings.HasSuffix(resolved, wantSuffix) {
  1524  		t.Errorf("EvalSymlinks(%q) = %q does not end with %q", check, resolved, wantSuffix)
  1525  	} else {
  1526  		t.Logf("EvalSymlinks(%q) = %q", check, resolved)
  1527  	}
  1528  }
  1529  

View as plain text