aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/tmux/.local/bin/tmux-sessionizer
blob: 29a0efc1ed939346852a78075bf2fea8164023b3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#!/bin/sh
# shellcheck disable=2016,2089

if [ "$#" -eq 0 ]; then
	PREVIEW_CMD='sel={}; less ${sel:-{q}} 2>/dev/null'

	lines=$(tmux display -p "#{pane_height}")
	columns=$(tmux display -p "#{pane_width}")
	WIDTH=$([ "$columns" -gt "120" ] && printf %s "120" || printf %s "90%")
	HEIGHT=$([ "$lines" -gt "40" ] && printf %s "40" || printf %s "90%")

	# shellcheck disable=2046
	set -- $(projectr ~/src ~/.dotfiles --git --max-depth=3 | sed "\|^$(tmux display -p '#{session_path}')\$|d" |
		fzf-tmux -p "$WIDTH,$HEIGHT" -- --tac --multi --print-query -d/ --with-nth -1 \
			--preview-window='right,75%,<80(up,75%,border-bottom)' --preview="$PREVIEW_CMD" |
		tr -s '\n' ' ') && [ $# -gt 1 ] && shift
fi

while [ $# -gt 0 ]; do
	session_path="$1"
	shift

	if [ ! -d "$session_path" ]; then
		repo="$session_path"
		if [ "$repo" = "${repo%/*}/${repo#*/}" ]; then
			for remote in ${GIT_REMOTES:-https://git.sr.ht https://github.com}; do
				if git ls-remote "$remote/$repo" CHECK_GIT_REMOTE_REACHABILITY; then
					session_path="$remote/$repo"
					break
				fi
			done
		fi

		session_path="$HOME/src/$(basename "$session_path")"
		git clone "$repo" "$session_path"
	fi

	if [ ! -d "$session_path" ]; then
		continue
	fi

	name=$(basename "$session_path" | tr . _)
	if ! tmux has-session -t="$name" 2>/dev/null; then
		tmux new-session -ds "$name" -c "$session_path"
	fi
done

if [ -z "$TMUX" ] && [ -z "$name" ]; then
	tmux attach-session -t "$name"
elif tmux has-session -t="$name" 2>/dev/null; then
	tmux switch-client -t "$name"
fi