From 0471a20c7cf5440bb5180f815254cc30873acbd9 Mon Sep 17 00:00:00 2001 From: John D Pell Date: Wed, 22 Sep 2021 13:00:36 -0700 Subject: [PATCH] lib/helpers: new function `_bash-it-find-in-ancestor()` New function to do a search looking for a sibling to a parent of the current directory, for example to find `../../.git` to indicate that `$PWD` is inside a git repository. --- lib/helpers.bash | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/lib/helpers.bash b/lib/helpers.bash index fbc6aa88..26f1c3a6 100755 --- a/lib/helpers.bash +++ b/lib/helpers.bash @@ -849,3 +849,21 @@ then fi } fi + +function _bash-it-find-in-ancestor() ( + # We're deliberately using a subshell for this entire function for simplicity. + # By using a subshell, we can use ${PWD} without special handling, and can + # just `cd ..` to move up the directory heirarchy. + # Let the shell do the work. + local kin + while [[ "${PWD}" != '/' ]]; do + for kin in "$@"; do + if [[ -r "${PWD}/${kin}" ]]; then + printf '%s' "${PWD}" + return "$?" + fi + done + command cd .. || return "$?" + done + return 1 +)