Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
admpub committed Nov 19, 2023
1 parent 96d4aac commit 74e5120
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 2 deletions.
37 changes: 36 additions & 1 deletion file.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
23 changes: 22 additions & 1 deletion file_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

0 comments on commit 74e5120

Please sign in to comment.