Skip to content

Commit

Permalink
Handle pre-commit paralellism on first installation #3
Browse files Browse the repository at this point in the history
When the hook is run for the first time ktlint is installed. There was a check in the script that checked whether ktlint was already downloaded. Since pre-commit is running the script multiple times in parallel, there was a race condition on the first usage of the hook. In this case some executions would try to execute ktlint although the download wasn't finished yet.

To prevent this we are now protecting the installation by a semaphore.
  • Loading branch information
elmi82 committed Apr 1, 2021
2 parents 64d5031 + a9c6553 commit e733cde
Showing 1 changed file with 20 additions and 4 deletions.
24 changes: 20 additions & 4 deletions run-ktlint.sh
Original file line number Diff line number Diff line change
@@ -1,16 +1,32 @@
#!/usr/bin/env sh
set -euo pipefail
IFS=$'\n\t'

REPOSITORY="https://github.com/pinterest/ktlint"
VERSION=0.41.0
CACHE=".cache"
KTLINT="${CACHE}/ktlint-${VERSION}"
SUCCESS_FILE="${CACHE}/download-finished-${VERSION}"
LOCKFILE="${CACHE}/pre-commit-ktlint-download.lock"

# make sure that lock file gets cleanup up in all cases
trap 'rm -f ${LOCKFILE}' EXIT

mkdir -p "${CACHE}"
if [ ! -f "${KTLINT}" ]
if [ ! -f "${SUCCESS_FILE}" ]
then
echo "Installing ${KTLINT}"
curl -#SLf "${REPOSITORY}/releases/download/$VERSION/ktlint" > "${KTLINT}"
chmod 755 "${KTLINT}"
exec 200>"${LOCKFILE}" || exit 1
flock 200 || exit 1

if [ ! -f "${SUCCESS_FILE}" ]
then
echo "Installing ${KTLINT}"
curl -#SLf "${REPOSITORY}/releases/download/$VERSION/ktlint" > "${KTLINT}"
chmod 755 "${KTLINT}"
touch "${SUCCESS_FILE}"
fi

flock -u 200
fi

${KTLINT} $*

0 comments on commit e733cde

Please sign in to comment.