@@ -10,6 +10,7 @@ BINARY_PATH=$(which wt)
1010JQ_URL=" https://stedolan.github.io/jq/download"
1111RELEASE_URL=" https://github.com/yankeexe/git-worktree-switcher/releases/latest"
1212RELEASE_API_URL=" https://api.github.com/repos/yankeexe/git-worktree-switcher/releases/latest"
13+ CHANGE_DIRECTORY_PREFIX=" changedir:"
1314
1415
1516# Escape forward slash
@@ -27,6 +28,7 @@ help_message() {
2728 echo -e " \twt list: list out all the git worktrees."
2829 echo -e " \twt update: update to the latest release of worktree switcher."
2930 echo -e " \twt version: show the CLI version."
31+ echo -e " \twt init <shell>: print the init script for <shell>."
3032 echo -e " \twt help: shows this help message."
3133}
3234
@@ -36,9 +38,7 @@ goto_main_worktree() {
3638 if [ -z " $main_worktree " ]; then
3739 :
3840 else
39- echo Changing to main worktree at: " $main_worktree "
40- cd " $main_worktree "
41- exec $SHELL
41+ directory=$main_worktree
4242 fi
4343}
4444
@@ -77,6 +77,69 @@ update() {
7777 fi
7878}
7979
80+ init_bash () {
81+ cat << EOF
82+ wt() {
83+ if ! command -v wt &> /dev/null; then
84+ echo "wt was not found in your \\\$ PATH"
85+ return 1
86+ fi
87+
88+ result="\$ (command wt "\$ @")"
89+ dest_path="\$ (echo "\$ result" | awk '/^$CHANGE_DIRECTORY_PREFIX .*/ {sub("$CHANGE_DIRECTORY_PREFIX ", ""); print; exit}')"
90+
91+ if [[ -n "\$ dest_path" ]]; then
92+ cd "\$ dest_path" || return
93+ elif [[ -n \$ result ]]; then
94+ echo "\$ result"
95+ fi
96+
97+ return 0
98+ }
99+ EOF
100+ }
101+
102+ init_fish () {
103+ cat << EOF
104+ function wt
105+ if ! command -q wt
106+ echo "wt was not found in your \\\$ PATH"
107+ return 1
108+ end
109+
110+ set -l result "\$ (command wt \$ argv)"
111+ set -l dest_path "\$ (echo "\$ result" | awk '/^$CHANGE_DIRECTORY_PREFIX .*/ {sub("$CHANGE_DIRECTORY_PREFIX ", ""); print; exit}')"
112+
113+ if test -n "\$ dest_path"
114+ cd "\$ dest_path"
115+ else if test -n "\$ result"
116+ echo "\$ result"
117+ end
118+ end
119+ EOF
120+ }
121+
122+ init () {
123+ shell=" ${args[1]} "
124+ if [[ -z $shell ]]; then
125+ echo " Please supply a shell."
126+ echo " eg. wt init bash"
127+ exit 1
128+ fi
129+ case " $shell " in
130+ bash|zsh)
131+ init_bash
132+ ;;
133+ fish)
134+ init_fish
135+ ;;
136+ * )
137+ echo " Unsupported shell: $shell "
138+ exit 1
139+ ;;
140+ esac
141+ }
142+
80143if [ -z " ${args[0]} " ]; then
81144 help_message
82145 exit 0
95158version)
96159 echo Version: $VERSION
97160 ;;
161+ init)
162+ init
163+ ;;
98164-)
99165 goto_main_worktree
100166 ;;
@@ -103,16 +169,9 @@ version)
103169 ;;
104170esac
105171
106- # Change worktree based on user argument.
107- change_worktree () {
108- echo Changing to worktree at: " $directory "
109- cd " $directory "
110- exec $SHELL
111- }
112-
113172# If directory variable is not empty then change worktree
114173if [ -z " $directory " ]; then
115174 :
116175else
117- change_worktree
176+ echo " $CHANGE_DIRECTORY_PREFIX$directory "
118177fi
0 commit comments