Skip to content

Commit

Permalink
refactor contract_path to return Cow<str>
Browse files Browse the repository at this point in the history
  • Loading branch information
cymruu committed Jul 7, 2022
1 parent ffc9fb9 commit f05264f
Showing 1 changed file with 13 additions and 8 deletions.
21 changes: 13 additions & 8 deletions src/modules/directory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use super::utils::directory_win as directory_utils;
use super::utils::path::PathExt as SPathExt;
use indexmap::IndexMap;
use path_slash::{PathBufExt, PathExt};
use std::borrow::Cow;
use std::iter::FromIterator;
use std::path::{Path, PathBuf};
use unicode_segmentation::UnicodeSegmentation;
Expand Down Expand Up @@ -63,8 +64,8 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut is_truncated = dir_string.is_some();

// the home directory if required.
let dir_string =
dir_string.unwrap_or_else(|| contract_path(display_dir, &home_dir, &home_symbol));
let dir_string = dir_string
.unwrap_or_else(|| contract_path(display_dir, &home_dir, &home_symbol).to_string());

#[cfg(windows)]
let dir_string = remove_extended_path_prefix(dir_string);
Expand All @@ -89,7 +90,7 @@ pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let contracted_home_dir = contract_path(display_dir, &home_dir, &home_symbol);
to_fish_style(
config.fish_style_pwd_dir_length as usize,
contracted_home_dir,
contracted_home_dir.to_string(),
&dir_string,
)
} else {
Expand Down Expand Up @@ -204,13 +205,17 @@ fn is_readonly_dir(path: &Path) -> bool {
///
/// Replaces the `top_level_path` in a given `full_path` with the provided
/// `top_level_replacement`.
fn contract_path(full_path: &Path, top_level_path: &Path, top_level_replacement: &str) -> String {
fn contract_path<'a>(
full_path: &'a Path,
top_level_path: &'a Path,
top_level_replacement: &'a str,
) -> Cow<'a, str> {
if !full_path.normalised_starts_with(top_level_path) {
return full_path.to_slash_lossy().to_string();
return full_path.to_slash_lossy();
}

if full_path.normalised_equals(top_level_path) {
return top_level_replacement.to_string();
return Cow::from(top_level_replacement);
}

// Because we've done a normalised path comparison above
Expand All @@ -221,12 +226,12 @@ fn contract_path(full_path: &Path, top_level_path: &Path, top_level_replacement:
.strip_prefix(top_level_path.without_prefix())
.unwrap_or(full_path);

format!(
Cow::from(format!(
"{replacement}{separator}{path}",
replacement = top_level_replacement,
separator = "/",
path = sub_path.to_slash_lossy()
)
))
}

/// Contract the root component of a path based on the real path
Expand Down

0 comments on commit f05264f

Please sign in to comment.