From 6d0bf438e302afcb0db5422ea2da59d1995e08c1 Mon Sep 17 00:00:00 2001 From: Damien Neil Date: Wed, 9 Nov 2022 17:49:44 -0800 Subject: path/filepath: add IsLocal IsLocal reports whether a path lexically refers to a location contained within the directory in which it is evaluated. It identifies paths that are absolute, escape a directory with ".." elements, and (on Windows) paths that reference reserved device names. For #56219. Change-Id: I35edfa3ce77b40b8e66f1fc8e0ff73cfd06f2313 Reviewed-on: https://go-review.googlesource.com/c/go/+/449239 Run-TryBot: Damien Neil Reviewed-by: Joseph Tsai TryBot-Result: Gopher Robot Reviewed-by: Ian Lance Taylor Reviewed-by: Ian Lance Taylor Reviewed-by: Joedian Reid --- src/path/filepath/path_test.go | 54 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) (limited to 'src/path/filepath/path_test.go') diff --git a/src/path/filepath/path_test.go b/src/path/filepath/path_test.go index 382381eb4e..771416770e 100644 --- a/src/path/filepath/path_test.go +++ b/src/path/filepath/path_test.go @@ -143,6 +143,60 @@ func TestClean(t *testing.T) { } } +type IsLocalTest struct { + path string + isLocal bool +} + +var islocaltests = []IsLocalTest{ + {"", false}, + {".", true}, + {"..", false}, + {"../a", false}, + {"/", false}, + {"/a", false}, + {"/a/../..", false}, + {"a", true}, + {"a/../a", true}, + {"a/", true}, + {"a/.", true}, + {"a/./b/./c", true}, +} + +var winislocaltests = []IsLocalTest{ + {"NUL", false}, + {"nul", false}, + {"nul.", false}, + {"nul.txt", false}, + {"com1", false}, + {"./nul", false}, + {"a/nul.txt/b", false}, + {`\`, false}, + {`\a`, false}, + {`C:`, false}, + {`C:\a`, false}, + {`..\a`, false}, +} + +var plan9islocaltests = []IsLocalTest{ + {"#a", false}, +} + +func TestIsLocal(t *testing.T) { + tests := islocaltests + if runtime.GOOS == "windows" { + tests = append(tests, winislocaltests...) + } + if runtime.GOOS == "plan9" { + tests = append(tests, plan9islocaltests...) + } + for _, test := range tests { + if got := filepath.IsLocal(test.path); got != test.isLocal { + t.Errorf("IsLocal(%q) = %v, want %v", test.path, got, test.isLocal) + } + } +} + const sep = filepath.Separator var slashtests = []PathTest{ -- cgit v1.3