summaryrefslogtreecommitdiffstatshomepage
path: root/tmux/.local/bin/tmux-sessionizer
blob: 17599f93da7041e392d20ec5fb0ecce07859cf00 (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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#!/bin/sh
# shellcheck disable=2016

if [ "$#" -ne 0 ]; then
	selection="$1"
else
	PROJECT_DIR="$HOME/src"

	if [ -n "$TMUX" ]; then
		DIRS="$(tmux list-sessions -F '#{session_last_attached}:#{session_path}' 2>/dev/null | tr -s '\n' ' ' | sed 's/ $//')"
	fi

	for session in "$XDG_DATA_HOME/nvim/sessions"/*; do
		entry="$(printf %s\\n "$session" | sed "s|^$XDG_DATA_HOME/nvim/sessions/||" | sed 's|%%|/|g' | sed 's|__|/|g')"
		if [ -d "$entry" ]; then
			DIRS="$DIRS $(stat -c %Y:"$entry" "$session")"
		fi
	done

	for project in "$PROJECT_DIR"/*; do
		if [ -d "$project" ]; then
			DIRS="$DIRS $(stat -c %Y:"$project" "$project")"
		fi
	done

	DIRS="$(printf %s\\n "$DIRS" | xargs -I{} -d ' ' sh -c '
  timestamp="$(printf %s "{}" | cut -d":" -f1)"
  dir_path="$(printf %s "{}" | cut -d":" -f2)"
  source="$(printf %s "{}" | cut -d":" -f2)"

	if [ -e "$dir_path/.git" ]; then
    git_timestamp="$(git -C "$dir_path" --no-pager log -1 --all --format="%at" 2>/dev/null || stat -c %Y "$dir_path"/.git)"
  fi

  if [ $git_timestamp -gt $timestamp ]; then
    printf %s:%s\\n $git_timestamp $dir_path
  else
    printf %s\\n {}
  fi
  ' | sort -r | sort --field-separator=':' -r --key=2 | uniq -s10 | sort -r | cut -d':' -f2)"

	output="$(printf %s\\n "$DIRS" | fzf-tmux -p -- --print-query -d/ --with-nth -2.. \
		--preview="tmux capture-pane -ep -t \$(basename '{}' | tr . _) 2>/dev/null ||
    $FZF_PREVIEW_COMMAND ||
    printf '%s' {q} | sed 's|/\$||' | xargs hut git show 2>/dev/null ||
    gh repo view {q} 2>/dev/null ||
    printf 'Create new project:\n %s' {q} |
    sed 's|^ \([^/~][^/]*\)\$| $HOME/\1|' |
    sed 's/^ //'" |
		tr -s '\n' ' ')"

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

if [ -z "$selection" ]; then
	if [ -z "$query" ]; then
		exit 0
	fi
	query=$(printf %s "$query" | sed 's/.git$//' | sed 's|/$||')
	selection="$HOME/src/$(basename "$query")"
	if [ ! -d "$selection" ]; then
		if hut git show "$query" >/dev/null 2>&1; then
			git clone "https://git.sr.ht/$query" "$selection" ||
				git clone "$query" "$selection" ||
				exit 1
		elif gh repo view "$query" >/dev/null 2>&1; then
			git clone "https://github.com/$query" "$selection" ||
				git clone "$query" "$selection" ||
				exit 1
		else
			exit 0
		fi
	fi
fi

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

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

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

tmux switch-client -t "$name"