aboutsummaryrefslogtreecommitdiff
path: root/filters
diff options
from:
to:
context:
space:
mode:
Diffstat (limited to 'filters')
-rwxr-xr-xfilters/ci-jenkins.sh58
1 files changed, 58 insertions, 0 deletions
diff --git a/filters/ci-jenkins.sh b/filters/ci-jenkins.sh
new file mode 100755
index 0000000..842af21
--- /dev/null
+++ b/filters/ci-jenkins.sh
@@ -0,0 +1,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"