aboutsummaryrefslogtreecommitdiff
path: root/dotfiles/common/.local/bin/tmux-util
blob: dca01fdfdf5c26c7522641809df8e3f70cbd32f7 (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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
#!/bin/bash
# tmux-util — small utilities for managing tmux sessions.
#
# Subcommands:
#   go <name>      attach to <name> if it exists, otherwise create it
#   pick           fzf-driven session switcher
#   ls             opinionated session listing (attached, idle, windows, cwd)
#   find <pattern> locate panes whose foreground process matches <pattern>
#   reap           gracefully exit every unattached session (skipping aiv-*)
#   rename         fzf-pick a session, prompt for a new name, rename it
#
# Run with no arguments to print this help.

set -uo pipefail

# -----------------------------------------------------------------------------
# Usage
# -----------------------------------------------------------------------------

usage() {
    cat <<'EOF'
Usage: tmux-util <subcommand> [args]

Subcommands:
  go <name>      Attach to session <name>; create it (in $PWD) if missing.
  pick           Fzf-driven session switcher.
  ls             List sessions with attached / idle / window / cwd columns.
  find <pattern> Locate panes whose foreground process matches <pattern>.
  reap           Send SIGHUP to every unattached session's panes and close
                 the session. Sessions matching $TMUX_UTIL_REAP_SKIP
                 (default: ^aiv-) are skipped.
  rename         Pick a session via fzf, prompt for a new name, rename it.

Run with no arguments to print this help.
EOF
}

# -----------------------------------------------------------------------------
# rename
# -----------------------------------------------------------------------------

cmd_rename() {
    local sessions
    sessions=$(tmux list-sessions \
        -F '#{session_attached} #{session_name}' 2>/dev/null || true)
    if [ -z "$sessions" ]; then
        echo "No tmux sessions to rename."
        return 0
    fi

    local choice
    choice=$(echo "$sessions" | awk '{
        state = ($1 == "1") ? "attached" : "detached"
        printf "%-9s %s\n", state, $2
    }' | fzf --header="Pick a session to rename" | awk '{print $2}')

    if [ -z "$choice" ]; then
        # User cancelled.
        return 0
    fi

    local new_name
    printf 'New name for "%s": ' "$choice"
    read -r new_name

    if [ -z "$new_name" ]; then
        echo "tmux-util rename: empty new name, cancelled." >&2
        return 1
    fi

    if [ "$new_name" = "$choice" ]; then
        echo "tmux-util rename: new name same as old, no change."
        return 0
    fi

    if tmux has-session -t "=$new_name" 2>/dev/null; then
        echo "tmux-util rename: a session named '$new_name' already exists." >&2
        return 1
    fi

    tmux rename-session -t "$choice" "$new_name"
    echo "Renamed: $choice -> $new_name"
}

# -----------------------------------------------------------------------------
# pick
# -----------------------------------------------------------------------------

cmd_pick() {
    local sessions
    sessions=$(tmux list-sessions \
        -F '#{session_attached} #{session_name}' 2>/dev/null || true)
    if [ -z "$sessions" ]; then
        echo "No tmux sessions to pick from."
        return 0
    fi

    # Format for fzf: "<state>  <name>" — name is the second field of the
    # selection line, which we recover after fzf returns.
    local choice
    choice=$(echo "$sessions" | awk '{
        state = ($1 == "1") ? "attached" : "detached"
        printf "%-9s %s\n", state, $2
    }' | fzf --header="Pick a tmux session" | awk '{print $2}')

    if [ -z "$choice" ]; then
        # User cancelled (Ctrl-C or Esc); fzf exits 130, the pipeline
        # returns empty.
        return 0
    fi

    if [ -n "${TMUX:-}" ]; then
        tmux switch-client -t "$choice"
    else
        tmux attach-session -t "$choice"
    fi
}

# -----------------------------------------------------------------------------
# find
# -----------------------------------------------------------------------------

cmd_find() {
    local pattern="${1:-}"
    if [ -z "$pattern" ]; then
        echo "tmux-util find: missing pattern" >&2
        echo "Usage: tmux-util find <pattern>" >&2
        return 2
    fi

    local matches
    matches=$(tmux list-panes -a \
        -F '#{session_name}:#{window_index}.#{pane_index} #{pane_current_command}' \
        2>/dev/null | grep -E "$pattern" || true)

    if [ -z "$matches" ]; then
        return 1
    fi
    echo "$matches"
}

# -----------------------------------------------------------------------------
# go
# -----------------------------------------------------------------------------

cmd_go() {
    local name="${1:-}"
    if [ -z "$name" ]; then
        echo "tmux-util go: missing session name" >&2
        echo "Usage: tmux-util go <name>" >&2
        return 2
    fi

    # `=name` forces exact match in `tmux has-session` (otherwise tmux does
    # prefix matching, which would let `go foo` attach to a session named
    # `foobar`).
    if tmux has-session -t "=$name" 2>/dev/null; then
        if [ -n "${TMUX:-}" ]; then
            tmux switch-client -t "$name"
        else
            tmux attach-session -t "$name"
        fi
    else
        if [ -n "${TMUX:-}" ]; then
            tmux new-session -d -s "$name" -c "$PWD"
            tmux switch-client -t "$name"
        else
            tmux new-session -s "$name" -c "$PWD"
        fi
    fi
}

# -----------------------------------------------------------------------------
# ls
# -----------------------------------------------------------------------------

# Render seconds as a short human duration (e.g. "5s", "12m", "3h", "2d").
format_idle() {
    local s="$1"
    if [ "$s" -lt 60 ]; then
        echo "${s}s"
    elif [ "$s" -lt 3600 ]; then
        echo "$((s / 60))m"
    elif [ "$s" -lt 86400 ]; then
        echo "$((s / 3600))h"
    else
        echo "$((s / 86400))d"
    fi
}

cmd_ls() {
    local sessions
    sessions=$(tmux list-sessions \
        -F '#{session_attached} #{session_name} #{session_activity} #{session_windows}' \
        2>/dev/null || true)

    if [ -z "$sessions" ]; then
        echo "No tmux sessions."
        return 0
    fi

    local now="${TMUX_UTIL_NOW:-$(date +%s)}"

    {
        printf 'STATE\tNAME\tIDLE\tWINDOWS\tCWD\n'
        local attached name activity windows state idle_str cwd
        while IFS=' ' read -r attached name activity windows; do
            [ -n "$name" ] || continue
            state="detached"
            [ "$attached" -gt 0 ] && state="attached"
            idle_str=$(format_idle "$((now - activity))")
            cwd=$(tmux display -p -t "$name" '#{pane_current_path}' 2>/dev/null || echo "?")
            # Replace leading $HOME with ~ for display.
            if [ -n "${HOME:-}" ] && [ "${cwd#$HOME}" != "$cwd" ]; then
                cwd="~${cwd#$HOME}"
            fi
            printf '%s\t%s\t%s\t%s\t%s\n' "$state" "$name" "$idle_str" "$windows" "$cwd"
        done <<<"$sessions"
    } | column -t -s $'\t'
}

# -----------------------------------------------------------------------------
# Reap
# -----------------------------------------------------------------------------

cmd_reap() {
    local skip="${TMUX_UTIL_REAP_SKIP:-^aiv-}"
    local sessions
    sessions=$(tmux list-sessions -F '#{session_name} #{session_attached}' 2>/dev/null \
               | awk '$2 == 0 {print $1}' \
               | grep -vE "$skip" || true)

    if [ -z "$sessions" ]; then
        echo "No unattached sessions to reap."
        return 0
    fi

    local s pids
    while IFS= read -r s; do
        [ -n "$s" ] || continue
        echo "Reaping: $s"
        pids=$(tmux list-panes -s -t "$s" -F '#{pane_pid}' 2>/dev/null)
        if [ -n "$pids" ]; then
            echo "$pids" | xargs -r kill -HUP
        fi
        # Give the session a moment to wind down naturally.
        local i
        for i in 1 2 3; do
            tmux has-session -t "$s" 2>/dev/null || break
            sleep 1
        done
        if tmux has-session -t "$s" 2>/dev/null; then
            echo "  still alive, force killing"
            tmux kill-session -t "$s"
        fi
    done <<<"$sessions"
}

# -----------------------------------------------------------------------------
# Dispatch
# -----------------------------------------------------------------------------

main() {
    if [ "$#" -eq 0 ]; then
        usage
        return 0
    fi

    local sub="$1"
    shift

    case "$sub" in
        -h|--help|help)
            usage
            ;;
        reap)
            cmd_reap "$@"
            ;;
        ls)
            cmd_ls "$@"
            ;;
        go)
            cmd_go "$@"
            ;;
        find)
            cmd_find "$@"
            ;;
        pick)
            cmd_pick "$@"
            ;;
        rename)
            cmd_rename "$@"
            ;;
        *)
            echo "tmux-util: unknown subcommand: $sub" >&2
            usage >&2
            return 2
            ;;
    esac
}

main "$@"