Skip to content

Instantly share code, notes, and snippets.

@jeekl
Created March 4, 2013 16:32
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jeekl/5083519 to your computer and use it in GitHub Desktop.
Save jeekl/5083519 to your computer and use it in GitHub Desktop.
git pre-commit hook to validate json objects so you don't commit broken json.
#!/usr/bin/env bash
# Runs all .json or .js files through pythons json lint tool before commiting,
# to make sure that you don't commit broken json objects.
git_dir=$(git rev-parse --show-toplevel)
for file in $(git diff-index --name-only --diff-filter=ACM --cached HEAD -- \
| grep -P '\.((js)|(json))$'); do
python -mjson.tool $file 2> /dev/null
if [ $? -ne 0 ] ; then
echo "Lint check of JSON object failed. Your changes were not commited."
echo "in $git_dir/$file:"
python -mjson.tool $file
exit 1
fi
done
@scheler
Copy link

scheler commented Sep 28, 2015

Does this work on JavaScript files too for you? I get - No JSON object could be decoded - from python -m json.tool

@pulpbill
Copy link

pulpbill commented Mar 30, 2017

Thanks for the script. I'm also using it to check if the json file is valid against sensu's conf:

#Check with sensu-client -c -d if the json is valid for sensu server.
git_dir=$(git rev-parse --show-toplevel)

for file in $(git diff-index --name-only --diff-filter=ACM --cached HEAD -- \
    | grep -P '\.((js)|(json))$'); do
    /opt/sensu/bin/sensu-client --validate_config -c /etc/sensu/config.json -d /etc/sensu/conf.d/ $file 2> /dev/null
    if [ $? -ne 0 ] ; then
        echo "Though the file is a valid json, it's not a valid sensu file. Your changes were not commited."
        echo "in $git_dir/$file:"
        $file
        exit 1
    fi
done

@adv0r
Copy link

adv0r commented Jun 5, 2017

the grep part doesn't work to for me on macosx. Executing it will get me a grep usage

[develop][~/Desktop/repo/.git/hooks]$ ./pre-commit
usage: grep [-abcDEFGHhIiJLlmnOoqRSsUVvwxZ] [-A num] [-B num] [-C[num]]
	[-e pattern] [-f file] [--binary-files=value] [--color=when]
	[--context[=num]] [--directories=action] [--label] [--line-buffered]
	[--null] [pattern] [file ...]

I wonder if the repository structure is expected to be in a certain way

@chefren
Copy link

chefren commented Aug 10, 2017

@adv0r, macosx's grep provides "-E (extended grep)" option, try using grep -E '\.((js)|(json))$'

@dataf3l
Copy link

dataf3l commented Jul 12, 2019

@scheler "Does this work on JavaScript files too for you" -> you can use g instead of git, maybe?
https://github.com/dataf3l/g

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment