Mercurial和Git中的JSLint预提交挂钩

时间:2009-12-03 04:41:52

标签: git mercurial jslint pre-commit-hook

我想在提交Mercurial或Git repo之前运行JSLint。

我希望这是一个自动步骤,而不是依赖于开发人员(主要是我),记住之前运行JSLint。我通常在开发时运行JSLint,但是想要在JS文件上指定一个合同,它们在提交到repo之前传递JSLint。

对于Mercurial,this page列出了预先提交的语法,但似乎唯一可用的变量是提交中涉及的parent1和parent2变更集ID。我真正想要的是提交涉及的文件名列表,以便我可以选择.js文件并对它们运行jslint。

Similar issue for GIT,作为预提交脚本的一部分提供的默认信息似乎有限。

可能有用的是调用hg status / git status作为precommit脚本的一部分,解析该输出以查找JS文件,然后以这种方式进行工作。我希望有一些更简单的东西,我不确定调用状态作为预先提交钩子的一部分是否反映了正确的信息。例如在Git中,如果尚未添加更改文件,但git commit使用-a,那么文件是否会在git status输出的正确部分中显示为提交集的一部分?

更新:我的工作正常,可在此处查看:http://github.com/jrburke/dvcs_jslint/

3 个答案:

答案 0 :(得分:11)

以下是@ Bitbieger的Git解决方案的变体,它与Node.jsnode-jslint的本地副本一起使用(即您需要在根存储库目录中npm install jslint)。

另外脚本:

  • 在所有.html和.json文件以及.js
  • 上运行jslint
  • 仅对已添加,复制或修改的文件运行jslint。这可以防止jslint在已重命名或删除的文件上出错。
  • 复制任何jslint错误以供用户查看
  • 使用--indent 4 --white true jslint选项确保源代码一致性

要使其正常工作,请将以下内容复制到.git/hooks/pre-commit,不要忘记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

答案 1 :(得分:2)

对于git,.git / hooks目录中有一些例子。如果您只需要JSLint的文件名,则可以使用git diff --name-only,在我的示例中将列出与当前HEAD不同的文件的名称。

答案 2 :(得分:1)

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