gpt4 book ai didi

node.js - 调用 git Shortlog -sn 时, Node child_process spawn 挂起

转载 作者:太空宇宙 更新时间:2023-11-03 22:41:12 25 4
gpt4 key购买 nike

我的场景

在我的 Node 应用程序中,我使用 child_process.spawn从当前存储库查询信息

我构建了一个小函数来返回一个 promise ,该 promise 通过命令的响应来解析:

const spawn = require('child_process').spawn;

const gitExec = command => (
new Promise((resolve, reject) => {
const thread = spawn('git', command);
const stdOut = [];
const stdErr = [];

thread.stdout.on('data', (data) => {
stdOut.push(data.toString('utf8'));
});

thread.stderr.on('data', (data) => {
stdErr.push(data.toString('utf8'));
});

thread.on('close', () => {
if (stdErr.length) {
reject(stdErr.join(''));
return;
}
resolve(stdOut.join());
});
})
);

module.exports = gitExec;

调用git分支按预期工作:

gitExec(['branch'])
.then((branchInfo) => {
console.log(branchInfo);
})

(如预期)结果为

    * develop
feature/forever
feature/sourceconfig
feature/testing
master

根据我的理解,这证明了我使用的方法确实有效。

当调用git Shortlog -sn时,生成的进程“挂起”并且不会解析任何内容

gitExec(['shortlog', '-sn'])
.then((shortlogInfo) => {
console.log(shortlogInfo);
})

通过命令行调用git Shortlog -sn我得到了预期的结果:

   154  Andreas Gack
89 Some other dude
6 Whoever else

我的(到目前为止不成功的)尝试

使用 spawnSync (同时更改我的 gitExec 函数以适应同步方法)返回一个记录的对象 - 因此该过程似乎实际上退出 - 但对象的相关 Prop output stdoutstderr 都是空的。
对象的status0,表示命令执行成功

我读过有关必须在生成选项中重新定义 maxBuffer 的内容,但是将其设置为(可笑的)高值或非常小的值都不会在同步或异步中产生差异方法。

shell 选项设置为 true 也不会在上述所有场景中产生影响。

该问题发生在我的 Win10x64 以及运行 Node v6.9.x 或 7.x 的 MacO 上

同时调用别名 git log --pretty=short 也不会提供结果

我的实际问题

  • 有人已经成功通过 child_process.spawn 查询 git Shortlog -sn 了吗?
  • 有人知道 Node 的一个模块可以查询当前本地 git 存储库吗?

我不知何故认为这两个命令gitbranchgitshortlog在内部以不同的方式处理它们的输出。

我很乐意在他们的 github 页面上创建一个问题,但实际上我不知道如何确定该问题的实际根本原因。

非常感谢任何进一步的意见!

最佳答案

git Shortlog 认为它需要从 stdin 读取一些内容,这就是整个过程挂起的原因。要解决这个问题,您可以将 stdin 作为选项从主进程传递,并像往常一样通过管道传输其他所有内容。然后它应该运行。

const spawn = require('child_process').spawn;

const gitExec = command => (
new Promise((resolve, reject) => {
const thread = spawn('git', command, { stdio: ['inherit', 'pipe', 'pipe'] });
const stdOut = [];
const stdErr = [];

thread.stdout.on('data', (data) => {
stdOut.push(data.toString('utf8'));
});

thread.stderr.on('data', (data) => {
stdErr.push(data.toString('utf8'));
});

thread.on('close', () => {
if (stdErr.length) {
reject(stdErr.join(''));
return;
}
resolve(stdOut.join());
});
})
);

module.exports = gitExec;

也许来自 git documentation 的更多上下文:

If no revisions are passed on the command line and either standard input is not a terminal or there is no current branch, git shortlog will output a summary of the log read from standard input, without reference to the current repository.

产生子进程时就是这种情况。因此它期望通过 stdin 传入一些内容。通过将 stdin 设置为主进程,git Shortlog 可以识别终端并因此运行。

关于node.js - 调用 git Shortlog -sn 时, Node child_process spawn 挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44439285/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com