Now in the package.json
I set "precommit": "lint node internal/scripts/precommit"
, and I want to get all the commited files path in my precommit.js, is there any way to solve this?

- 543
- 1
- 7
- 25
2 Answers
In your script, you can use git
command to get a list of committed files.
var cp=require('child_process')
var output=cp.execSync('cmd /c git show --pretty="" --name-only HEAD').toString()
var files=output.split('\n')
console.log(files)
The files
variable will contain an array of all the files in the last commit.

- 23,232
- 12
- 77
- 117
-
Try to remove the `cmd /c` on linux. – Aminadav Glickshtein Jan 10 '18 at 10:37
-
I test it and find that the result files is from top 1 commit, but the result which I want is the files before commit, because I will run this script during `precommit` rather than after commit – SmallTown NE Jan 10 '18 at 12:53
-
So do you want the files that you put in stage (`git add`)? If so use `git diff --name-only --cached` – Aminadav Glickshtein Jan 10 '18 at 13:14
-
Thanks for your answer! – SmallTown NE Jan 11 '18 at 05:31
From "Git pre-commit hook : changed/added files", the actual Git command would be:
git diff --cached --name-only --diff-filter=ACM -z | xargs -0 ...
You can see one possible usage in comes from templates/hooks--pre-commit.sample
.
It is also actually used in the JavaScript Standard Style GitHub repo.
Finally, do use spawnSync
, as in "Catching Fatal Errors with Node.js child_process
"
The best way to catch errors without letting your app brick is by using the process'
spawn
(or in this casespawnSync
) method:
var childProcess = require('child_process');
var commitMessage = (function() {
var spawn = childProcess.spawnSync('git', ['log', '--format=%B', '-n', '1']);
var errorText = spawn.stderr.toString().trim();
if (errorText) {
console.log('Fatal error from `git log`. You must have one commit before deploying.');
throw new Error(errorText);
}
else {
return spawn.stdout.toString().trim();
}
})();
With this method you can check the stderr buffer first; if there's a String from it you know it errored out, if no error text then the process was clean!
Adapt this method to your hook case, and change its Git command by the one suggested above.

- 1,262,500
- 529
- 4,410
- 5,250