I'm trying modify a file within commit-msg
or prepare-commit-msg
hook before its committed.
The problem I'm experiencing is that the modifications are not being committed, the file is getting staged, but the changes only applied in the next commit.
Can someone point me in the right direction, what I'm doing wrong here?
#!/usr/bin/env node
const fs = require("node:fs");
const exec = require('child_process').exec;
//get commit message
const msg = fs.readFileSync(process.argv[2], "utf8");
//add message to file
const content = msg + fs.readFileSync("changes.txt", "utf8");
//save file
fs.writeFileSync("changes.txt", content);
//stage file
exec(`git add changes.txt`, (err, stdout, stderr) =>
{
if (err)
console.error(err);
process.exit(~~err);
});
pre-commit
hook is the only one that can modify the actual contents of the commit. prepare-commit-msg
and commit-msg
are ran later, and they cannot modify the commit contents. Also, the actual commit message is not available in prepare-commit-msg
, only the template that the user sees.
To get the actual commit message and write it to a file that is also included in the commit itself, you would have to use a post-commit
hook to read the commit message, write it to a file, and then amend the previous commit. This seems like a bad idea and I strongly suggest that you don't go with this path.