#!/usr/bin/env bash # # Run Gradle tasks against an explicitly-named project and report the result from # the exit code, never from the console text. # # Why this exists: reading "BUILD SUCCESSFUL" out of piped Gradle output is not a # reliable signal. A shell chain like `cd dir && cp f . ` followed on the next # line by `./gradlew test` will happily run Gradle in whatever directory the # shell was already in if the cd failed, and the success line it prints is then # about a different project entirely. That failure mode is silent and reads # exactly like success. # # Usage: # gradle-verify [-- ] # # Exits with Gradle's own exit code. Prints a summary block that names the # absolute project directory actually used. set -euo pipefail die() { printf '%s: %s\n' "$(basename "$0")" "$*" >&2; exit 2; } [ $# -ge 2 ] || die "usage: $(basename "$0") [-- ]" raw_dir=$1; shift # Resolve to an absolute path up front and fail loudly if it is not what we # expect. Every later step uses this resolved value, so there is nothing for an # ambient cwd to influence. project_dir=$(cd "$raw_dir" 2>/dev/null && pwd) \ || die "project dir does not exist or is not readable: $raw_dir" [ -x "$project_dir/gradlew" ] \ || die "no executable gradlew in: $project_dir" tasks=() extra=() seen_sep=0 for arg in "$@"; do if [ "$arg" = "--" ]; then seen_sep=1; continue; fi if [ $seen_sep -eq 1 ]; then extra+=("$arg"); else tasks+=("$arg"); fi done [ ${#tasks[@]} -ge 1 ] || die "no gradle tasks given" printf '=== gradle-verify ===\n' printf 'project : %s\n' "$project_dir" printf 'tasks : %s\n' "${tasks[*]}" [ ${#extra[@]} -gt 0 ] && printf 'args : %s\n' "${extra[*]}" # -p pins the project directory regardless of cwd. Note gradlew is invoked by # absolute path too, so we are not depending on PATH or on cwd for the wrapper # either. set +e "$project_dir/gradlew" -p "$project_dir" "${tasks[@]}" ${extra[@]+"${extra[@]}"} status=$? set -e printf 'exit : %d\n' "$status" if [ $status -eq 0 ]; then printf 'result : PASS\n' else printf 'result : FAIL\n' fi exit $status