os: add function to expand "~" to home directory (#11362)

pull/11384/head
Larpon 2021-09-01 15:32:28 +02:00 committed by GitHub
parent 63ff5690ff
commit bd33eaa3b8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 21 additions and 0 deletions

View File

@ -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) ?

View File

@ -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()
}