aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/tmux/.local/bin/tmux-sessionizer
blob: 04f86333469c1e999acf07edc2782774e542e0db (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
#!/bin/sh
# shellcheck disable=2016,2089

PROJECT_DIR="$HOME/src"
SESSION_DIR="$XDG_DATA_HOME/nvim/sessions"
PREVIEW_CMD="previewer.sh {} 2>/dev/null || previewer.sh {q} --remote"
ATTACHED="$(tmux list-sessions -F '#{?session_attached,#{session_path},}' 2>/dev/null | sed '/^$/d')"

if [ "$#" -eq 0 ]; then
	# shellcheck disable=2046
	set -- $({
		printf %s\\n "$HOME/.dotfiles"
		fd . "$PROJECT_DIR" --type=d --max-depth=1
		fd . "$SESSION_DIR" --type=f --max-depth=1 | sed "s|^$SESSION_DIR/||" | sed 's#%%\|__#/#g'
	} | sed 's|/$||' | sed "\|^$HOME\$|d" | sed "\|^$ATTACHED\$|d" | sort -u |
		timestamp.sh --git --sessions="$SESSION_DIR" --format="{}:{1}" | sort -r | cut -d':' -f2 |
		fzf-tmux -p -- --multi --print-query -d/ --with-nth -1 --preview-window=right,75% --preview="$PREVIEW_CMD" |
		tr -s '\n' ' ')
fi

while [ $# -gt 0 ]; do
	session_path="$1"
	shift
	if [ ! -d "$session_path" ]; then
		repo=$(printf %s "$session_path" | sed 's/.git$//' | sed 's|/$||')
		remotes="$repo https://git.sr.ht/$repo https://github.com/$repo"
		for remote in $remotes; do
			if timeout 3s git ls-remote "$remote" CHECK_GIT_REMOTE_URL_REACHABILITY; then
				session_path="$HOME/src/$(basename "$remote")"
				git clone "$remote" "$session_path"
				break
			fi
		done
	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