Skip to content

Commit

Permalink
vlib.os: fix join-path
Browse files Browse the repository at this point in the history
Closes #20231

Co-authored-by: Turiiya <34311583+ttytm@users.noreply.github.com>
  • Loading branch information
hholst80 and ttytm committed May 5, 2024
1 parent 387af74 commit 855f1d0
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 15 deletions.
37 changes: 23 additions & 14 deletions vlib/os/os.v
Original file line number Diff line number Diff line change
Expand Up @@ -576,25 +576,34 @@ pub fn join_path(base string, dirs ...string) string {
defer {
unsafe { sb.free() }
}
sbase := base.trim_right('\\/')
defer {
unsafe { sbase.free() }
mut i := 0
mut needs_sep := false
if base != '' {
sb.write_string(base)
needs_sep = !base.ends_with(path_separator)
} else {
for i < dirs.len {
d := dirs[i]
i++
if d != '' {
sb.write_string(d)
needs_sep = !base.ends_with(path_separator)
break
}
}
}
sb.write_string(sbase)
for d in dirs {
for i < dirs.len {
d := dirs[i]
if d != '' {
sb.write_string(path_separator)
if needs_sep {
sb.write_string(path_separator)
}
sb.write_string(d)
needs_sep = !d.ends_with(path_separator)
}
i++
}
mut res := sb.str()
if sbase == '' {
res = res.trim_left(path_separator)
}
if res.contains('/./') {
// Fix `join_path("/foo/bar", "./file.txt")` => `/foo/bar/./file.txt`
res = res.replace('/./', '/')
}
res := sb.str()
return res
}

Expand Down
3 changes: 2 additions & 1 deletion vlib/os/os_test.c.v
Original file line number Diff line number Diff line change
Expand Up @@ -621,9 +621,10 @@ fn test_join() {
assert os.join_path('v', '', 'dir') == 'v\\dir'
} $else {
assert os.join_path('v', 'vlib', 'os') == 'v/vlib/os'
assert os.join_path('/foo/bar', './file.txt') == '/foo/bar/file.txt'
assert os.join_path('/foo/bar', './file.txt') == '/foo/bar/./file.txt'
assert os.join_path('', 'f1', 'f2') == 'f1/f2'
assert os.join_path('v', '', 'dir') == 'v/dir'
assert os.join_path('/', 'test') == '/test'
}
}

Expand Down

0 comments on commit 855f1d0

Please sign in to comment.