How to write a JavaScript condition that reports if git commands succeed or fail in the terminal?

问题: I am a begginer I am trying to create a VS Code extension that will do 4 git commands for me (checkout, pull, merge and push). My problem is in my condition... I want the...

问题:

I am a begginer

I am trying to create a VS Code extension that will do 4 git commands for me (checkout, pull, merge and push). My problem is in my condition... I want the extension to stop if one of the git command fail in the terminal so I am trying to make an if/else JavaScript condition that will tell if the git command succeeds or fails in the terminal so the extension will stop if the git commands fails and will continue if not.

I have look everywhere on Google and I don't find anything that help me. In my code, I have write a condition for now that is terminal.error() == true even if I know that this command doesn't make any sense. Can someone help me or if you know another way to do this, please tell me.

context.subscriptions.push(vscode.commands.registerCommand('terminalTest.TS', () => {
    const terminal = vscode.window.createTerminal(`TS Terminal #${NEXT_TERM_ID++}`);
    vscode.window.showInformationMessage('Terminal is now open');

    terminal.sendText("git checkout master");
    if (terminal.error() == true) {
        vscode.window.showInformationMessage('Failed to checkout');
    }
    else {
        terminal.sendText('git pull');

回答1:

You would want to look at the response code for that git checkout master shell command. Within the VS Code terminal API, I cannot find a way to do that (although I'm not certain it's not possible).

So instead, as far as I can tell from searching, within a VSCode extension, you would have access to Node.js libraries. This means you can execute the command using the child_process library. This library can use the response codes for commands, as required.

const child_process = require("child_process")
child_process.exec("git checkout master", (error, stdout, stderr) => {
    if (error == 0) {
        // Sucess, now onto 'git pull'
    } else {
        // Failure, abort
    }
});

Hopely a different library would be possible for your project.

And note, if you want more information about why the git checkout master failed, the command uses different response codes for different things (e.g. 128 for no git repo), or you can look at stdout/stderr.

  • 发表于 2019-07-08 00:26
  • 阅读 ( 130 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除