🎉被动添加emoji使commit log生动起来

127 阅读1分钟

前言😋

  一般来说我们会使用husky,commitlint来规范我们的提交,定义诸如feat、fix之类的类型。例如下方两张图片:

  

  如果你和我一样更喜欢右图带有emoji的提交记录,那么可以考虑继续看下去了。手写emoji是不太现实的,我们会用commitizen为我们编写一个提交模板来让我们选择,但在实际的体验当中,我发现更改提交命令、选择模板->编辑->再选择->编辑->结束。这一过程和一行命令完成"类别+描述"相比起来较为繁琐。于是我就想到我们既然有husky的钩子,为什么不写一个脚本来自动帮我们写入emoji呢?

正文😱

首先,我们需要在husky的commit-msg文件中的加入这么一行代码

# 注意要是最后一句,过掉前置的校验。
node "$(dirname -- "$0")/prefix-emoji.js" "$1"

然后,我们需要编写prefix-emoji.js文件,与commit-msg同级

import { readFileSync, writeFileSync } from 'fs'

const EMOJI_MAP = {
  init: '🌱',
  feat: '✨',
  refactor: '♻️',
  fix: '🚨',
  format: '🎨',
  clean: '🔥',
  chore: '🚀',
  release: '🎉'
}

// 找到对应的commit type并替换
const msg = readFileSync(process.argv[2], 'utf8')
const typeMatch = msg.match(/([^:]*):/)
const type = typeMatch ? typeMatch[1] : null
const typeEmoji = type ? EMOJI_MAP[type] : null
if (typeEmoji) {
  // 写回commit msg文件
  const withEmojiMsg = `${typeEmoji} ${msg}`
  writeFileSync(process.argv[2], withEmojiMsg, 'utf8')
}

结束语🥺

  这只是一个简单的思路,主要是看类似添加emoji的文章都是推荐的使用commitizen,但我是感觉没有什么使用体验。以上代码触发的过程以及具体要更改的内容还需要根据自己的项目去做调整。 👋👋👋