clang-format.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #!/usr/bin/env node
  2. const spawn = require('child_process').spawnSync;
  3. const path = require('path');
  4. const filesToCheck = ['*.h', '*.cc'];
  5. const CLANG_FORMAT_START = process.env.CLANG_FORMAT_START || 'main';
  6. function main(args) {
  7. let fix = false;
  8. while (args.length > 0) {
  9. switch (args[0]) {
  10. case '-f':
  11. case '--fix':
  12. fix = true;
  13. default:
  14. }
  15. args.shift();
  16. }
  17. let clangFormatPath = path.dirname(require.resolve('clang-format'));
  18. const options = ['--binary=node_modules/.bin/clang-format', '--style=file'];
  19. if (fix) {
  20. options.push(CLANG_FORMAT_START);
  21. } else {
  22. options.push('--diff', CLANG_FORMAT_START);
  23. }
  24. const gitClangFormatPath = path.join(clangFormatPath,
  25. 'bin/git-clang-format');
  26. const result = spawn('python', [
  27. gitClangFormatPath,
  28. ...options,
  29. '--',
  30. ...filesToCheck
  31. ], { encoding: 'utf-8' });
  32. if (result.stderr) {
  33. console.error('Error running git-clang-format:', result.stderr);
  34. return 2;
  35. }
  36. const clangFormatOutput = result.stdout.trim();
  37. // Bail fast if in fix mode.
  38. if (fix) {
  39. console.log(clangFormatOutput);
  40. return 0;
  41. }
  42. // Detect if there is any complains from clang-format
  43. if (clangFormatOutput !== '' &&
  44. clangFormatOutput !== ('no modified files to format') &&
  45. clangFormatOutput !== ('clang-format did not modify any files')) {
  46. console.error(clangFormatOutput);
  47. const fixCmd = 'npm run lint:fix';
  48. console.error(`
  49. ERROR: please run "${fixCmd}" to format changes in your commit
  50. Note that when running the command locally, please keep your local
  51. main branch and working branch up to date with nodejs/node-addon-api
  52. to exclude un-related complains.
  53. Or you can run "env CLANG_FORMAT_START=upstream/main ${fixCmd}".`);
  54. return 1;
  55. }
  56. }
  57. if (require.main === module) {
  58. process.exitCode = main(process.argv.slice(2));
  59. }