-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstale-branches
executable file
·98 lines (83 loc) · 2.6 KB
/
stale-branches
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
#!/bin/bash
EXCEPTIONS_FILE="$(git rev-parse --show-toplevel)/.mess/s/stale-branches-exceptions.conf"
list_stale_branches() {
cutoff_date=$(date -d "2 weeks ago" "+%Y-%m-%d %H:%M:%S")
log_dir="$(git rev-parse --show-toplevel)/.mess"
log_file="$log_dir/git-checkouts.log"
# Ensure the log file exists
touch "$log_file"
# Get a list of all local branches
all_branches=$(git branch --format "%(refname:short)")
cutoff_ts=$(date -d "$cutoff_datetime" "+%s")
recent_checkouts=$(while read -r line; do
log_datetime=$(echo "$line" | awk -F': ' '{print $1}')
branch_name=$(echo "$line" | awk -F': ' '{print $2}')
log_ts=$(date -d "$log_datetime" "+%s")
if [ "$log_ts" -gt "$cutoff_ts" ]; then
echo "$branch_name"
fi
done < "$log_file" | sort | uniq )
for branch in $all_branches; do
if ! echo "$recent_checkouts" | grep -q "^$branch$"; then
echo "$branch"
fi
done
}
# Function to delete or forcefully delete stale branches
delete_stale_branches() {
local force_delete=$1
local delete_cmd="git branch -d"
if [[ "$force_delete" == "true" ]]; then
delete_cmd="git branch -D"
fi
if [[ -f "$EXCEPTIONS_FILE" ]]; then
echo "$EXCEPTIONS_FILE exists"
source "$EXCEPTIONS_FILE"
else
echo "$EXCEPTIONS_FILE does not exist"
declare -A exceptions=()
fi
local stale_branches=$(list_stale_branches)
for branch in $stale_branches; do
# skip exceptions
if [[ -n "${exceptions[$branch]}" ]]; then
echo "Skipping exception: $branch"
continue
fi
if [[ "$branch" != "" ]]; then
echo "Deleting branch: $branch"
$delete_cmd "$branch" || echo "Could not delete $branch. It might not be fully merged."
fi
done
}
# Parse command line args
force_flag=""
list_flag=""
for arg in "$@"
do
case $arg in
-d|--delete)
delete_flag="true"
;;
--force)
force_flag="true"
;;
-l|--list)
list_flag="true"
;;
*)
echo "Unknown option: $arg"
echo "Usage: $0 [--list] | [-d|--delete [--force]]"
exit 1
;;
esac
done
#if [[ "$list_flag" == "true" || ( -z "$delete_flag" && -z "$force_flag" ) ]]; then
if [[ "$list_flag" == "true" || ( -z "$delete_flag" ) ]]; then
list_stale_branches
elif [[ "$delete_flag" == "true" ]]; then
delete_stale_branches $force_flag
else
echo "Usage: $0 [--list] | [-d|--delete [--force]]"
exit 1
fi