Skip to content

Commit bd33eaa

Browse files
authored
os: add function to expand "~" to home directory (#11362)
1 parent 63ff569 commit bd33eaa

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

vlib/os/os.v

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -336,6 +336,19 @@ pub fn home_dir() string {
336336
}
337337
}
338338

339+
// expand_tilde_to_home expands the character `~` in `path` to the user's home directory.
340+
// See also `home_dir()`.
341+
pub fn expand_tilde_to_home(path string) string {
342+
if path == '~' {
343+
return home_dir().trim_right(path_separator)
344+
}
345+
if path.starts_with('~' + path_separator) {
346+
return path.replace_once('~' + path_separator, home_dir().trim_right(path_separator) +
347+
path_separator)
348+
}
349+
return path
350+
}
351+
339352
// write_file writes `text` data to a file in `path`.
340353
pub fn write_file(path string, text string) ? {
341354
mut f := create(path) ?

vlib/os/os_test.v

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -750,3 +750,11 @@ fn test_utime() {
750750
os.utime(filename, int(atime), int(mtime)) or { panic(err) }
751751
assert os.file_last_mod_unix(filename) == mtime
752752
}
753+
754+
fn test_expand_tilde_to_home() {
755+
home_test := os.join_path(os.home_dir(), 'test', 'tilde', 'expansion')
756+
home_expansion_test := os.expand_tilde_to_home(os.join_path('~', 'test', 'tilde',
757+
'expansion'))
758+
assert home_test == home_expansion_test
759+
assert os.expand_tilde_to_home('~') == os.home_dir()
760+
}

0 commit comments

Comments
 (0)