Skip to content

Commit

Permalink
Merge pull request #8 from trussworks/adh-hadolint
Browse files Browse the repository at this point in the history
Add hadolint hook that downloads binary on run
  • Loading branch information
ahobson authored Apr 14, 2021
2 parents 1333208 + b1000fc commit 37522b5
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
6 changes: 6 additions & 0 deletions .pre-commit-hooks.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,9 @@
entry: /usr/bin/sort -u -o .spelling .spelling
language: script
pass_filenames: false

- id: hadolint
name: Run hadolint Dockerfile linter
description: Run hadolint Dockerfile linter
entry: pre-commit-hadolint
language: script
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,7 @@ will ignore words listed in a `.spelling` file in your repo.
## spelling-sort

Run `sort` on the `.spelling` file used by the `markdown-spellcheck` tool. This keeps the file tidy as it is used.

## hadolint

Run the [hadolint](https://github.com/hadolint/hadolint) Dockerfile linter
52 changes: 52 additions & 0 deletions pre-commit-hadolint
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
#!/usr/bin/env bash

set -euo pipefail

HADOLINT_PREFIX_URL="https://github.com/hadolint/hadolint/releases/download"
HADOLINT_VERSION="v2.1.0"
OS=$(uname -s)
ARCH=$(uname -m)
HADOLINT_BINARY="hadolint-${OS}-${ARCH}"
HADOLINT_URL="${HADOLINT_PREFIX_URL}/${HADOLINT_VERSION}/${HADOLINT_BINARY}"

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
LOCAL_BINARY="${DIR}/${HADOLINT_BINARY}-${HADOLINT_VERSION}"

function mylock() {
# *sigh*
# macOS does not have flock so fall back to perl(!) if it's not
# available
if command -v flock &>/dev/null; then
flock -x 200
else
perl -e 'use Fcntl qw(:flock); open($fh, "<&=", 200) || die "Cannot open"; flock($fh, LOCK_EX) || die "Cannot lock"'
fi
}

# Download the binary if it doesn't already exist
# use the locking pattern from https://linux.die.net/man/1/flock
(
mylock
if [[ ! -x ${LOCAL_BINARY} ]]; then
curl -o "${LOCAL_BINARY}" -L -sSf "${HADOLINT_URL}"
chmod 755 "${LOCAL_BINARY}"
fi
) 200> "${LOCAL_BINARY}.lock"

files=()

# only run hadolint if it looks like a Dockerfile
for f in "$@"; do
case $f in
(Dockerfile*|*/Dockerfile*)
files+=( "${f}" )
;;
esac
done

if [[ "${#files[@]}" -gt 0 ]]; then
exec "${LOCAL_BINARY}" "${files[@]}"
fi

# if no files, exit successfully
exit 0

0 comments on commit 37522b5

Please sign in to comment.