From d6b9153ac5c3f1916339c1f0fc4103ea67e7d83c Mon Sep 17 00:00:00 2001 From: Carson Riker Date: Fri, 29 Sep 2023 10:40:51 -0400 Subject: [PATCH] Fix Default Prompt Tilde Insertion Logic (#10539) This pr closes #10521. # Description The default prompt by nushell will replace `$nu.home-path` with `~`. E.g. for a user named `user`, `/home/user` would become `~`. This also works with sub paths, e.g. `/home/user/docs` would become `~/docs`. The issue is that this replacement was a tad overzealous. A path like `/home/user-with-suffix` would become `~-with-suffix`. This PR fixes the issue by updating the home path detection logic. # User-Facing Changes The bugged behavior no longer occurs. # Tests + Formatting * `cargo` checks were not performed as this does not touch rust. * The updated logic was tested against [elvish](https://github.com/elves/elvish)'s path replacement logic, for ~10,000 randomly selected folders on a linux server. All paths were processed the same. --- .../nu-utils/src/sample_config/default_env.nu | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/crates/nu-utils/src/sample_config/default_env.nu b/crates/nu-utils/src/sample_config/default_env.nu index 9935859be..4f756fb25 100644 --- a/crates/nu-utils/src/sample_config/default_env.nu +++ b/crates/nu-utils/src/sample_config/default_env.nu @@ -5,10 +5,21 @@ def create_left_prompt [] { let home = $nu.home-path - let dir = ([ - ($env.PWD | str substring 0..($home | str length) | str replace $home "~"), - ($env.PWD | str substring ($home | str length)..) - ] | str join) + # Perform tilde substitution on dir + # To determine if the prefix of the path matches the home dir, we split the current path into + # segments, and compare those with the segments of the home dir. In cases where the current dir + # is a parent of the home dir (e.g. `/home`, homedir is `/home/user`), this comparison will + # also evaluate to true. Inside the condition, we attempt to str replace `$home` with `~`. + # Inside the condition, either: + # 1. The home prefix will be replaced + # 2. The current dir is a parent of the home dir, so it will be uneffected by the str replace + let dir = ( + if ($env.PWD | path split | zip ($home | path split) | all { $in.0 == $in.1 }) { + ($env.PWD | str replace $home "~") + } else { + $env.PWD + } + ) let path_color = (if (is-admin) { ansi red_bold } else { ansi green_bold }) let separator_color = (if (is-admin) { ansi light_red_bold } else { ansi light_green_bold })