Skip to content

Commit

Permalink
os: add function to expand "~" to home directory (#11362)
Browse files Browse the repository at this point in the history
  • Loading branch information
Larpon committed Sep 1, 2021
1 parent 63ff569 commit bd33eaa
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
13 changes: 13 additions & 0 deletions vlib/os/os.v
Expand Up @@ -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) ?
Expand Down
8 changes: 8 additions & 0 deletions vlib/os/os_test.v
Expand Up @@ -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()
}

2 comments on commit bd33eaa

@islonely
Copy link
Contributor

@islonely islonely commented on bd33eaa Sep 3, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it would make more since to make os.real_path do this. Maybe make the function you have there private and call it immediately inside os.real_path? That is, if it doesn’t already do checks for tilde

@Larpon
Copy link
Contributor Author

@Larpon Larpon commented on bd33eaa Sep 5, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it would make more since to make os.real_path do this. Maybe make the function you have there private and call it immediately inside os.real_path? That is, if it doesn’t already do checks for tilde

I can see an additional benefit in adding it to real_path. But I don't think it should be private since it's not always desired to get the real path. If you're working with symlinks it's not always desired to resolve them but you want the tilde expanded

Please sign in to comment.