os: add function to expand "~" to home directory (#11362)
parent
63ff5690ff
commit
bd33eaa3b8
13
vlib/os/os.v
13
vlib/os/os.v
|
@ -336,6 +336,19 @@ pub fn home_dir() string {
|
|||
}
|
||||
}
|
||||
|
||||
// expand_tilde_to_home expands the character `~` in `path` to the user's home directory.
|
||||
// See also `home_dir()`.
|
||||
pub fn expand_tilde_to_home(path string) string {
|
||||
if path == '~' {
|
||||
return home_dir().trim_right(path_separator)
|
||||
}
|
||||
if path.starts_with('~' + path_separator) {
|
||||
return path.replace_once('~' + path_separator, home_dir().trim_right(path_separator) +
|
||||
path_separator)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
// write_file writes `text` data to a file in `path`.
|
||||
pub fn write_file(path string, text string) ? {
|
||||
mut f := create(path) ?
|
||||
|
|
|
@ -750,3 +750,11 @@ fn test_utime() {
|
|||
os.utime(filename, int(atime), int(mtime)) or { panic(err) }
|
||||
assert os.file_last_mod_unix(filename) == mtime
|
||||
}
|
||||
|
||||
fn test_expand_tilde_to_home() {
|
||||
home_test := os.join_path(os.home_dir(), 'test', 'tilde', 'expansion')
|
||||
home_expansion_test := os.expand_tilde_to_home(os.join_path('~', 'test', 'tilde',
|
||||
'expansion'))
|
||||
assert home_test == home_expansion_test
|
||||
assert os.expand_tilde_to_home('~') == os.home_dir()
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue