-
Notifications
You must be signed in to change notification settings - Fork 0
/
entrypoint.sh
executable file
·107 lines (84 loc) · 2.32 KB
/
entrypoint.sh
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
#!/bin/bash
usage() {
echo "Usage: $0 [-d] [-n days] repository_name"
echo " -d Dry run. Show tags to be deleted without actually deleting them."
echo " -n days Number of days. Tags older than these many days will be deleted."
echo " -h Display this help message."
echo " DEBUG=true Enable debug mode."
}
check_dependencies() {
if ! command -v jq &>/dev/null || ! command -v doctl &>/dev/null; then
echo "Both jq and doctl should be installed to run this script."
exit 1
fi
}
check_for_errors() {
local raw_response="$1"
if [ -z "$raw_response" ]; then
echo "No tags found for repository: $REPOSITORY. Got empty response."
exit 0
fi
if jq -e '.errors' <<<"$raw_response" >/dev/null 2>&1; then
echo "Error: $(jq -r '.errors[0].detail' <<<"$raw_response")"
exit 1
fi
}
DRY_RUN=false
DAYS=2
while getopts ":dh:n:" opt; do
case $opt in
d) DRY_RUN=true ;;
n) DAYS=$OPTARG ;;
h)
usage
exit 0
;;
\?)
echo "Invalid option: -$OPTARG" >&2
usage
exit 1
;;
esac
done
shift $((OPTIND - 1))
if [ "$#" -lt 1 ]; then
echo "Error: Repository name is required."
usage
exit 1
fi
REPOSITORY="$1"
check_dependencies
rawResponse=$(doctl registry repository list-tags "$REPOSITORY" --output=json)
[ "$DEBUG" = true ] && echo "Raw response: $rawResponse"
check_for_errors "$rawResponse"
tags=$(jq '[.[] | {updated_at, tag}]' <<<"$rawResponse")
toDelete=()
len=$(jq length <<<"$tags")
echo "Found $len tags."
for i in $(seq 0 $((len - 1))); do
tag=$(jq -r --argjson index "$i" '.[$index].tag' <<<"$tags")
updated=$(jq -r --argjson index "$i" '.[$index].updated_at' <<<"$tags")
if [[ "$OSTYPE" == "darwin"* ]]; then
updated=${updated/Z/+0000}
updatedDate=$(date -jf "%Y-%m-%dT%H:%M:%S%z" "$updated" +%s)
else
updatedDate=$(date -d "$updated" +%s)
fi
now=$(date +%s)
diff=$((now - updatedDate))
diff_days=$((diff / 86400))
if [ "$tag" != "latest" ] && [ $diff_days -ge $DAYS ]; then
toDelete+=($tag)
fi
done
echo "Found ${#toDelete[@]} tags to delete."
if [ "$DRY_RUN" = true ]; then
for value in "${toDelete[@]}"; do
echo "Would delete tag (dry run): $value"
done
else
for value in "${toDelete[@]}"; do
echo "Deleting tag: $value"
doctl registry repository delete-tag "$REPOSITORY" $value --force
done
fi