aboutsummaryrefslogtreecommitdiff
path: root/filters/ci-jenkins.sh
blob: 842af2109db07d7c997d2b6cdbb2c79257bf5aca (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
#!/bin/sh
# This script may be used with the ci-filter or repo.ci-filter setting in
# cgitrc to hide the "ci" tab for refs which have no pipeline on a Jenkins
# instance.
#
# Arguments:
#   $1  the name of the branch or tag being viewed
#   $2  "branch" or "tag"
#   $3  the ci url which the "ci" tab would redirect to
#
# Exit with a zero status to show the tab, non-zero to hide it. This script
# must not write anything to standard output, as that would end up in the
# middle of the page cgit is rendering.
#
# The filter is consulted while rendering every repository page, so the
# verdict is cached on disk to keep Jenkins from being hammered, and the
# probe is given a short timeout so that an unreachable Jenkins degrades
# into a missing tab rather than a hanging web server.
#
# Set CI_NETRC to a netrc(5) file if the Jenkins instance requires
# authentication; without it a private job answers 403 and the tab is
# hidden even though the pipeline exists.

CI_CACHE_DIR="${CI_CACHE_DIR:-/var/cache/cgit/ci-filter}"
CI_CACHE_TTL_MINUTES="${CI_CACHE_TTL_MINUTES:-5}"
CI_TIMEOUT="${CI_TIMEOUT:-2}"

url="$3"
test -n "$url" || exit 1

# Jenkins job pages are often not readable anonymously, so query the REST
# API rather than the page the tab points at.
probe="$url/api/json?tree=name"

key="$(printf '%s' "$url" | cksum | tr -cd '0-9')"
cache="$CI_CACHE_DIR/$key"

mkdir -p "$CI_CACHE_DIR" 2>/dev/null

if test -f "$cache" &&
   test -z "$(find "$cache" -mmin "+$CI_CACHE_TTL_MINUTES" 2>/dev/null)"
then
	exit "$(cat "$cache")"
fi

status=0
curl --silent --fail --head --output /dev/null \
     --max-time "$CI_TIMEOUT" \
     ${CI_NETRC:+--netrc-file "$CI_NETRC"} \
     "$probe" >/dev/null 2>&1 || status=1

if test -d "$CI_CACHE_DIR"
then
	printf '%s\n' "$status" >"$cache.$$" 2>/dev/null &&
		mv "$cache.$$" "$cache" 2>/dev/null
fi

exit "$status"