[translation] how to write git submission message

Time:2022-3-2

The personal blog and creation index page are under production, and only the largest local version is released here. The original file is based on hexo and related plug-ins and is not compatible with the format here. It will not be repaired uniformly for the time being.


[translation] how to write git submission message[1]The simplified Chinese version of corresponds to the original textHow to Write a Git Commit Message, originally written by Chris beams. Please note that:

  • The text format shall be consistent with the original web page as far as possible;
  • The translator’s note will be presented in the form of footnotes, and its content should start with “translator’s note”;
  • If there is a jump hyperlink in the original text, it will be removed directly if not necessary, and no further explanation will be made in the translation;
  • If there are words and sentences in the original text that are difficult to convey the author’s writing intention after translation (usually caused by orders, or due to the special nature of the source language, etc.), they will not be translated and will not be further explained in the translation.

The translated text will be displayed from the following separation line.


How to write git submission information

Original author: Chris beams
Original creation date: August 31, 2014

Submitting messages is important. Here’s how to write them.

图1 信息量递减的提交消息

Introduction: why is it important to submit good news

If you’ve ever browsed through some git repositories at random, you’re likely to find their submission messages more or less cluttered. For example, you can take a look at some of my early submissions to springGem[2]Log of:

$ git log --oneline -5 --author cbeams --before "Fri Mar 26 2009"

e5f4b49 Re-adding ConfigurationPostProcessorTests after its brief removal in r814. @Ignore-ing the testCglibClassesAreLoadedJustInTimeForEnhancement() method as it turns out this was one of the culprits in the recent build breakage. The classloader hacking causes subtle downstream effects, breaking unrelated tests. The test method is still useful, but should only be run on a manual basis to ensure CGLIB is not prematurely classloaded, and should not be run as part of the automated build.
2db0f12 fixed two build-breaking issues: + reverted ClassMetadataReadingVisitor to revision 794 + eliminated ConfigurationPostProcessorTests until further investigation determines why it causes downstream tests to fail (such as the seemingly unrelated ClassPathXmlApplicationContextTests)
147709f Tweaks to package-info.java files
22b25e0 Consolidated Util and MutableAnnotationUtils classes into existing AsmUtils
7f96f57 polishing

Ah! Compare some recent submitted logs of the same warehouse:

$ git log --oneline -5 --author pwebb --before "Sat Aug 30 2014"

5ba3db6 Fix failing CompositePropertySourceTests
84564a0 Rework @PropertySource early parsing logic
e142fd1 Add tests for ImportSelector meta-data
887815f Update docbook dependency and generate epub
ac8326d Polish mockito usage

Which do you prefer to read?

The submitted messages of the former are different in length and form, while the latter is more accurate and consistent; The former is a natural result, while the latter is never written by chance.

There are some exceptions when many warehouses similar to the former can be found everywhere.Linux kernelandGit itselfThe source code of is a good example. Or take a lookSpring BootOr byTim PopeManaged warehouse.

Contributors to these repositories know that a polished git submission message is to communicate a change to other developers (and themselves in the future)sequence of eventsThe best way to[3]。 A diff output will tell youwhatChanged, and only submitting a message can tell you properlyWhy?Changed. Peter HuttererExpress this viewWell done:

Redefining the context of a piece of code is wasteful. We can’t avoid it completely, so we should try our bestReduce this situationThe occurrence of. Submitting messages can do this accurately, soA submission message can show whether a developer is a good collaborator[4]

If you don’t have a lot of ideas to write a good git submission message, it may indicate that you don’t spend a lot of time using itgit logCommands and related tools. There is a cruel cycle here: because submission history lacks structure and consistency, someone won’t spend a lot of time using or caring about it. And because it is not used or cared for, it will always lack structure and consistency.

However, a well maintained log is a beautiful and practical thing, which will makegit blamerevertrebaselogshortlogAnd other subcommands are dynamic and bring some value to reviewing other people’s submissions and pull requests — and they can suddenly be done independently. Understanding why something happened a few months or years ago will not only become possible, but also efficient.

The long-term success of a project (compared with other factors) depends not only on its maintainability, but also on whether a maintainer has few more powerful tools than logs. It’s worth spending some time learning how to properly maintain the project log. The difficulties that may arise when maintaining a log initially will soon turn into habits and eventually become a source of pride and productivity for all participants.

In this article, I will tell you the most basic element of maintaining a healthy submission history: how to write a separate submission message. There are other important habits I won’t mention here, such as unified submission[5], maybe I’ll talk about them in my subsequent submissions.

Most programming languages have established conventions that build styles that conform to language habits, such as naming, formatting, and so on[6]。 Of course, there are many variations of these conventions, but most developers agree that focusing on one is far better than the chaos caused by everyone choosing one.

A team should treat submitting logs in the same way. In order to create a practical revision history, the team should first agree on a submission message convention that meets at least the following three points:

style。 Syntax of markup language[7], break line spacing, syntax[8], case, punctuation. Make it clear, eliminate guesswork, and make everything as simple as possible. The end result will be an extraordinarily consistent Journal – not only enjoyable to read, but actuallyIt can be read regularly[9]

content。 What information should the body of the submitted message (if any) contain? What is?NoIncluded?

metadata。 Tracking number such as issue[10]How should the number of pull request be mentioned?

Fortunately, there are some well-established conventions to create a git submission message that conforms to the language habits. Indeed, these are assumed to operate in a specific git command. There’s nothing you need to reinvent here. Just follow the seven rules below and you’ll open the door to submitting like an expert.

Seven rules for written git to submit messages

Remember:theseallHas beenproposetooYes

  1. Separate the title and body with a blank line;
  2. The title shall be controlled within 50 characters;
  3. Capitalize the first letter of the title;
  4. Don’t write a full stop at the end of the title;
  5. The title uses imperative tone;
  6. The main body breaks every 72 characters;
  7. Explain with subjectWhat did you doandWhy?, notHow

For example:

Summarize changes in around 50 characters or less

More detailed explanatory text, if necessary. Wrap it to about 72
characters or so. In some contexts, the first line is treated as the
subject of the commit and the rest of the text as the body. The
blank line separating the summary from the body is critical (unless
you omit the body entirely); various tools like `log`, `shortlog`
and `rebase` can get confused if you run the two together.

Explain the problem that this commit is solving. Focus on why you
are making this change as opposed to how (the code explains that).
Are there side effects or other unintuitive consequences of this
change? Here's the place to explain them.

Further paragraphs come after blank lines.

 - Bullet points are okay, too

 - Typically a hyphen or asterisk is used for the bullet, preceded
   by a single space, with blank lines in between, but conventions
   vary here

If you use an issue tracker, put references to them at the bottom,
like this:

Resolves: #123
See also: #456, #789

1. Separate the title and body with a blank line

according togit commitImperativeHelp page

Although not required, it is a good idea to start the submission message with a short line (less than 50 characters) summarizing the change, followed by an empty line, followed by a more detailed description. The first line of the entire text will be recognized as the title of the submission, which will run through GIT[11]。 For example, GIT format patch (1) transforms submission into mail, which takes the submitted title as the subject of the mail and the remaining submitted content as the body of the mail.

First, not every submission requires a title and body. Sometimes a line is also good, especially when the change is so simple that further explanation is unnecessary. For example:

Fix typo in introduction to user guide

There is nothing to explain. If the reader wants to know what the spelling error is, just look at the change itself, in other words, usegit showgit difforgit log -p

If you want to submit with a command, give it togit commitCommand add-mOptions are easy:

$ git commit -m"Fix typo in introduction to user guide"

However, when a submission requires a little interpretation and context, you need to write its body. For example:

Derezz the master control program

MCP turned out to be evil and had become intent on world domination.
This commit throws Tron's disc into MCP (causing its deresolution)
and turns it back into a chess game.

use-mOption to write the body of the submitted message is not easy. You’d better write it in a suitable text editor. If you don’t already have an editor, use the GIT command line to set it, seeThis section of Pro Git

In any case, the interval between the title and the body can be rewarded when browsing the log. Here is the complete log:

$ git log
commit 42e769bdf4894310333942ffc5a15151222a87be
Author: Kevin Flynn 
Date:   Fri Jan 01 00:00:00 1982 -0200

 Derezz the master control program

 MCP turned out to be evil and had become intent on world domination.
 This commit throws Tron's disc into MCP (causing its deresolution)
 and turns it back into a chess game.

Execute nowgit log --oneline, this outputs only the header row:

$ git log --oneline
42e769 Derezz the master control program

Or executiongit shortlog, this will be grouped according to the user’s submission. For simplicity, only the title line will be output:

$ git shortlog
Kevin Flynn (1):
      Derezz the master control program

Alan Bradley (1):
      Introduce security program "Tron"

Ed Dillinger (3):
      Rename chess program to "MCP"
      Modify chess program
      Upgrade chess program

Walter Gibbs (1):
      Introduce protoype chess program

There are also other contexts in Git where the distinction between the title line and the body is broken – but neither of them works properly when there is no empty line between them[12]

2. The title shall be controlled within 50 characters

50 characters is not a hard limit, but a rule of thumb. Keeping the title lines at this length ensures that they are readable and forces the author to spend some time thinking about how to most succinctly explain what is going to happen.

Tip: if you have difficulty summarizing what you submitted, it may be because you submitted too many changes at one time. Try to doAtomic level submission[13](another topic of contribution).

GitHub’s user interface is fully aware of these conventions. For example, it will warn you when your title line exceeds 50 characters:

图2 GitHub 的字数警告

In addition, the title line with more than 72 characters will be truncated, and then replaced with ellipsis:

图3 GitHub 的字数超限截断

Therefore, strive to limit it to 50 characters and treat 72 characters as a hard limit.

3. Capitalize the title

It’s as simple as it sounds. All header lines need to be capitalized.

For example, use:

  • Accelerate to 88 miles per hour

To replace:

  • accelerate to 88 miles per hour

4. Don’t write a full stop at the end of the title

The punctuation at the end of a sentence is irrelevant in the title. In addition, when you want to control 50 characters, spaces are precious.

For example, use:

  • Open the pod bay doors

To replace:

  • Open the pod bay doors.

5. The title uses imperative tone

imperativeIt means “say or write something similar to a command or instruction”. Here are some examples:

  • Clean your room
  • Close this door
  • Take away the garbage

Each of the seven rules you are reading is written in imperative mood (“subject line breaks every 72 characters” and others).

The imperative tone sounds a little impolite, which is why we don’t use it often, but it’s perfect for the title submitted by git, one of the reasons isGit itself creates submissions in your name using an imperative tone

For example, usegit mergeThe default submission message after is:

Merge branch 'myfeature'

And usegit revertAfter:

Revert "Add the thing with the stuff"

This reverts commit cc87791524aedd593cff5a74532befe7ab69ce9d.

Or click the “merge” button on GitHub’s pull request interface:

Merge pull request #123 from someuser/somebranch

Therefore, when you write a submission message in an imperative tone, you are following git’s built-in conventions. For example:

  • Refactor subsystem X for readability
  • Update getting started documentation
  • Remove deprecated methods
  • Release version 1.0.0

It may seem silly to write like this at first. We use it more oftenDeclarative toneThis tone is used to describe the fact, which is why many submitted messages end like this:

  • Fixed bug with Y
  • Changing behavior of X

And sometimes submitted messages are written like descriptions of their contents:

  • More fixes for broken stuff
  • Sweet new API methods

To get rid of any confusion, here is a simple rule to make you do it right every time:

A suitable git submission title should always complete the following sentences:

  • If applied, this submission willThis is your title

For example:

  • If applied, this commit will refactor subsystem X for readability
  • If applied, this commit will update getting started documentation
  • If applied, this commit will remove deprecated methods
  • If applied, this commit will release version 1.0.0
  • If applied, this commit will merge pull request #123 from user/branch

For non successful, this is not noticeable:

  • If applied, this commit will fixed bug with Y
  • If applied, this commit will changing behavior of X
  • If applied, this commit will more fixes for broken stuff
  • If applied, this commit will sweet new API methods

Remember: the use of imperative tone is only important for the title. You can relax this rule when writing the main body.

6. The main body breaks every 72 characters

Git never breaks lines automatically. When you write a submitted body, you need to notice its right boundary and wrap it manually.

The recommended value for line folding is 72 characters, so git will generally keep the content within 80 characters as it is, and there is enough space for indenting and typesetting.

A good text editor can help you. VIM is easy to configure, such as wrapping at 72 characters when writing git submission messages. However, in the traditional sense, the IDE is bad for intelligently supporting the folding of submitted messages (although IntelliJ idea is in the latest version)finallyfinishBetter than before(see below).

7. Use the subject to explain what was done and why, not how

thereA submission from bitcoin coreIs the best example of explaining what has changed and why:

commit eb0b56b19017ab5c16c745e6da39c53126924ed6
Author: Pieter Wuille 
Date:   Fri Aug 1 22:57:55 2014 +0200

   Simplify serialize.h's exception handling

   Remove the 'state' and 'exceptmask' from serialize.h's stream
   implementations, as well as related methods.

   As exceptmask always included 'failbit', and setstate was always
   called with bits = failbit, all it did was immediately raise an
   exception. Get rid of those variables, and replace the setstate
   with direct exception throwing (which also removes some dead
   code).

   As a result, good() is never reached after a failure (there are
   only 2 calls, one of which is in tests), and can just be replaced
   by !eof().

   fail(), clear(n) and exceptions() are just never called. Delete
   them.

Take a look at itComplete diff information, think about how much time the author saves other and future submitters by spending time here and now providing the context of the code. If he fails to do so, this submission is likely to be forgotten forever.

In most cases, you can omit the details of how the change was made. At this point, the code is usually self explanatory (if the code is so complex that it needs to be interpreted in boring language, that’s what source code comments should do). Just focus on first identifying the reason for the change – what you did before the change (and what went wrong), how they work now, and why you decided to solve the problem your way[14]

In the future, it may be you who thank you for your maintenance!

Tips

Learn to love the command line. Leave ide behind.

For many reasons, such as the existence of GIT subcommands, it is wise to embrace the command line. Git has crazy power, and so does IDE, but the two are reflected in different aspects. I use one IDE (IntelliJ idea) every day and others (eclipse) widely, but I’ve never seen an IDE with git integration comparable to a simple and powerful command line (once you realize this).

Some git related ide functions are priceless [^ 15], just like when you delete filesgit rm, when you rename a filegitExecute the command correctly. When you start trying to submit, merge, rebase, or analyze unfathomable history with the IDE, everything will collapse.

When the day comes to dominate all the mana of GIT, all that remains is the command line.

Remember, whether you use bash, Zsh or PowerShell, there areTab Automatic completionscriptTo alleviate the pain of many memory sub commands and switches.

Read Pro Git

Pro GitIt’s free to read online, and it’s wonderful. Make good use of it!

Caption provider:xkcd


[End]

footnote

  1. Translator‘s note: the original text of “submit message” is “commit message”, the same below.↩︎

  2. Translator’s note: the plug-in name of spring library is “gem”.↩︎

  3. The contributors to these repositories know that a well written git commit message is the best way to communicate context about a change to fellow developers (and found to their future selves).↩︎

  4. Translator’s note: the original text is “re establishing the context of a piece of code is wasteful We can’t avoid it completely, so our efforts should go toreducing it [as much] as possible. Commit messages can do exactly that and as a result, a commit message shows whether a developer is a good collaborator“ 。 ↩︎

  5. Translator’s note: the original text is “most programming languages have well established conventions as to what constructs idiomatic style, i.e. naming, formatting and so on”.↩︎

  6. Translator’s note: the original is “syntax”.↩︎

  7. Translator’s note: the original is “grammar”.↩︎

  8. The end result will be a remark consistent log that’s not only a pleasure to read but that actuallydoes get read on a regular basis” 。 ↩︎

  9. Translator’s note: the original is “issue tracking IDS”.↩︎

  10. The text up to the first blank line in a commit message is treated as the commit title, and that title is used through GIT.↩︎

  11. Translator’s note: the original text is “there are a number of other contexts in Git where the distinction between subject line and body kicks in – but none of their work properly without the blank line in between”.↩︎

  12. Translator’s note: the original is “atomic commitments”.↩︎

  13. Translator’s note: the original text is “just focus on making clear the reasons why you made the change in the first place – the way things worked before the change (and what was wrong with that), the way they work now, and why you decided to solve it the way you did”.↩︎

  14. Translator’s note: the original text is “certain git related ide functions are invalid”.↩︎