From bd33eaa3b89d5ddb73032f4b388643ab723a0b9b Mon Sep 17 00:00:00 2001 From: Larpon Date: Wed, 1 Sep 2021 15:32:28 +0200 Subject: [PATCH] os: add function to expand "~" to home directory (#11362) --- vlib/os/os.v | 13 +++++++++++++ vlib/os/os_test.v | 8 ++++++++ 2 files changed, 21 insertions(+) diff --git a/vlib/os/os.v b/vlib/os/os.v index 4574156324..ffeba964a4 100644 --- a/vlib/os/os.v +++ b/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) ? diff --git a/vlib/os/os_test.v b/vlib/os/os_test.v index 2fff68ec2d..c10e0c0ab7 100644 --- a/vlib/os/os_test.v +++ b/vlib/os/os_test.v @@ -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() +}