Pre Commit Hook for JSLint in Mercurial and Git

前端 未结 3 1119
予麋鹿
予麋鹿 2021-02-05 10:09

I want to run JSLint before a commit into either a Mercurial or Git repo is done.

I want this as an automatic step that is set up instead of relying on the developer (ma

相关标签:
3条回答
  • 2021-02-05 10:41

    For git, there are examples in the .git/hooks directory. If you just need the file names for JSLint, you could use git diff --name-only, which in my example will list the names of the files that differ from the current HEAD.

    0 讨论(0)
  • 2021-02-05 10:43

    JSLint with SpiderMonkey

    for js in $(git diff-index --name-only --cached HEAD -- | grep '\.js$'); do
        if jslint.sh $js 2>&1 | grep 'Lint at line' ; then
            echo $js
            exit 1
        else
            echo "js files validated"
            exit 0
        fi  
    done
    
    0 讨论(0)
  • 2021-02-05 10:57

    The following is a variation of @Bitbieger's Git solution that works with Node.js and a local copy of node-jslint (i.e. you need to npm install jslint in your root repository directory).

    Additionally the script:

    • Runs jslint over all .html and .json files as well as .js
    • Only runs jslint over files that have been added, copied or modified. This prevents jslint from erroring on files that have been renamed or deleted.
    • Replicates any jslint errors for the user to see
    • Uses the --indent 4 --white true jslint options to ensure source code consistency

    To get it to work copy the following to .git/hooks/pre-commit and don't forget to chmod +x .git/hooks/pre-commit

    # Pre-commit hook passing files through jslint
    #
    # This ensures that all js, html and json files are valid and conform
    # to expectations.
    
    ROOT_DIR=$(git rev-parse --show-toplevel)
    JSLINT="${ROOT_DIR}/node_modules/.bin/jslint --indent 4 --white true"
    
    for file in $(git diff-index --name-only --diff-filter=ACM --cached HEAD -- | grep -P '\.((js)|(html)|(json))$'); do
        if node $JSLINT $file 2>&1 | grep 'No errors found' ; then
            echo "jslint passed ${file}"
            exit 0
        else
            node $JSLINT $file
            exit 1
        fi  
    done
    
    0 讨论(0)
提交回复
热议问题