function spawnClangFormat()

in index.js [47:122]


function spawnClangFormat(args, done, stdio) {
  // WARNING: This function's interface should stay stable across versions for the cross-version
  // loading below to work.
  let nativeBinary;

  try {
    nativeBinary = getNativeBinary();
  } catch (e) {
    setImmediate(() => done(e));
    return;
  }

  if (args.find(a => a === '-version' || a === '--version')) {
    // Print our version.
    // This makes it impossible to format files called '-version' or '--version'. That's a feature.
    // minimist & Co don't support single dash args, which we need to match binary clang-format.
    console.log(`clang-format NPM version ${VERSION} at ${LOCATION}`);
    args = ['--version'];
  }

  // extract glob, if present
  const filesGlob = getGlobArg(args);

  if (filesGlob) {
    // remove glob from arg list
    args = args.filter(arg => arg.indexOf(GLOB_OPTION) === -1);

    glob(filesGlob, function(err, files) {
      if (err) {
        done(err);
        return;
      }

      // split file array into chunks of 30
      let i, j, chunks = [], chunkSize = 30;

      for (i = 0, j = files.length; i < j; i += chunkSize) {
        chunks.push(files.slice(i, i + chunkSize));
      }

      // launch a new process for each chunk
      async.series(
          chunks.map(function(chunk) {
            return function(callback) {
              const clangFormatProcess = spawn(nativeBinary, args.concat(chunk), {stdio: stdio});
              clangFormatProcess.on('close', function(exit) {
                if (exit !== 0)
                  callback(errorFromExitCode(exit));
                else
                  callback();
              });
            };
          }),
          function(err) {
            if (err) {
              done(err);
              return;
            }
            console.log('\n');
            console.log(
                `ran clang-format on ${files.length} ${files.length === 1 ? 'file' : 'files'}`);
            done();
          });
    });
  } else {
    const clangFormatProcess = spawn(nativeBinary, args, {stdio: stdio});
    clangFormatProcess.on('close', function(exit) {
      if (exit) {
        done(errorFromExitCode(exit));
      } else {
        done();
      }
    });
    return clangFormatProcess;
  }
}