aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/tmux/.local/bin/tmux-sessionizer
blob: 87ad7604cab8e87e8a34f250143cc2211e5ad450 (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
53
54
55
#!/bin/sh
# shellcheck disable=2016

if [ "$#" -ne 0 ]; then
	path="$1"
else
	PROJECT_DIR="$HOME/src"
	DIRS="$HOME/.dotfiles"

	for entry in "$PROJECT_DIR"/*; do
		if [ -d "$entry" ]; then
			DIRS="$DIRS $entry"
		fi
	done

	DIRS="$(printf %s\\n "$DIRS" | xargs -I{} -d ' ' sh -c 'path="{}"
	session_file="$XDG_DATA_HOME/nvim/sessions/$(echo "$path" | sed "s|/|%|g").vim"
	if [ -f "$session_file" ]; then
		stat -c %Y:"$path" "$session_file"
	elif git -C "$path" rev-parse HEAD >/dev/null 2>&1; then
		git -C "$path" --no-pager log -1 --all --format="%at:$path" 2>/dev/null
	elif [ -e "$path/.git" ]; then
		stat -c %Y:"$path" "$path"/.git
	else
		stat -c %Y:"$path" "$path"
  fi' | sort -r | cut -d':' -f2)"

	output="$(printf %s\\n "$DIRS" |
		fzf-tmux -p -- --print-query -d/ --with-nth -2.. --preview="$FZF_PREVIEW_COMMAND {}" |
		tr -s '\n' ':')"

	query="$(printf %s\\n "$output" | cut -d':' -f1)"
	selection="$(printf %s\\n "$output" | cut -d':' -f2)"

	path="${selection:-$query}"
fi

if [ -z "$path" ]; then
	exit 0
elif [ ! -d "$path" ]; then
	mkdir -p "$1"
fi

name=$(basename "$path" | tr . _)

if [ -z "$TMUX" ] && pgrep tmux; then
	tmux new-session -s "$name" -c "$path"
	exit 0
fi

if ! tmux has-session -t="$name" 2>/dev/null; then
	tmux new-session -ds "$name" -c "$path"
fi

tmux switch-client -t "$name"