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