在 yeoman 生成器中推送到 git 回购?

Push to git repo in a yeoman generator?

我希望有人能稍微解释一下 Yeoman 的 spawnCommand() 方法是如何工作的。我正在开发一个生成器,我希望它能初始化一个 git 存储库,最后提交并推送生成的应用程序。

我的印象是第二个参数是一个数组,它是一个命令数组,在进程中 运行。所以,像这样的东西会 运行 'git init' 然后是 'git remote add origin',等等

end: function () {
    if(this.repo !== '') {
      this.spawnCommand('git', ['init', 
        'remote add origin ' + this.repo, 
        'add --all', 
        'commit -m "initial commit from generator"', 
        'push -u origin master']
      );
    }
    console.log(yosay('I believe we\'re done here.'));
}

不幸的是,它只是抛出一个使用错误:

usage: git init [-q | --quiet] [--bare] ...

然后我尝试自己做 init,然后像这样做其他的:

end: function () {
    if(this.repo !== '') {
      this.spawnCommand('git', ['init']);
      this.spawnCommand('git', ['remote add origin ' + this.repo, 
        'add --all', 
        'commit -m "initial commit from generator"', 
        'push -u origin master']
      );
    }
    console.log(yosay('I believe we\'re done here.'));
}

然后输出对我来说意义不大:

git: 'remote add origin {URL}' is not a git command. See 'git --help'.
Initialized empty Git repository in /my/project/.git/

这让我觉得它们是 运行 异步的,这可能是添加远程源失败的原因,但除此之外我很困惑。

是否有另一种方法让生成器推送到 git,或者我最好不要尝试自动执行初始推送?

编辑:

运行 每个命令作为它自己的 spawnCommand() 也不起作用。

this.spawnCommand('git', ['init']);
this.spawnCommand('git', ['remote add origin ', this.repo]);
this.spawnCommand('git', ['add --all']);
this.spawnCommand('git', ['commit -m "initial commit from generator"']);
this.spawnCommand('git', ['push -u origin master']);

输出:

error: invalid key: pager.remote add origin 
error: invalid key: pager.add --all
error: invalid key: alias.remote add origin
error: invalid key: alias.add --all
error: invalid key: pager.commit -m "initial commit from generator"
error: invalid key: pager.push -u origin master
Initialized empty Git repository in /my/project/.git/
error: invalid key: alias.commit -m "initial commit from generator"
error: invalid key: alias.push -u origin master
git: 'remote add origin ' is not a git command. See 'git --help'.
git: 'push -u origin master' is not a git command. See 'git --help'.
git: 'add --all' is not a git command. See 'git --help'.
git: 'commit -m "initial commit from generator"' is not a git command. See 'git --help'.

开始认为这可能不是最好的方法。

每个 git 命令使用一个 this.spawnCommandSync() 运行。

this.spawnCommandSync('git', ['init']);
this.spawnCommandSync('git', ['remote', 'add', 'origin', this.repo]);
this.spawnCommandSync('git', ['add', '--all']);
this.spawnCommandSync('git', ['commit', '-m', '"initial commit from generator"']);
this.spawnCommandSync('git', ['push', '-u', 'origin', 'master']);

该数组是一个字符串参数数组。这是与 node.js spawn 相同的界面 - 除了包装 cross-spawn 以支持 windows 之外没有任何魔法。

this.spawnCommand() 是异步的,所以如果你使用它,你需要控制流程,这样命令就不会同时获得 运行 并且可能顺序错误.考虑到这是一个 yeoman 生成器,使用同步命令通常就足够了。