path.rs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. use std::{
  2. fs,
  3. path::{Path, PathBuf},
  4. };
  5. use crate::{Error, Result};
  6. pub fn expand_path(path: &str) -> Result<PathBuf> {
  7. let ret: PathBuf;
  8. if path.starts_with("~/") {
  9. let homedir = dirs::home_dir().unwrap();
  10. let remains = PathBuf::from(path.strip_prefix("~/").unwrap());
  11. ret = [homedir, remains].iter().collect();
  12. } else if path.starts_with('~') {
  13. ret = dirs::home_dir().unwrap();
  14. } else {
  15. ret = PathBuf::from(path);
  16. }
  17. Ok(ret)
  18. }
  19. pub fn join_config_path(file: &Path) -> Result<PathBuf> {
  20. let mut path = PathBuf::new();
  21. let dfi_path = Path::new("darkfi");
  22. if let Some(v) = dirs::config_dir() {
  23. path.push(v);
  24. }
  25. path.push(dfi_path);
  26. path.push(file);
  27. Ok(path)
  28. }
  29. pub fn get_config_path(arg: Option<String>, fallback: &str) -> Result<PathBuf> {
  30. if let Some(a) = arg {
  31. expand_path(&a)
  32. } else {
  33. join_config_path(&PathBuf::from(fallback))
  34. }
  35. }
  36. pub fn load_keypair_to_str(path: PathBuf) -> Result<String> {
  37. if Path::new(&path).exists() {
  38. let key = fs::read(&path)?;
  39. let str_buff = std::str::from_utf8(&key)?;
  40. Ok(str_buff.to_string())
  41. } else {
  42. println!("Could not parse keypair path");
  43. Err(Error::KeypairPathNotFound)
  44. }
  45. }