Did you know that Git can be customized to your needs in a multitude of ways?
您是否知道 Git 可以通过多种方式根据您的需求进行定制?

Creating aliases in Git is a powerful feature that allows you to define "shortcuts" for longer Git commands (and more). For some, it’s just a tool to make command-line Git usage survivable, but I will show you that Git aliases are so powerful they can contribute to making command-line the preferred and most efficient way to use Git.
在 Git 中创建别名是一项强大的功能,它允许您为更长的 Git 命令(以及更多命令)定义“快捷方式”。对于某些人来说,它只是一个让命令行 Git 使用变得可行的工具,但我将向您展示 Git 别名是如此强大,它们可以帮助使命令行成为使用 Git 的首选且最有效的方式。

The main motivation for creating Git aliases could be one or more of the following:
创建 Git 别名的主要动机可能是以下一项或多项:

  • Optimize: Create shortcuts for frequent Git commands.
    优化:为常用的 Git 命令创建快捷方式。
  • Customize: Make Git behave how you want or support team-agreed habits.
    定制:让 Git 按照您想要的方式运行或支持团队商定的习惯。
  • Memorize: Easy-to-remember shortcuts for complex operations.
    记忆:易于记忆的复杂操作快捷键。

In part one of my blog series, I will take you on a journey from the very humble basics, introducing Git aliases that just save typing longer commands, up to more advanced features that even many seasoned Git veterans have never used.
在我的博客系列的第一部分中,我将带您踏上一段旅程,从非常简单的基础知识开始,介绍只需键入较长命令的 Git 别名,再到甚至许多经验丰富的 Git 老手从未使用过的更高级功能。

Part two continues on from there, introducing even more advanced concepts and venturing into truly “out there” uses of Git aliases, including some downright crazy examples, before discussing alternatives for solving the same needs.
第二部分继续从这里开始,介绍更先进的概念,并尝试真正“外面”使用 Git 别名,包括一些彻头彻尾疯狂的示例,然后再讨论解决相同需求的替代方案。

Learning and understanding these techniques, whether used for aliases you steal from others or venturing into pushing the boundaries yourself, will make you a more efficient and powerful Git user and hopefully make your day-to-day life with Git more enjoyable. Along the way, you will probably also learn a few tips and tricks and explore corners of Git that you weren’t even aware of.
学习和理解这些技术,无论是用于从别人那里窃取的别名还是自己冒险突破界限,都将使您成为更高效、更强大的 Git 用户,并有望让您使用 Git 的日常生活变得更加愉快。在此过程中,您可能还会学到一些提示和技巧,并探索您甚至不知道的 Git 角落。

What are Git aliases, and how do we set them up?
什么是 Git 别名,我们如何设置它们?

Git aliases are substitutions for Git subcommands in the same way that, e.g., Bash aliases are substitutions for other Bash commands or scripts. Git simply allows you to define your own Git commands that do what you want and can be used seamlessly along with the built-in commands.
Git 别名是 Git 子命令的替代,就像 Bash 别名是其他 Bash 命令或脚本的替代一样。 Git 只是允许您定义自己的 Git 命令来执行您想要的操作,并且可以与内置命令无缝地使用。

Aliases are defined in the Git config hierarchy, but as we usually want them to work everywhere on our machine, the global configuration is their natural home.
别名是在 Git 配置层次结构中定义的,但由于我们通常希望它们在我们计算机上的任何地方都可以工作,因此全局配置是它们的自然家园。

You can add aliases either by directly editing your global config file or using the git config command.
您可以通过直接编辑全局配置文件或使用 git config 命令来添加别名。

To create your first simple alias, just try:
要创建您的第一个简单别名,只需尝试:

$ git config --global alias.st status

This will add a new line to the [alias] section of your global config file and create the section if it isn't already there. Let's have a look:
这将在全局配置文件的 [alias] 部分添加一个新行,并创建该部分(如果尚不存在)。我们来看一下:

$ cat ~/.gitconfig
[user]
   name = Jan Krag
   email = jan.krag@eficode.com
[alias]
   st = status
Congratulations, you have your first alias and can now type:
恭喜,您拥有了第一个别名,现在可以输入:

git st
Instead of: 代替:
git status

For more complex aliases, later on your journey, I suggest that you simply open ~/.gitconfig in your preferred editor and add or modify your aliases directly there.
对于更复杂的别名,在您稍后的旅程中,我建议您只需在首选编辑器中打开 ~/.gitconfig 并直接在其中添加或修改别名即可。

Level 1: The lazy typer
第一级:懒惰的打字者

Ok, let's get started with the first level. I am lazy and simply want to optimize my typing of commands I use hundreds of times a day or to handle common typos I frequently make.
好的,让我们开始第一层。我很懒,只是想优化每天使用数百次的命令输入,或者处理我经常犯的常见拼写错误。

We have already seen the st suggestion above, but here are a few more common examples of simple shortcuts:
我们已经看到了上面的 st 建议,但这里有一些更常见的简单快捷方式的示例:

[alias]
    s  = status
    st = status
    c = commit
    sw = switch
    br = branch

For "common typo" style aliases, these are a personal preference. Create aliases for whichever commands your fingers can't type. My personal nemesis is switch, but I have just resolved to always use the short "sw" suggested above instead of creating aliases for all the possible typos I can make in that one word. But here are a few examples for inspiration:
对于“常见拼写错误”风格的别名,这些是个人偏好。为您的手指无法输入的命令创建别名。我个人的克星是 switch ,但我刚刚决定始终使用上面建议的短“ sw ”,而不是为我在该单词中可能出现的所有可能的拼写错误创建别名。但这里有一些灵感的例子:

[alias]
    comit = commit
    swicht = switch
    statut = status

Now, at this time you might already be thinking about which Git commands are your best candidates for aliasing. I came up with an interesting answer years ago. Just like Git, my shell (Bash, Zsh) also supports aliases. So I created the following shell alias in my .bashrc and .zshrc config files:
现在,您可能已经在考虑哪些 Git 命令最适合使用别名。几年前我想出了一个有趣的答案。就像 Git 一样,我的 shell(Bash、Zsh)也支持别名。因此,我在 .bashrc.zshrc 配置文件中创建了以下 shell 别名:

alias frequentgit='history | cut -c 8- | grep git | sort | uniq -c  | sort -n -r | head -n 10'(Note: This is a shell alias, not a Git alias).
(注意:这是 shell 别名,而不是 Git 别名)。
 
If I run this alias at any point in time, it will look through my shell history and list the most frequently used Git commands.
如果我在任何时间点运行此别名,它都会查看我的 shell 历史记录并列出最常用的 Git 命令。

Git command

Some of them might already be existing aliases (here slog, st, and glog), but the others might very well be good candidates for you to "shorten" or to remember using aliases you have already made. The only reason I use "git status" so frequently, despite my "git st" alias, is that I deliver a lot of Git training classes, where I commit myself to using the actual commands.
其中一些可能已经是现有别名(此处为 slog、st 和 glog),但其他别名很可能是您“缩短”或记住使用已经创建的别名的良好候选者。尽管我有“ git st ”别名,但我如此频繁地使用“ git status ”的唯一原因是我提供了大量的 Git 培训课程,在这些课程中我致力于使用实际的命令。

Level 2: Simple options to avoid typing daily option flags
第 2 级:简单选项,避免输入每日选项标志

So, time to move up a notch on the Git alias volume control. Aliases also allow us to add "options" to the Git commands we are aliasing, so let's see how we can utilize that.
因此,是时候在 Git 别名音量控制上提升一个档次了。别名还允许我们向我们要别名的 Git 命令添加“选项”,所以让我们看看如何利用它。

The most common use case is creating easy aliases for common variants of Git log output.
最常见的用例是为 Git 日志输出的常见变体创建简单的别名。

E.g.: 例如。:

[alias]
    last  = log -1
    lo = log --oneline
    l5 = log --oneline -5

Another great suggestion is to use this feature to create those pesky "missing" Git commands that you think should have existed and where you might struggle to remember which exact command and option you have to use to achieve that very common task.
另一个很好的建议是使用此功能来创建那些令人讨厌的“缺失”Git 命令,您认为这些命令应该存在,并且您可能很难记住必须使用哪个确切命令和选项来完成该非常常见的任务。

amend = commit --amend
untrack = rm --cached
unadd = restore --staged
Remember that aliases are a personal preference. You have to make the aliases that make sense to you for commands that you might actually use (and understand). More advanced examples in this category could be things like:
请记住,别名是个人喜好。您必须为您可能实际使用(和理解)的命令创建对您有意义的别名。此类别中更高级的示例可能是:
pleasepush = push --force-with-lease
gg = grep -E --line-number
softadd = add --intent-to-add
catp = cat-file -p

Admittedly, many Git users may have never heard about these Git commands and options, let alone used them. This makes these aliases either useless or a great learning opportunity.
不可否认,许多 Git 用户可能从未听说过这些 Git 命令和选项,更不用说使用它们了。这使得这些别名要么毫无用处,要么成为一个很好的学习机会。

Level 3: Complex arguments help us remember rarely-used commands
第三级:复杂的参数帮助我们记住很少使用的命令

The next level on our journey is to investigate using aliases for commands that also take complex arguments.
我们旅程的下一个层次是研究对也采用复杂参数的命令使用别名。

[alias]
foo = <subcommand> <option> <arg...> <option> <arg...>    

So far, we have mainly focused on aliasing frequently or commonly used commands, but since we can now shorten much more complex commands, we might also find it useful to go in the other direction and use aliases for:
到目前为止,我们主要关注频繁或常用命令的别名,但由于我们现在可以缩短更复杂的命令,因此我们可能还会发现朝另一个方向使用别名很有用:

  • Infrequently used hard-to-remember Git tasks.
    不常用且难以记住的 Git 任务。
  • Making hard-to-type commands handier.
    使难以输入的命令变得更加方便。

Together, this allows you to use nice Git features that you might otherwise not bother with.
总之,这使您可以使用 Git 的一些功能,否则您可能不会介意这些功能。


# Diff of last commit
dlc = diff --cached HEAD^ 

# list all defined aliases
aliases = config --get-regexp alias

# Find very first commit
first = rev-list --max-parents=0 HEAD

# what would be merged
incoming = log HEAD..@{upstream}

# what would be pushed
outgoing = log @{upstream}..HEAD
outgoing = log @{u}..

# List all commits (on this branch) made by me
mycommits = log --author=\".*[Jj]an\\s*[Kk]rag.*\"

As you can see, I have described the aliases "inline" in the examples above by using the ability to add # comments in your config file. This is not only to make the example easier, but to strongly suggest that you do this as well in your actual config. It took me way too many years to learn the hard way to do this, and now I have numerous weird aliases and other settings collected that I can't quite remember the purpose of.
正如您所看到的,我在上面的示例中通过使用在配置文件中添加 # 注释的功能描述了“内联”别名。这不仅是为了使示例更容易,而且强烈建议您在实际配置中也这样做。我花了很多年的时间才学会了执行此操作的艰难方法,现在我收集了许多奇怪的别名和其他设置,但我不太记得它们的用途。

Let's look at a few more specific and often-used examples from my collection. This time I will actually show you the results. I will show you a useful diff alias, but first, the "before" view running git diff on a markdown file.
让我们看一下我收集的一些更具体且常用的示例。这次我将实际向大家展示结果。我将向您展示一个有用的 diff 别名,但首先是在 markdown 文件上运行 git diff 的“之前”视图。

Git diff

Now let's add an alias:
现在让我们添加一个别名:

wdiff = diff -w --word-diff=color --ignore-space-at-eol

And use that instead:
并使用它来代替:

Git wdiff

This is obviously much cleaner and easier to grasp. It is not the alias itself that is doing the magic; these are built-in features in Git. But the alias makes it useful in my daily life because I can't be bothered to remember to type: git diff -w --word-diff=color --ignore-space-at-eol every time.
这显然更加清晰并且更容易掌握。发挥魔力的并不是别名本身,而是别名本身。这些是 Git 中的内置功能。但别名使它在我的日常生活中很有用,因为我懒得每次都记住输入: git diff -w --word-diff=color --ignore-space-at-eol

Let us define: 让我们定义:

[alias]
structure = log --oneline --simplify-by-decoration --graph --all
And then run the command on a huge repo:
然后在一个巨大的存储库上运行命令:

$ git structure

Git

The shown snippet covers a range of over 3,000 commits in the Tensorflow repo by just showing the commits that are "labeled" (tags or branch heads).
显示的代码片段仅显示“标记”(标签或分支头)的提交,涵盖了 Tensorflow 存储库中 3,000 多个提交。

To close this level off, and lead nicely into the next one, let’s look at what’s probably the most beneficial use of aliases with complex arguments: The ability to create even more customized git log commands that suit your preference by utilizing custom formats. I don't want this to become a tutorial on the actual formatting options, so let's just dive right in, and you will catch the drift. This is all thoroughly documented in the Pretty formats section of git help log.
为了结束这个级别,并很好地进入下一个级别,让我们看看具有复杂参数的别名最有益的用途是什么:能够通过利用自定义格式创建更适合您偏好的自定义 git log 命令。我不希望这成为有关实际格式选项的教程,所以让我们直接深入,您就会明白其中的要点。这一切都在 git help log 的漂亮格式部分中有详细记录。

I present to you, my daily driver:
我向您介绍我的日常司机:

slog = log --pretty=format:'%C(auto)%h %C(red)%as %C(blue)%aN%C(auto)%d%C(green) %s'

Git slog

Level 4: Pretty formats - clean up your aliases with reusability
第 4 级:漂亮的格式 - 通过可重用性清理别名

For this level, let us venture outside the immediate realm of Git aliases, and I will teach you how to use the little-known feature of custom pretty formats to clean up your aliases and vastly improve reusability.
对于这个级别,让我们冒险超越 Git 别名的直接领域,我将教您如何使用自定义漂亮格式的鲜为人知的功能来清理别名并极大地提高可重用性。

We saw above how I utilize custom formatting fields to craft exactly the log output I prefer, and this is all nice and good until you realize that I used to have all of the following:
我们在上面看到了如何利用自定义格式字段来精确制作我喜欢的日志输出,这一切都很好,直到您意识到我曾经拥有以下所有内容:

slog = log --pretty=format:'%C(auto)%h %C(red)%as %C(blue).....
#(For those lazy days).
l = log --pretty=format:'%C(auto)%h %C(red)%as %C(blue).....
l1 = log -1 --pretty=format:'%C(auto)%h %C(red)%as %C(blue).....
l5 = log -5 --pretty=format:'%C(auto)%h %C(red)%as %C(blue).....
l10 = log -10 --pretty=format:'%C(auto)%h %C(red)%as %C(blue).....
l20 = log -20 --pretty=format:'%C(auto)%h %C(red)%as %C(blue).....

(Actual aliases were much longer but all the same format string).
(实际别名要长得多,但格式字符串相同)。

And many similar ones. This made it really annoying every time I wanted to tweak the format, or coloring, etc.
还有很多类似的。每次我想调整格式或颜色等时,这都变得非常烦人。

These days, in more recent versions of Git, aliases may refer to others, so the above can be vastly improved, e.g.:
如今,在最新版本的 Git 中,别名可以引用其他别名,因此可以大大改进上述内容,例如:

l1 = slog -1
l5 = slog -5

But it turns out that there is a better option.
但事实证明还有更好的选择。

You may know that Git has some built-in "pretty" formats that you can use in your log, like:
您可能知道 Git 有一些内置的“漂亮”格式,您可以在日志中使用它们,例如:

git log --pretty=oneline
git log --pretty=full
git log --pretty=raw

(See the above-linked documentation for more coverage).
(有关更多内容,请参阅上面链接的文档)。

Way too late in my journey, I discovered that Git allowed me to define my own custom "pretty" formats in Git config, but when I found this feature, it was awesome!
在我的旅程中为时已晚,我发现 Git 允许我在 Git 配置中定义自己的自定义“漂亮”格式,但是当我发现这个功能时,它太棒了!

These formats can be defined in the [pretty] section of your config (or git config –global pretty.myformat …..) like this:
这些格式可以在配置的 [pretty] 部分(或 git config –global pretty.myformat ….. )中定义,如下所示:

[pretty]
    slog = format:%C(yellow)%h %Cred%as %Cblue%an%Cgreen%d %Creset%s
    bw = format:%h | %as | %>(20,trunc)%d%x09%s

Once I have these defined, I can use them at any time when running a Git log command:
一旦定义了这些,我就可以在运行 Git log 命令时随时使用它们:

$ git log --pretty=slog

This also means that I can rewrite all my weird log aliases to use my own pretty format, and then I have a single place to edit whenever my tastes change.
这也意味着我可以重写所有奇怪的日志别名以使用我自己的漂亮格式,然后每当我的品味发生变化时我就有一个可以编辑的地方。

[alias]
    l1 = log -1 --pretty=slog
    l5 = log -5 --pretty=slog 
    slog = log --pretty=slog
    slogbw = log --pretty=bw
    glog = log --graph --pretty=slog 
    outgoing = log --pretty=slog @{u}..

Another bonus of having these pretty formats defined is that I can also use them "on demand" even when running "in-the-moment" log commands.
定义这些漂亮格式的另一个好处是,即使在运行“即时”日志命令时,我也可以“按需”使用它们。

$ git log --pretty=slog --no-merges --author-date-order  foo..bar

Level 5: Prefixes - override Git behavior for specific Git subcommands
级别 5:前缀 - 覆盖特定 Git 子命令的 Git 行为

For level 5, to round off this part one blog post, we’re going to have a look at a very unknown feature in Git aliases utilizing an also rather unknown feature.
对于第 5 级,为了完善第 1 部分博客文章,我们将使用一个相当未知的功能来了解 Git 别名中的一个非常未知的功能。

It turns out that Git aliases can send options not only to the Git subcommand but to the git command itself. And if you are thinking, "I didn't know that the Git command had options," you are probably not alone.
事实证明,Git 别名不仅可以将选项发送到 Git 子命令,还可以发送到 git 命令本身。如果您在想,“我不知道 Git 命令有选项”,那么您可能并不孤单。

One useful and easy-to-explain example is the option to control pagination. By default, Git will pass any output of more than a screenful to less (or other configured pager), and output less than a screenful is printed outright. But Git allows us to override this behavior if desired, e.g.:
一个有用且易于解释的示例是控制分页的选项。默认情况下,Git 会将任何超过一屏的输出传递给 less(或其他配置的分页器),并且小于一屏的输出将被直接打印。但是 Git 允许我们根据需要覆盖此行为,例如:

git –paginate 
git --no-pager 

Let us see how that could be utilized in an alias.
让我们看看如何在别名中使用它。

E.g.: 例如。:

pst = --paginate status # so that output doesn't stick around on your screen and scroll buffer when you quit less
listconfig = --no-pager config --list # so that output stays on your screen and scroll buffer to allow copy/paste

Another good use of this feature is to use it in conjunction with Git's ability to temporarily override config settings.
此功能的另一个很好的用途是将其与 Git 临时覆盖配置设置的功能结合使用。

In Git, you can use the -c option to override a config value for this single command only, i.e., git -c <config override> <subcommand>.
在 Git 中,您可以使用 -c 选项仅覆盖此单个命令的配置值 i.e., git -c <config override> <subcommand>.

This can also be used as an alias:
这也可以用作别名:

annoncommit = -c user.name="Anonymous" -c user.email="notme@localhost" commit

Note: This is different from using git commit --author= as it sets both the author and the committer identity, as seen in the following example:
注意:这与使用 git commit --author= 不同,因为它同时设置作者和提交者身份,如以下示例所示:

$ git add .
$ git annoncommit --message 'foo'
$ git log --pretty=full
commit 0ae65ffc6192b6a2561db906bfed5c45bac702db (HEAD -> master)
Author: Anonymous 
Commit: Anonymous 

    foo
Let's see a few more useful examples:
让我们看一些更有用的例子:
# Verbose commit (add diff to comments in commit text)
vcommit = -c commit.verbose=true commit
# Use VSCode for editing, just this once
vscommit = -c core.editor="code --wait" commit
# Use VSCode for interactive rebase
riv = -c sequence.editor="code --wait" rebase -i

What’s next in the Git blog post series?
Git 博客文章系列的下一篇内容是什么?

I have taken you through a bit more than the basics of Git aliases. We have seen how they can be incredibly helpful for daily work, commands that we use frequently or commands that we use so rarely that we can't remember them. We have also gone a bit outside the box of normal Git aliases by playing around with options for Git itself (already a feature that most users don't know about).
我向您介绍的不仅仅是 Git 别名的基础知识。我们已经看到它们如何对日常工作、我们经常使用的命令或我们很少使用以至于我们记不住的命令非常有帮助。我们还尝试了 Git 本身的选项(这已经是大多数用户不知道的功能),从而稍微超出了普通 Git 别名的范围。

This is a good place to leave you hanging in anticipation of part two, where we continue with:
这是一个让你对第二部分充满期待的好地方,我们将继续:

  1. !non-git commands: More “bang” for the buck.
    !non-git 命令:更“划算”。
  2. Reusing aliases. 重用别名。
  3. Pipelining the action: Chaining unix tools for more action or craziness.
    流水线操作:链接 Unix 工具以实现更多操作或疯狂。
  4. Bash functions for the win.
    Bash 的功能是为了胜利。
  5. Going overboard because limits can only be found by crossing them.
    太过分了,因为只有跨越界限才能找到界限。
  6. Bonus round exploring alternatives to Git aliases.
    探索 Git 别名的替代品的奖励回合。

Go to part two! 转到第二部分!

Published: Apr 8, 2024
发布日期:2024 年 4 月 8 日

DevOpsCI/CD