eslint-format.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #!/usr/bin/env node
  2. const spawn = require('child_process').spawnSync;
  3. const filesToCheck = '*.js';
  4. const FORMAT_START = process.env.FORMAT_START || 'main';
  5. const IS_WIN = process.platform === 'win32';
  6. const ESLINT_PATH = IS_WIN ? 'node_modules\\.bin\\eslint.cmd' : 'node_modules/.bin/eslint';
  7. function main (args) {
  8. let fix = false;
  9. while (args.length > 0) {
  10. switch (args[0]) {
  11. case '-f':
  12. case '--fix':
  13. fix = true;
  14. break;
  15. default:
  16. }
  17. args.shift();
  18. }
  19. // Check js files that change on unstaged file
  20. const fileUnStaged = spawn(
  21. 'git',
  22. ['diff', '--name-only', '--diff-filter=d', FORMAT_START, filesToCheck],
  23. {
  24. encoding: 'utf-8'
  25. }
  26. );
  27. // Check js files that change on staged file
  28. const fileStaged = spawn(
  29. 'git',
  30. ['diff', '--name-only', '--cached', '--diff-filter=d', FORMAT_START, filesToCheck],
  31. {
  32. encoding: 'utf-8'
  33. }
  34. );
  35. const options = [
  36. ...fileStaged.stdout.split('\n').filter((f) => f !== ''),
  37. ...fileUnStaged.stdout.split('\n').filter((f) => f !== '')
  38. ];
  39. if (fix) {
  40. options.push('--fix');
  41. }
  42. const result = spawn(ESLINT_PATH, [...options], {
  43. encoding: 'utf-8'
  44. });
  45. if (result.error && result.error.errno === 'ENOENT') {
  46. console.error('Eslint not found! Eslint is supposed to be found at ', ESLINT_PATH);
  47. return 2;
  48. }
  49. if (result.status === 1) {
  50. console.error('Eslint error:', result.stdout);
  51. const fixCmd = 'npm run lint:fix';
  52. console.error(`ERROR: please run "${fixCmd}" to format changes in your commit
  53. Note that when running the command locally, please keep your local
  54. main branch and working branch up to date with nodejs/node-addon-api
  55. to exclude un-related complains.
  56. Or you can run "env FORMAT_START=upstream/main ${fixCmd}".
  57. Also fix JS files by yourself if necessary.`);
  58. return 1;
  59. }
  60. if (result.stderr) {
  61. console.error('Error running eslint:', result.stderr);
  62. return 2;
  63. }
  64. }
  65. if (require.main === module) {
  66. process.exitCode = main(process.argv.slice(2));
  67. }