---
# System prepended metadata

title: Git Guidelines
tags: [adh]

---

---
tags: adh
---

# Git Guidelines

## Configuration

Use your ADH e-mail address (if you haev one :wink:) along with a corresponding GPG key and configure it in your GitHub settings accordingly.

You can use an ADH-specific Git config file that applies to all repos below a certain directory.
That's especially useful if you use your GitHub account also for other projects or private stuff and need another e-mail address  and maybe no GPG key there.
The following file configures the e-mail address correctly and makes sure that commits are automatically signed.

_Add this to your `.gitconfig`:_

```ini
[includeIf "gitdir:~/path/to/your/adh/projects/"]
    path = .gitconfig_adh
```

_Add `.gitconfig_adh`:_

```ini
[user]
    email = john.doe@azdigital-health.com
    signingkey = ABCDEF42

[commit]
    gpgsign = true
```

If you use SSH, add this:

```ini

[url "ssh://git@github.com/azdigital-health/"]
    insteadOf = https://github.com/azdigital-health/
```

Go downloads dependencies using Git.
This forces Git to always use SSH for the given URL,
so Go will also use SSH with your configured key.


## Branches

Any development should happen on branches other than `master`.
Pushing to `master` directly is not possible and disabled in GitHub.
Any change needs to go through a pull request.

Branch names should follow the following pattern:

`<branch type>/<JIRA ticket>-some-optional-description`

The naming convention is important, especially because it allows us to extract the issue number by a commit hook.

The branch type is actually not that relevant.
We don't want to be too formalistic about it.
Most commonly, it will be `feature`, but other types, such as `bug`, `task`, or `chore`, are ok too.


## Committing

### Be Precise!

Git allows us to decide what should be part of a commit and what not.
It even allows us to commit specific hunks of files only.
Make use of these features.
Create logically self-contained commits.
Unrelated stuff should go into separate commits for the following reasons:

- `git blame` becomes much more useful
- The history is better whereas with large commits, the process of code development is obscured
- Bugs can more easily be isolated (e. g. using `git bisect`) and reverted using `git revert` which would not be possible if a commit contained unrelated stuff that should not be reverted
- Cherry-picking, e. g. for back-porting things, is easier

### Write Good Commit Messages!

A commit message contains a subject line (summary), optionally followed by multiple paragraphs.
The last section can be a footer section containing key/value pairs.

#### General Guidelines

- Separate subject from body with a blank line
- Limit the subject line to 65 characters.
  Otherwise GitHub wraps the line and that will mess up proper commit message formatting 
  and log display on the command-line
- Capitalize the first letter of the subject line
- Do not end the subject line with a period
- Use the imperative mood in the subject line
- Wrap the body at 72 characters
- Use the body to explain what and why vs. how

For details, please refer to:
https://chris.beams.io/posts/git-commit/

#### Body

Give the commit some thought.
It may be a good idea to add some context.
The following questions can help:

- Why is this change necessary?
- Why is it implemented that way?
- How does it address the issue?
- What side effects does this change have?

#### Footer

The footer can contain multiple key/value pairs in this format:

`Key: Value`

Keys should be capitalized.

The Jira issues should be listed in the footer.
Use multiple entries for multiple issues.

```
JIRA: ADHINFRA-42
```

In case multiple folks contribute to the same PR, they should all be listed as co-authors.
GitHub uses this information and displays it accordingly.

```
Co-authored-by: John Doe <john.doe@syncier.com>
Co-authored-by: Jane Doe <jane.doe@syncier.com>
```

**The commit message should also be reviewed during a code review!**


## Pull Requests

### Make the History Nice Before You Create a PR

While working on your branch, you may commit as you like.
It is wise to commit often.
Use commits as savepoints.
You can even use commit messages to take notes for the next day before you go home.
However, once you are ready to show what you have crafted, make the history nice before you create a PR.
This will make the review experience much more pleasant.

In general, you should squash to a single commit but multiple commits may make sense.
However, these commits must follow the above guidelines for proper commits.
If you do find that creating more than one commit is appropriate, branch off and create separate PRs for these commits.

It is ok to base one PR on another.
In such a case you will, of course, have two commits when you create the PR.
You should create a comment explaining that the PR is based on another one so reviewers are not confused and only review the second commit.
In fact, it is probably best to only create a draft PR which can then be rebased once the other PR is merged.

### Creating the Pull Requests

The pull request title is automatically taken from the commit's summary and the description is taken from the commit's body if there is only one commit.
This is another good reason why it makes sense to squash commits before creating a PR.
In general, you should not have to edit PR title and description because the information is taken from a commit that is already in shape.

### Don't Rebase the PR once Someone Has Started Reviewing

If changes are requested during code review, add new commits.
Do not rebase pull requests because GitHub usually has trouble identifying newly added changes in this case.
If you want to bring in upstream changes, again, do not rebase but merge them into the PR branch.

### Merging Pull Requests

We do not create merge commits.
This option is disabled because it messes up history.
A good and linear history is a valuable thing.
Unnecessary merge commits destroy the picture.
Pull requests are always squashed or rebased.

When you select the squash option in the GitHub UI, GitHub automatically concatenates the messages from all commits in the PR.
This does not make sense.
Don't blindly hit the button!
Fix the message!
Usually, the proper body for the message is the PR description.
Also, make sure any `JIRA` or `Co-authored-by` footers are retained, but not duplicated!

**In general, a pull request should only ever be merged by the owner themselves!**

## Tips and Tricks

### Configure Automatic Pruning of Stale Remote Refs

```console
git config --global fetch.prune true
```

### Configure Automatic Stashing on Rebase

```console
git config --global rebase.autoStash true
```

### Squashing Commits

The easiest way to squash commits is via a soft reset.
However, it is important that the commit we reset to be an ancestor of the current `HEAD`.
Otherwise the merge result will be wrong.
We can make sure this is the case by merging in the upstream branch before resetting to it.

```console
git fetch origin/master
git merge origin/master
git reset --soft origin/master
git commit
```

Use the `squash` alias listed below which also checks that the merge-base is an ancestor of the current `HEAD`.

### Transplanting Branches or Commits

If you base one PR on another, you will later on have to rebase the PR on top of `origin/master` when the PR it was based on is merged.

```console
git rebase --onto origin/master <parent of first commit to be rebased>
```

#### Example:

Let's say you start off with this PR which is based on another PR that contains only `commit1`.

```
commit2  Implement new feature
commit1  Do some clean-up
```

Next, you create additional commits based on code reviews:

```
commit4  Fix that based on code review
commit3  Fix this based on code review
commit2  Implement new feature
commit1  Do some clean-up
```

Now, assuming the other PR has been merged, we would have to rebase this PR on top of `origin/master`.
Just doing `git rebase origin/master` might work because Git may be able to detect that the contents of `commit1` are already on `master`, the better and safer way to do it would be this:

```console
git rebase --onto origin/master commit1
```

Or alternatively, just specify the parent of the first commit to rebase:

```console
git rebase --onto origin/master commit2^
```

### Useful Aliases

```ini
[alias]
    # Show pretty oneline log
    ll = log --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%ci) %C(bold blue)<%an>%Creset'

    l1 = !git ll -1
    l = !git ll -10

    # Show pretty log with graph
    lg = !git ll --graph

    # Show pretty log with graph for all branches
    lga = !git lg --all

    # Show pretty log with graph for all refs
    lgb = !git lg --branches

    # Show incoming commits with respect to upstream of current branch
    li = !git ll HEAD..@{upstream}

    # Show outcoming commits with respect to upstream of current branch
    lo = !git ll @{upstream}..HEAD

    # Show incoming commits with respect to origin/master
    lim = !git ll HEAD..origin/master

    # Show outcoming commits with respect to origin/master
    lom = !git ll origin/master..HEAD

    # List all refs sorted by commit date
    refs = for-each-ref --sort=-committerdate --format='%(color:red bold)%(refname:short)%(color:reset) %(color:yellow)%(committerdate:relative)%(color:reset) %(color:magenta bold)%(authorname)%(color:reset) %(color:green)%(objectname:short)%(color:reset) %(contents:subject)'

    # List all remote tracking branches sorted by commit date (rbs = remote branches sorted)
    rbs = !git refs refs/remotes

    # List all local branches sorted by commit date (lbs = local branches sorted)
    lbs = !git refs refs/heads

    # List outdated branches that track a branch that no longer exists
    lob = !git branch -vv | grep ': gone' | cut -d ' ' -f 3

    # Delete outdated branches
    dob = !git lob | xargs git branch -D

    # Squash commits (by default against master)
    squash = "!f() { if ! git merge-base --is-ancestor ${1:-master} HEAD; then echo "${1:-master} is not an ancestor of HEAD"; exit 1; fi; git reset --soft $(git merge-base ${1:-master} HEAD); git commit; }; f"
```
