0
\$\begingroup\$

As in many teams, me and my coworkers are putting ticket number into beginning of each commit message. If your branches are starting with ticket number it is easy to create prepare-commit-msg hook to automate this action, and since I'm a front-end deveoper, I decided to write it as a nodejs script. Look at what I came up with and tell me how to make it better if you will.

#.git/hooks/prepare-commit-msg
#!/usr/bin/env node
const fs = require('fs')
const { exec } = require('child_process')
const COMMIT_EDITMSG = process.argv[2]
exec('git symbolic-ref --short HEAD', (err, stdout) => {
 if (err) throw err
 fs.readFile(
 COMMIT_EDITMSG,
 'utf8',
 (err, message) => {
 if (err) throw err
 fs.writeFile(
 COMMIT_EDITMSG,
 `${stdout.replace(/(-|_).*/, '')} ${message}`.replace(/\n/, ''),
 err => {
 if (err) throw err
 }
 )
 }
 )
})
asked Jun 26, 2018 at 11:51
\$\endgroup\$
3
  • \$\begingroup\$ You most definitely want to be using return console.error(...) in all those error scenarios :) \$\endgroup\$ Commented Jun 28, 2018 at 0:09
  • \$\begingroup\$ Would you advise to throw an error instead of loging it trough console.error? \$\endgroup\$ Commented Jun 28, 2018 at 9:19
  • \$\begingroup\$ even better! Point is, something bad has happened that shouldn't have, you don't want to let the hook continue, with your current code it would. \$\endgroup\$ Commented Jun 28, 2018 at 9:46

1 Answer 1

1
\$\begingroup\$

Outwith the improved error handling as per the comments, another improvement on this be to write the hook using a more synchronous approach e.g.

#.git/hooks/prepare-commit-msg
#!/usr/bin/env node
const { readFileSync, writeFileSync } = require('fs')
const { execSync } = require('child_process')
const COMMIT_EDITMSG = process.argv[2];
const stdout = execSync('git symbolic-ref --short HEAD');
const message = readFileSync(COMMIT_EDITMSG, 'utf-8');
writeFileSync(COMMIT_EDITMSG, `${stdout.replace(/(-|_).*/, '')} ${message}`.replace(/\n/, ''));

This completely eliminates the need for callbacks and, naturally, if an error occurs the commit should be blocked - it's also a lot more succinct and easier to read.

answered Jun 28, 2018 at 10:55
\$\endgroup\$
2
  • \$\begingroup\$ Thank you, to my shame I wasn't been aware of syncronous versions of this functions \$\endgroup\$ Commented Jun 28, 2018 at 11:13
  • \$\begingroup\$ @askhat whoops, that's a mistake, it should be using that! Updated. \$\endgroup\$ Commented Jun 28, 2018 at 11:24

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.