From 77d6a247858c942f9ffa7e4c8d08d270d9d94eb4 Mon Sep 17 00:00:00 2001 From: Mahad Zaryab <43658574+mahadzaryab1@users.noreply.github.com> Date: Thu, 15 Aug 2024 18:27:08 -0400 Subject: [PATCH] fix(paths): trim leading and trailing whitespaces for file system paths (#162) * Remove Leading And Trailing Whitespaces For Paths * Add Test For Leading And Trailing Whitespaces * Add More Test Cases For Whitespaces In Middle of Path --- pkg/finder/finder_test.go | 69 +++++++++++++++++++++++++++++++++++++++ pkg/finder/fsfinder.go | 4 ++- 2 files changed, 72 insertions(+), 1 deletion(-) diff --git a/pkg/finder/finder_test.go b/pkg/finder/finder_test.go index 18ae27d5..48777ac9 100644 --- a/pkg/finder/finder_test.go +++ b/pkg/finder/finder_test.go @@ -249,6 +249,75 @@ func Test_FileFinderBadPath(t *testing.T) { } } +func Test_FileFinderPathWithWhitespaces(t *testing.T) { + tests := []struct { + name string + path string + expectErr bool + }{ + { + name: "no whitespace", + path: "../../test/fixtures/subdir", + }, + { + name: "leading whitespace", + path: " ../../test/fixtures/subdir", + }, + { + name: "trailing whitespace", + path: "../../test/fixtures/subdir ", + }, + { + name: "leading and trailing whitespace", + path: " ../../test/fixtures/subdir ", + }, + { + name: "whitespace in middle of path", + path: "../../test/ fixtures /subdir", + expectErr: true, + }, + { + name: "leading whitespace + whitespace in middle of path", + path: " ../../test/ fixtures /subdir", + expectErr: true, + }, + { + name: "trailing whitespace + whitespace in middle of path", + path: "../../test/ fixtures /subdir ", + expectErr: true, + }, + { + name: "leading and trailing whitespace + whitespace in middle of path", + path: " ../../test/ fixtures /subdir ", + expectErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + fsFinder := FileSystemFinderInit( + WithPathRoots(tt.path), + ) + + files, err := fsFinder.Find() + + if tt.expectErr { + if err == nil { + t.Errorf("Error should be thrown for bad path") + } + } else { + if len(files) < 1 { + t.Errorf("Unable to find file") + } + + if err != nil { + t.Errorf("Unable to find file") + } + } + }) + } +} + func Benchmark_Finder(b *testing.B) { fsFinder := FileSystemFinderInit( WithPathRoots("../../test/fixtures/"), diff --git a/pkg/finder/fsfinder.go b/pkg/finder/fsfinder.go index 08bb94a3..8593863f 100644 --- a/pkg/finder/fsfinder.go +++ b/pkg/finder/fsfinder.go @@ -81,7 +81,9 @@ func (fsf FileSystemFinder) Find() ([]FileMetadata, error) { seen := make(map[string]struct{}, 0) uniqueMatches := make([]FileMetadata, 0) for _, pathRoot := range fsf.PathRoots { - matches, err := fsf.findOne(pathRoot, seen) + // remove all leading and trailing whitespace + trimmedPathRoot := strings.TrimSpace(pathRoot) + matches, err := fsf.findOne(trimmedPathRoot, seen) if err != nil { return nil, err }