dotfiles_core/path.rs
1// Copyright (c) 2021-2022 Miguel Barreto and others
2//
3// Permission is hereby granted, free of charge, to any person obtaining
4// a copy of this software and associated documentation files (the
5// "Software"), to deal in the Software without restriction, including
6// without limitation the rights to use, copy, modify, merge, publish,
7// distribute, sublicense, and/or sell copies of the Software, and to
8// permit persons to whom the Software is furnished to do so, subject to
9// the following conditions:
10//
11// The above copyright notice and this permission notice shall be
12// included in all copies or substantial portions of the Software.
13//
14// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22//! Contains helpful functions to deal with paths in the context of parsing them for dotfiles
23//! configs.
24
25#[cfg(unix)]
26use home::home_dir;
27#[cfg(unix)]
28use std::path::Component;
29use std::path::{Path, PathBuf};
30
31use crate::error::{DotfilesError, ErrorType};
32
33/// Converts a file path to absolute if it is relative. If `current_dir` is provided it uses it for
34/// the base dir, otherwise it relies on [std::env::current_dir()]
35pub fn convert_path_to_absolute(
36 file_name: &Path,
37 current_dir: Option<&Path>,
38) -> Result<PathBuf, DotfilesError> {
39 let path = process_home_dir_in_path(&PathBuf::from(file_name));
40 Ok(if path.is_absolute() {
41 path
42 } else {
43 let mut new_path = current_dir.map_or_else(
44 || std::env::current_dir().map_err(DotfilesError::from_io_error),
45 |dir| Ok(dir.to_owned()),
46 )?;
47 if new_path.is_relative() {
48 return Err(DotfilesError::from(
49 format!(
50 "convert_path_to_absolute got a base dir of {} which is not absolute",
51 new_path.to_str().unwrap()
52 ),
53 ErrorType::CoreError,
54 ));
55 }
56 new_path.push(path);
57 new_path
58 })
59}
60
61/// Checks for ~ and replaces it with a home directory if necessary.
62pub fn process_home_dir_in_path(value: &Path) -> PathBuf {
63 #[cfg(unix)]
64 if let Some(Component::Normal(component)) = value.components().next() {
65 if component == "~" {
66 // Starts with ~/, should be replaced by home directory
67 let mut new_path = home_dir().unwrap();
68 let rest_of_path: PathBuf = value.components().skip(1).collect();
69 new_path.push(rest_of_path);
70
71 return new_path;
72 }
73 }
74 value.to_owned()
75}