高效Git-命令客制化

2024/04/29 | 字数880 | 阅读2分钟


Git原生提供了丰富的命令,但如果这些命令还是不能满足你的需求,git也提供了扩展命令的途径,你可以使用自己熟悉的任何编程语言来写一个自己的命令出来。下面小编用一个bash脚本作为例子,讲一讲扩展git命令的流程:

我们要实现的是一个根据commit信息生成CHANGELOG的功能,需要提供一个起始commit id或者tag标识:

bash
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
## git-changelog
error() {
  echo "ERROR: $*" >&2
  exit 1
}
usage() {
  echo "usage: git changelog <commit or tag>" >&2
  exit 1
}

_prefixes="feature fix doc refact"

[[ $# -ne 1 ]] && usage
git rev-parse $1 >/dev/null 2>&1 || error "invalid commit id $1"

now=$(date +'%Y-%m-%dT%TZ%z')
from=$1
echo changelog:
echo "-------------"
echo "datetime: $now"
echo "baseline: $from"
echo ""

for one in ${_prefixes}; do
  echo "$one:"
  echo "-------------"
  git --no-pager log "${from}..HEAD" --grep="^${one}:" --pretty='%s'
  echo ""
done

将上面的文件保存到一个git-changelog文件,添加执行权限,并将它放到/usr/local/bin目录下,同时确保/usr/local/bin目录在你的$PATH变量中。


接着就可以到任何你的git仓库中,执行:git changelog <start-commit-id>,下面是小编的一个git仓库下的执行结果:

txt
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
changelog:
-------------
datetime: 2024-04-29T10:30:51Z+0800
baseline: 74375de

feature:
-------------
feature: add ttf.name
feature: add hl for keynote terminal commands
feature: add hl for show code in keynode
feature: add github.js for fonts
feature: add defaults.domains.export
feature: add defaults.domains.export
feature: add mac-default.sh
feature: add formatter in nvchad
feature: add go and sql snippets for nvchad
feature: add make snippets for nvchad
feature: new nvchad repo
feature: add nvchad conf

fix:
-------------
fix: feishu.js for cn and en
fix: en-US for feishu

doc:
-------------

refact:
-------------

总结一下,扩展git命令的步骤:

对于上面的可执行文件是用哪种语言开发的,git并不关心;

这是TJ大神写的一些自定义命令,喜欢的话可以拿来用: https://github.com/tj/git-extras

上一篇:Git使用-典型git工作流 下一篇:高效Git-命令别名

【文章不错,鼓励一下】