Skip to content

Commit 47eafc5

Browse files
Cyanoxygenchenx97
authored andcommitted
_vcs/hg: add a helper function to detect Mercurial repository
This helper ascends to the parent directories of PWD one by one, tests if the directory contains .hg, or the path eventually hits /. Using loops instead recursions saved a lot of time, 0.16s on recursions and 0.01s on loops, when $PWD is 127 directories deep.
1 parent e8189b9 commit 47eafc5

File tree

1 file changed

+18
-1
lines changed
  • bashrc.d/_vcs

1 file changed

+18
-1
lines changed

bashrc.d/_vcs/hg

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,28 @@ alias hb='hg branch'
1313
alias hs='hg status'
1414
alias ha='hg add .'
1515

16+
_detect_hg() {
17+
local _hg_dir="$1"
18+
local i=1
19+
if [ "${_hg_dir:0:1}" != "/" ] ; then
20+
echo "$FUNCNAME: absolute path required" >&2
21+
return 1
22+
fi
23+
# NOTE $_hg_dir is empty when it reaches /.
24+
while ! [ "/$_hg_dir" -ef "/" ] ; do
25+
if [ -d "$_hg_dir"/.hg ] ; then
26+
return 0
27+
fi
28+
_hg_dir="${_hg_dir%/*}"
29+
done
30+
[ -d /.hg ]
31+
}
32+
1633
# From http://mediadoneright.com/content/ultimate-git-ps1-bash-prompt
1734
# Modified for hg.
1835
_ps1_hg_status() {
1936
# skip the check if possible, because hg is slow.
20-
test -e .hg || return 1
37+
_detect_hg $PWD || return 1
2138
hgb=$(hg branch 2>/dev/null) || return 1
2239
hgs=$(LC_ALL=C hg status 2>&1)
2340
if [ -z "$hgs" ]; then # unmodified

0 commit comments

Comments
 (0)