diff --git a/file.go b/file.go index 334938a..e293b0a 100644 --- a/file.go +++ b/file.go @@ -103,12 +103,47 @@ func BaseFileName(ppath string) string { if i+1 < len(ppath) { return ppath[i+1:] } - return BaseFileName(ppath[0:i]) + return `` } } return ppath } +func HasPathSeperatorPrefix(ppath string) bool { + return strings.HasPrefix(ppath, `/`) || strings.HasPrefix(ppath, `\`) +} + +func HasPathSeperatorSuffix(ppath string) bool { + return strings.HasSuffix(ppath, `/`) || strings.HasSuffix(ppath, `\`) +} + +var pathSeperatorRegex = regexp.MustCompile(`(\\|/)`) + +func GetPathSeperator(ppath string) string { + matches := pathSeperatorRegex.FindAllStringSubmatch(ppath, 1) + if len(matches) > 0 && len(matches[0]) > 1 { + return matches[0][1] + } + return `` +} + +func SplitFileDirAndName(ppath string) (dir string, name string) { + if len(ppath) == 0 { + return + } + for i := len(ppath) - 1; i >= 0; i-- { + if ppath[i] == '/' || ppath[i] == '\\' { + if i+1 < len(ppath) { + return ppath[0:i], ppath[i+1:] + } + dir = ppath[0:i] + return + } + } + name = ppath + return +} + // FileSize returns file size in bytes and possible error. func FileSize(file string) (int64, error) { f, err := os.Stat(file) diff --git a/file_test.go b/file_test.go index fc1dbec..3af8b44 100644 --- a/file_test.go +++ b/file_test.go @@ -50,7 +50,28 @@ func TestBaseFileName(t *testing.T) { r = BaseFileName(`abc\dd.txt`) assert.Equal(t, `dd.txt`, r) r = BaseFileName(`abc\dd.txt/`) - assert.Equal(t, `dd.txt`, r) + assert.Equal(t, ``, r) r = BaseFileName(`/`) assert.Equal(t, ``, r) + r = BaseFileName(`dd.txt`) + assert.Equal(t, `dd.txt`, r) +} + +func TestSplitFileDirAndName(t *testing.T) { + dir, name := SplitFileDirAndName(`abc/dd.txt`) + assert.Equal(t, `abc`, dir) + assert.Equal(t, `dd.txt`, name) + + dir, name = SplitFileDirAndName(`dd.txt`) + assert.Equal(t, ``, dir) + assert.Equal(t, `dd.txt`, name) + + dir, name = SplitFileDirAndName(`abc/`) + assert.Equal(t, `abc`, dir) + assert.Equal(t, ``, name) + + sep := GetPathSeperator(`dfefe/ffefe`) + assert.Equal(t, `/`, sep) + sep = GetPathSeperator(`dfefe\ffefe`) + assert.Equal(t, `\`, sep) }