由于Grep找不到匹配,防止退出时产生Gulp Spawn Child进程错误

时间:2016-07-12 03:23:00

标签: git bash gulp

在git guppy中使用child_process和Gulp 4我会在任务中生成一个子进程,以响应运行小型bash脚本的git钩子。

BASH SCRIPT

#!/usr/bin/env bash

changed_files="$(git diff-tree -r --name-only --no-commit-id ORIG_HEAD HEAD)"

added_files="$(git diff-tree -r --name-only --diff-filter=AR --no-commit-id ORIG_HEAD HEAD)"

check_run() {
    echo "$changed_files" | grep --quiet "$1" && eval "$2"
}

check_add() {
    echo "$added_files" | grep --quiet "$1" && eval "$2"
}

# Run `npm install` if package.json changed, `bower install` if `bower.json`,
# or `composer install` if composer.json has changed.
check_run package.json "npm install"
check_run bower.json "bower install"
check_run composer.json "composer install"

GULP FILE

gulp.task('post-checkout', gulp.series(
    'post-checkout-install',
    ...
));

gulp.task('post-checkout-install', function () {

    return cp.spawn('sh', ['./bash/git/hooks/post-merge.sh'], {
        stdio: 'inherit',
        cwd: process.cwd()
    });
});

我已经在/.git/hooks中测试了合并后的脚本文件,它运行正常,但是当使用Gulp通过生成的shell执行此操作时,会抛出此错误:

$ gulp post-checkout
[19:48:27] Using gulpfile D:\projects\app\gulpfile.js
[19:48:27] Starting 'post-checkout'...
[19:48:27] Starting 'post-checkout-install'...
[19:48:28] 'post-checkout-install' errored after 200 ms
[19:48:28] Error: exited with error code: 1
    at ChildProcess.onexit (D:\projects\app\node_modules\end-of-stream\index.js:39:23)
    at emitTwo (events.js:87:13)
    at ChildProcess.emit (events.js:172:7)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
[19:48:28] 'post-checkout' errored after 208 ms

TESTS

所以我拆分命令以查看可能导致问题的原因,并且从下面的片段看起来似乎都是由于grep没有在差异列表中找到文件或文件扩展名,这不会导致直接作为gulp hook运行时的任何问题。

# No error just running this by itself and it returns the diff list
git diff-tree -r --name-only --no-commit-id ORIG_HEAD HEAD

# Fails I believe since package.json isn't in the diff list, since the
# same command with .js, .css, and .json fails, but .html passes since
# there are only .html files in the diff list
git diff-tree -r --name-only --no-commit-id ORIG_HEAD HEAD | grep "package.json"

# No error and runs npm install since .html files are in the diff list
git diff-tree -r --name-only --no-commit-id ORIG_HEAD HEAD | grep ".html" && eval "npm install"

那么如何阻止它退出上述错误只是因为列表中没有找到文件或文件类型?我尝试在grep中添加-ef标志,但这也没有用。

更新

这似乎压倒了被抛出的错误。我不确定是否需要退出进程,但无论如何都要添加它并调用完成的回调。这说它仍然无法正常运行。

gulp.task('post-checkout-install', function (done) {

    return cp.spawn('sh', ['./bash/git/hooks/post-merge.sh'], {
        stdio: 'inherit',
        cwd: process.cwd()
    }).on('exit', function (code) {

        done();

        process.exit(code);
    });
});

1 个答案:

答案 0 :(得分:0)

如果您不希望grep的非零退出状态导致check_runcheck_add的非零退出状态,则按如下所示重写它们:

check_run() {
    if echo "$changed_files" | grep --quiet "$1"
    then
        eval "$2"
    fi
}

check_add() {
    if echo "$added_files" | grep --quiet "$1"
    then
        eval "$2"
    fi
}