|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +/** |
| 4 | + * Script to set our template as commit message template. This depends on husky |
| 5 | + * parameters $HUSKY_GIT_PARAMS which gives me the git commit message template |
| 6 | + * being used for commit message. By default this is ./git/COMMIT_MSG file |
| 7 | + */ |
| 8 | + |
| 9 | +/** |
| 10 | + * Here we are using only the first parameter of $HUSKY_GIT_PARAMS variable i.e. |
| 11 | + * the commit message file. We will update that file with our template file |
| 12 | + * content |
| 13 | + */ |
| 14 | + |
| 15 | +/** |
| 16 | + * Usage examples: |
| 17 | + * Add this script in your hooks section of husky. We require 1.x version of |
| 18 | + * husky so this will not work for 0.x version of husky. |
| 19 | + * |
| 20 | + * Example: |
| 21 | + * ```javascript |
| 22 | + * // .huskyrc.js |
| 23 | + * module.exports = { |
| 24 | + * hooks: { |
| 25 | + * "prepare-commit-msg": "git-commit-template .gitmessage", |
| 26 | + * }, |
| 27 | + * }; |
| 28 | + * |
| 29 | + * ``` |
| 30 | + */ |
| 31 | + |
| 32 | +const fs = require("fs"); |
| 33 | +const path = require("path"); |
| 34 | +const COMMIT_MSG_FILE_NAME = ".commit-msg"; |
| 35 | + |
| 36 | +// Default template file but will be overridden with input argument if provided |
| 37 | +let templateFile = path.join(__dirname, `../${COMMIT_MSG_FILE_NAME}`); |
| 38 | + |
| 39 | +/** |
| 40 | + * If we have 3rd argument i.e. file name then use that as template |
| 41 | + * e.g. |
| 42 | + * ./bin/setup-template.js .gitmessage |
| 43 | + * // Then argv will look like this: |
| 44 | + * argv = [ "node", "./bin/setup-template.js", ".gitmessage" ] |
| 45 | + */ |
| 46 | +if (process.argv[2]) { |
| 47 | + templateFile = path.join(process.cwd(), process.argv[2]); |
| 48 | +} |
| 49 | + |
| 50 | +/** |
| 51 | + * Sample git params are [ "./git/COMMIT_MSG", "commit", "HEAD" ] in case of |
| 52 | + * --amend flag |
| 53 | + */ |
| 54 | +const gitParams = process.env["HUSKY_GIT_PARAMS"].split(" "); |
| 55 | + |
| 56 | +/** |
| 57 | + * We are running our logic only in case of empty commit message. In other |
| 58 | + * scenarios commit message would already be present and no longer needs our |
| 59 | + * template thus skip it. |
| 60 | + */ |
| 61 | +if (gitParams.length === 1) { |
| 62 | + const commitMsgFile = gitParams[0]; |
| 63 | + |
| 64 | + let gitFileContent = fs.readFileSync(commitMsgFile, { encoding: "utf8" }); |
| 65 | + const templateFileContent = fs.readFileSync(templateFile, { |
| 66 | + encoding: "utf8", |
| 67 | + }); |
| 68 | + |
| 69 | + gitFileContent = templateFileContent + gitFileContent; |
| 70 | + |
| 71 | + fs.writeFileSync(commitMsgFile, gitFileContent, { encoding: "utf8" }); |
| 72 | +} |
0 commit comments