summaryrefslogtreecommitdiff
path: root/mac/.local/bin/opensessions
blob: 6f9f236d46c08da82ba856b063356b9dd8fc7881 (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
#!/bin/sh

# split the selected directories into an array
dirs="$*"

# filter out any empty selections
dirs=$(echo "$dirs" | tr -s ' ' '\n' | sed '/^$/d')
[ -z "$dirs" ] && exit 0

# function to clean and create a valid session name
get_session_name() {
  basename "$1" | sed 's/[^a-zA-Z0-9]/_/g'
}

set -- $dirs

# handle session creation for multiple selected directories
for dir in $dirs; do
  if [ -d "$dir" ]; then
    session_name=$(get_session_name "$dir")
    if ! tmux has-session -t "$session_name" 2>/dev/null; then
      tmux new-session -d -s "$session_name" -c "$dir"
      if git -C "$dir" rev-parse --is-inside-work-tree >/dev/null 2>&1 && [ -n "$(git -C "$dir" status --porcelain)" ]; then
        tmux send-keys -t "$session_name" "git status --porcelain" C-m
      fi
    fi
  fi
done

if [ "$#" -gt 0 ]; then
  first_session=$(get_session_name "$1")
  if [ -n "$TMUX" ]; then
    tmux switch-client -t "$first_session"
  else
    tmux attach-session -t "$first_session"
  fi
fi