Skip to content

Instantly share code, notes, and snippets.

@tilpner
Created February 19, 2016 17:28
Show Gist options
  • Save tilpner/b0e5423b82d38b1f9035 to your computer and use it in GitHub Desktop.
Save tilpner/b0e5423b82d38b1f9035 to your computer and use it in GitHub Desktop.
Limited tilde expansion, doesn't support ~user
use std::path::{Path, PathBuf};
use std::env;
fn expand<P: AsRef<Path>>(path: P) -> Option<PathBuf> {
let path = path.as_ref();
if path.starts_with("~") {
let mut path = path.iter();
path.next();
env::home_dir().map(|home| home.join(path))
} else {
Some(path.to_owned())
}
}
fn main() {
println!("{:?}, {:?}, {:?}",
expand("~/code"),
expand("/home/foo/code"),
expand("/home/foo/~/foo"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment