Skip to content

Commit

Permalink
✨ up(fs): add new util func PathMatch for match path
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Mar 16, 2023
1 parent 9c81ef3 commit 86abf8e
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
9 changes: 9 additions & 0 deletions fsutil/check.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,3 +120,12 @@ func IsZipFile(filepath string) bool {

return bytes.Equal(buf, []byte("PK\x03\x04"))
}

// PathMatch check for a string.
func PathMatch(pattern, s string) bool {
ok, err := path.Match(pattern, s)
if err != nil {
ok = false
}
return ok
}
24 changes: 24 additions & 0 deletions fsutil/check_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ func TestFsUtil_common(t *testing.T) {
assert.Eq(t, "jpg", fsutil.Extname("testdata/test.jpg"))

// IsZipFile
assert.False(t, fsutil.IsZipFile("testdata/not-exists-file"))
assert.False(t, fsutil.IsZipFile("testdata/test.jpg"))
assert.Eq(t, "test.jpg", fsutil.PathName("testdata/test.jpg"))

Expand Down Expand Up @@ -59,3 +60,26 @@ func TestIsAbsPath(t *testing.T) {
assert.True(t, fsutil.IsAbsPath("/data/some.txt"))
assert.NoErr(t, fsutil.DeleteIfFileExist("/not-exist"))
}

func TestGlobMatch(t *testing.T) {
tests := []struct {
p, s string
want bool
}{
{"a*", "abc", true},
{"ab.*.ef", "ab.cd.ef", true},
{"ab.*.*", "ab.cd.ef", true},
{"ab.cd.*", "ab.cd.ef", true},
{"ab.*", "ab.cd.ef", true},
{"a*/b", "a/c/b", false},
{"a*", "a/c/b", false},
{"a**", "a/c/b", false},
}

for _, tt := range tests {
assert.Eq(t, tt.want, fsutil.PathMatch(tt.p, tt.s), "case %v", tt)
}

assert.False(t, fsutil.PathMatch("ab", "abc"))
assert.True(t, fsutil.PathMatch("ab*", "abc"))
}
1 change: 1 addition & 0 deletions fsutil/fsutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ func TestMimeType(t *testing.T) {
buf.Reset()

assert.True(t, fsutil.IsImageFile("testdata/test.jpg"))
assert.True(t, fsutil.IsImageFile("testdata/not-exists"))
}

func TestTempDir(t *testing.T) {
Expand Down

0 comments on commit 86abf8e

Please sign in to comment.