-
Notifications
You must be signed in to change notification settings - Fork 0
/
badges
81 lines (75 loc) · 2.18 KB
/
badges
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
#!/bin/bash
declare SHIELDS='https://img.shields.io/static/v1'
declare DEFAULT_COLOR='inactive'
# init pathnames to badges
badge_init() {
local badge_name="${1}"
local badge_default="${2}" #opt
generate_badge "${badge_name}" "${badge_default:--}"
}
# % to colors
percent_to_color() {
declare color='brightgreen'
declare perc="${1%\%}"
(( 10#$perc < 85 )) \
&& color='green'
(( 10#$perc < 70 )) \
&& color='yellow'
(( 10#$perc < 55 )) \
&& color='orange'
(( 10#$perc < 45 )) \
&& color='red'
printf -- '%s\n' "${color}"
}
fraction_to_color() {
[[ "${1}" == */0 ]] \
&& printf '%s\n' "${DEFAULT_COLOR}" \
&& return 1
percent_to_color "$(( 100 * $1 ))"
}
# URL encoding
url_encode() {
jq -Rr @uri <<< "${1}"
}
# generate badge
generate_badge() {
# required
local label="${1:-}"
local value="${2:-}"
[[ -z "${label}" || -z "${value}" ]] \
&& echo 'Missing badge label or value' >&2 \
&& return 2
# optional
local color="${3:-}"
local file_name="${4:-}"
local link="${5:-}"
local title="${6:-}"
# auto color
if [[ -z "${color}" ]]; then
if [[ $value =~ ^[0-9]+/[0-9]+$ ]]; then
color="$(fraction_to_color "${value}")"
elif [[ $value =~ ^[0-9]+%$ ]]; then
color="$(percent_to_color "${value%\%}")"
else
color="${DEFAULT_COLOR}"
fi
fi
# default badge name is "badge-[ci job name]-[normalized label]"
# normalized label: spaces to dashes, to lowercase
[[ -z "${file_name}" ]] \
&& file_name="${label// /-}" \
&& file_name="badge-${CI_JOB_NAME:-local}-${file_name,,}"
# generate shileds.io badge
WORKING_DIR="${WORKING_DIR:-.}"
local dest="${RESULTS:-${WORKING_DIR}/.results}/${file_name}.svg"
curl -so "${dest}" "${SHIELDS}?label=$(url_encode "${label}")&message=$(url_encode "${value}")&color=${color}"
# always add link element with or without href
# always cause of title not working only in svg, it needs to be in some element like <a>
[[ -n "${link}" ]] \
&& link="href=\"${link}\""
sed -Ei "s~(<svg[^>]+>)(.*)(</svg>)~\1<a ${link}>\2</a>\3~" "${dest}"
# update title
[[ -n "${title}" ]] \
&& sed -Ei "s~<title>.*</title>~<title>${title}</title>~" "${dest}"
return 0
}