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

set -eu

pgrep -x transmission-daemon >/dev/null 2>&1 && {
  echo "Turn off transmission-daemon first!"
  exit 1
}

# Check if inside a Git repository
! git rev-parse --is-inside-work-tree >/dev/null 2>&1 && echo "Not a git repository." && exit 1

# Function to generate a message for each status line
generate_message() {
  status=$1
  file=$2
  if echo "$file" | grep -q '/'; then
    file_name="${file##*/}"
    path_name="${file%/*}"
    dir_name="${path_name##*/}"
    dir_file_name="$dir_name/$file_name"
  else
    dir_file_name="$file"
  fi
  case "$status" in
  " M" | "M ") # Modified
    echo "modified $dir_file_name"
    ;;
  "??") # Untracked (new) files
    echo "created $dir_file_name"
    ;;
  " D" | "D ") # Deleted from the index
    echo "deleted $dir_file_name"
    ;;
  *) # Catch-all for other statuses
    echo "updated $dir_file_name"
    ;;
  esac
}

# Check for changes in the working directory
changes=$(git status --porcelain)

# Check for unpushed commits
unpushed=$(git cherry -v | wc -l)

[ -z "$changes" ] && [ "$unpushed" -eq 0 ] && exit

# Save current directory and change to the Git repo root
repo_root=$(git rev-parse --show-toplevel || echo ".")
cd "$repo_root" || exit

# Get the current Git branch name
branch=$(git symbolic-ref -q HEAD | sed -e 's|^refs/heads/||')

# Generate default commit message if there are changes
if [ -n "$changes" ] && [ "$unpushed" -eq 0 ]; then
  num_changes=$(echo "$changes" | wc -l)
  if [ "$num_changes" -gt 5 ]; then
    default="updates"
  else
    default=$(echo "$changes" | while IFS= read -r line; do
      status=$(echo "$line" | cut -c1-2)
      file=$(echo "$line" | cut -c4-)
      generate_message "$status" "$file"
    done | tr '\n' ',' | sed 's/,$//;s/,/, /g;s/"$//')
  fi
  message="${1:-$default}"

  # Add and commit changes
  git add --all .
  git commit -m "$message"
else
  message=$(git cherry -v | awk '{$1=$2=""; print $0}' | sed 's/^ *//' | tail -n 1)
fi

if [ "$repo_root" = "${PASSWORD_STORE_DIR:-${HOME}/.password-store}" ]; then
  pass git remote | xargs -L1 pass git push --all
else
  git pull --rebase origin "$branch"
  git remote | xargs -L1 git push --all
fi

printf "\n[repo] %s(%s): %s\n" "$(basename "$repo_root")" "$branch" "$message"

# Return to the original directory
cd - >/dev/null

command -v dwmblocks >/dev/null 2>&1 && pkill -RTMIN+18 "${STATUSBAR:-dwmblocks}"