|
| 1 | +#!/usr/bin/env bash |
| 2 | +# ktlint — Kotlin linter (category: JVM executable). |
| 3 | +# Downloads the upstream ktlint executable (self-extracting jar wrapper), sha256-verifies it, |
| 4 | +# caches it, locates a JDK 11+ via lib/jvm.sh, and execs `<ktlint> <args> <files>`. |
| 5 | +set -euo pipefail |
| 6 | + |
| 7 | +HOOK_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" |
| 8 | +REPO_ROOT="$(cd "${HOOK_DIR}/../.." && pwd)" |
| 9 | + |
| 10 | +# shellcheck source=../../lib/platform.sh |
| 11 | +source "${REPO_ROOT}/lib/platform.sh" |
| 12 | +# shellcheck source=../../lib/download.sh |
| 13 | +source "${REPO_ROOT}/lib/download.sh" |
| 14 | +# shellcheck source=../../lib/jvm.sh |
| 15 | +source "${REPO_ROOT}/lib/jvm.sh" |
| 16 | + |
| 17 | +VERSION="$(grep -v '^#' "${HOOK_DIR}/version.txt" | tr -d '[:space:]')" |
| 18 | +CHECKSUMS="${HOOK_DIR}/checksums.txt" |
| 19 | + |
| 20 | +asset_name="ktlint" |
| 21 | +# GitHub Releases canonical URL for ktlint executable. |
| 22 | +url="https://github.com/pinterest/ktlint/releases/download/${VERSION}/ktlint" |
| 23 | + |
| 24 | +# locate_java exits 0 with a warning if no JDK 11+ is available. |
| 25 | +java_bin="$(locate_java)" |
| 26 | + |
| 27 | +exe_path="$(download_tool ktlint "${VERSION}" "${url}" "${asset_name}" "${CHECKSUMS}")" |
| 28 | + |
| 29 | +if [[ $# -eq 0 ]]; then |
| 30 | + exit 0 |
| 31 | +fi |
| 32 | + |
| 33 | +# Snapshot file hashes pre-lint to detect modifications. |
| 34 | +declare -a before_hashes=() |
| 35 | +for f in "$@"; do |
| 36 | + before_hashes+=("$(_sha256_of "${f}" 2>/dev/null || echo NONE)") |
| 37 | +done |
| 38 | + |
| 39 | +# ktlint can auto-fix via --format flag. When invoked with filenames, |
| 40 | +# it lints them. Combine JAVA_HOME and direct invocation. |
| 41 | +# The executable is a shell script wrapper around a jar, so we need java. |
| 42 | +JAVA_HOME="${JAVA_HOME:-}" "${exe_path}" "$@" |
| 43 | +status=$? |
| 44 | + |
| 45 | +modified=0 |
| 46 | +i=0 |
| 47 | +for f in "$@"; do |
| 48 | + after="$(_sha256_of "${f}" 2>/dev/null || echo NONE)" |
| 49 | + if [[ "${before_hashes[$i]}" != "${after}" ]]; then |
| 50 | + modified=1 |
| 51 | + fi |
| 52 | + i=$((i + 1)) |
| 53 | +done |
| 54 | + |
| 55 | +if ((modified == 1)); then |
| 56 | + printf 'ktlint: found lint issues (use --format to auto-fix); re-stage and re-run.\n' >&2 |
| 57 | + exit 1 |
| 58 | +fi |
| 59 | + |
| 60 | +exit "${status}" |
0 commit comments