1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
extern crate dirs; use dirs::home_dir; use std::path::PathBuf; use std::ffi::{OsStr, OsString}; use std::os::unix::ffi::{OsStrExt, OsStringExt}; pub trait PathBufTools { fn short_path(&self) -> PathBuf; fn short_string(&self) -> String; fn name_starts_with(&self, pat: &str) -> bool; fn quoted_file_name(&self) -> Option<OsString>; fn quoted_path(&self) -> OsString; } impl PathBufTools for PathBuf { fn short_path(&self) -> PathBuf { if let Some(home) = home_dir() { if let Ok(short) = self.strip_prefix(home) { let mut path = PathBuf::from("~"); path.push(short); return path } } return self.clone(); } fn short_string(&self) -> String { self.short_path().to_string_lossy().to_string() } fn name_starts_with(&self, pat: &str) -> bool { if let Some(name) = self.file_name() { let nbytes = name.as_bytes(); let pbytes = pat.as_bytes(); if nbytes.starts_with(pbytes) { return true; } else { return false; } } false } fn quoted_file_name(&self) -> Option<OsString> { if let Some(name) = self.file_name() { let mut name = name.as_bytes().to_vec(); let mut quote = "\"".as_bytes().to_vec(); let mut quoted = vec![]; quoted.append(&mut quote.clone()); quoted.append(&mut name); quoted.append(&mut quote); let quoted_name = OsStr::from_bytes("ed).to_os_string(); return Some(quoted_name); } None } fn quoted_path(&self) -> OsString { let mut path = self.as_os_str().to_os_string().into_vec(); let mut quote = "\"".as_bytes().to_vec(); let mut quoted = vec![]; quoted.append(&mut quote.clone()); quoted.append(&mut path); quoted.append(&mut quote); OsString::from_vec(quoted) } }