Skip to content

Instantly share code, notes, and snippets.

@mathieucaroff
Created June 5, 2023 08:52
Show Gist options
  • Select an option

  • Save mathieucaroff/39a721d6e3959c0a51e035c984c61ac9 to your computer and use it in GitHub Desktop.

Select an option

Save mathieucaroff/39a721d6e3959c0a51e035c984c61ac9 to your computer and use it in GitHub Desktop.

Revisions

  1. mathieucaroff created this gist Jun 5, 2023.
    34 changes: 34 additions & 0 deletions negateExitCode.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,34 @@
    /**
    * Spawn the given command with its arguments, exit with the inverse of the
    * exit code of the spawned command: exits 0 if the code is anything other
    * than 0, and exits with 1 if the code is 0.
    *
    * Usage:
    *
    * node scripts/utils/negateExitCode.js <command> [<arguments>...]
    *
    * Examples:
    *
    * # print hello and exit with code 1
    * node scripts/utils/negateExitCode.js echo hello
    *
    * # print hello and exit with code 0
    * node scripts\utils\negateExitCode.js bash -c "echo hello; exit 2"
    *
    * # run the commandThatShouldFail and exits with 0 if it does exit with any
    * # non-zero code, and exit with 1 if it exits with code 0.
    * node scripts/utils/negateExitCode.js yarn commandThatShouldFail --argument1 yadaYada
    */

    const { spawnSync } = require('child_process')

    const [_node, _thisFile, command, ...args] = process.argv

    if (process.argv.length < 3) {
    console.error('negateExitCode.js: No command received as argument')
    process.exit(1)
    }

    const subprocess = spawnSync(command, args, { stdio: 'inherit' })

    process.exit(subprocess.status === 0 ? 1 : 0)