clang-format.js 2.0 KB

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