]> git.phdru.name Git - dotfiles.git/commitdiff
.bashrc, .shellrc: Add `cd_worktree` with completion
authorOleg Broytman <phd@phdru.name>
Sun, 15 Oct 2023 12:24:03 +0000 (15:24 +0300)
committerOleg Broytman <phd@phdru.name>
Sun, 15 Oct 2023 13:09:05 +0000 (16:09 +0300)
.bashrc
.shellrc

diff --git a/.bashrc b/.bashrc
index 85cb4d87d8dbe099264af8d6b323b72131fb6576..18c00e23b1d2d2f002e96beaf8b1753add70e61a 100644 (file)
--- a/.bashrc
+++ b/.bashrc
@@ -235,6 +235,24 @@ if test -x /usr/bin/git >/dev/null 2>&1; then
         fi
     }
 
+    # completion for `cd_worktree`
+
+    _cd_worktree_comp() {
+        local cur="${COMP_WORDS[COMP_CWORD]}"
+        COMPREPLY=(`compgen -W "$(
+            git worktree list | awk '{s=$3; gsub("[\\\\[\\\\]]", "", s); print s}'
+        )" -- "$cur"`)
+    }
+
+    _cd_worktree_comp_loader() {
+        _completion_loader git
+        unset _cd_worktree_comp_loader
+        complete -F _cd_worktree_comp cd_worktree
+        return 124
+    }
+
+    complete -F _cd_worktree_comp_loader cd_worktree
+
     # completion for aliases in global .gitconfig
 
     # fixup rbi rbia rbiap rbip - do refs name completion
index b06ba8b24312a12021ba31d788e50cf0e5fcfbb3..5d46454aebef3e37633c23599d11aeb52fdf588d 100644 (file)
--- a/.shellrc
+++ b/.shellrc
@@ -72,6 +72,22 @@ if test -x /usr/bin/git >/dev/null 2>&1; then
         fi
         cd "$path_url"
     }
+
+    # See https://stackoverflow.com/a/77266926/7976758
+
+    cd_worktree() {
+        if [ $# -ne 1 ]; then
+            echo "Usage: cd_worktree <branch>" >&2
+            return 1
+        fi
+        path="$(git worktree list | grep -F "$1" | awk '{print $1}')"
+        if [ -n "$path" ]; then
+            cd "$path"
+        else
+            echo "Cannot find path for branch '$1'" >&2
+            return 1
+        fi
+    }
 fi
 
 include() {