# Collaboration: issues, pull requests and code review

How teams change code together on GitHub: track work in issues, propose changes in pull requests, contribute from a fork, review code well, and protect main so every change is reviewed and tested.

Course: [Git & GitHub](https://devops.rajeev.pro/courses/git), lesson 7. About 35 minutes, intermediate. Source: https://devops.rajeev.pro/courses/git/07-collaboration

## What you will learn

- Write issues people can act on, and organise them with labels and templates
- Run the full pull request flow from a branch, with gh or the website
- Link a pull request to its issue so merging closes it
- Contribute to a project you can't push to, through a fork
- Review code usefully, and respond to review without friction
- Protect main with required reviews and checks, and route reviews with CODEOWNERS

## How a change reaches main

**What goes wrong without a process.** Picture five developers who all push straight to `main`. On
Monday someone pushes a change that passes on their laptop but breaks the build. On Tuesday another
change quietly removes a check that stopped duplicate orders, and nobody notices because nobody else
read it. On Wednesday two people rewrite the same function in different directions. Each mistake is
small, but `main` is what gets deployed, so every one of them reaches customers.

**What a team does instead.** Nobody commits straight to `main`. Every change travels the same road:
it's described in an **issue**, built on its own **branch**, proposed in a **pull request**, checked
by **CI** (the automated tests) and read by a **reviewer**, and only then merged. Each stop catches a
different kind of mistake:

> **Figure.** The life of a change on a team. 1, an issue describes the problem. 2, a developer creates a branch, such as fix/42-empty-cart, and commits. 3, they push and open a pull request with Closes #42 in the description. 4, CI runs tests and checks on the pull request automatically. 5, a reviewer, chosen by CODEOWNERS, reads the change and approves or requests changes; the author pushes fixes to the same branch. 6, when reviews and checks pass, the pull request is merged, the branch is deleted and issue 42 closes. Rules on main make steps 4 and 5 mandatory.
>
> Issue, branch, pull request, checks, review, merge. Rules on main make the checks and the review compulsory.

## Branching strategies

Every team agrees, out loud or not, on two things: **how long a branch may live**, and **what `main`
means**. That agreement is a branching strategy. Git doesn't care which one you pick; your release process
and your merge conflicts do. There are three you'll meet at work:

> **Figure.** Animated, three rows drawn one after another. Trunk-based: main is one long line of commits; tiny branches of one commit leave and rejoin main within a day, and an unfinished feature is switched off by a flag. GitHub flow: a branch fix/42-empty-cart gets three commits, goes through a pull request with CI, merges into main, and main is deployed. GitFlow: main holds only tagged releases, v1.0 and v1.1. A develop branch leaves main; feature/coupons branches from develop and merges back; release/1.1 branches from develop, gets a fix, then merges into main, tagged v1.1, and back into develop.
>
> Trunk-based keeps branches tiny. GitHub flow adds a pull request per change. GitFlow adds develop and release branches, and main only holds releases.

| Strategy        | Branches                                                   | `main` means                | Fits                                                               |
| --------------- | ---------------------------------------------------------- | --------------------------- | ------------------------------------------------------------------ |
| **Trunk-based** | branches live hours, at most a day or two                  | always releasable, deployed | teams with strong CI and feature flags, deploying many times a day |
| **GitHub flow** | one branch per change, merged through a pull request       | always deployable           | most web teams and services: the default to start with             |
| **GitFlow**     | `develop`, `feature/*`, `release/*`, `hotfix/*` and `main` | the last released version   | versioned software shipped in releases: apps, libraries, firmware  |

**Trunk-based development** attacks the real cause of merge pain: branches that drift apart for weeks.
Everyone merges small changes into `main` (the trunk) at least daily. A feature that isn't finished still
merges, switched off behind a **feature flag**, so `main` stays releasable. It needs fast, trustworthy CI,
because there's no long branch to catch mistakes on.

**GitHub flow** is trunk-based with a pull request on every change: branch from `main`, commit, open a PR,
let CI and a reviewer pass it, merge, deploy. Branches live days, not weeks. It's what this course uses.

**GitFlow** was designed for software shipped as numbered releases. Features merge into `develop`; when
it's time to ship, a `release/1.1` branch is cut, only fixes go into it, and it merges into `main` (tagged
`v1.1`) and back into `develop`. Urgent fixes branch from `main` as `hotfix/*`. You get a stabilisation
period, at the cost of more branches, more merges and slower feedback. For a web service you deploy
continuously, it's usually more process than you need; its own author later added a note saying the same.

Pick by how you ship. Deploying continuously points to GitHub flow or trunk-based. Shipping versions that
customers install, with several versions supported at once, is where release branches earn their keep.

## Issues and labels

An **issue** is a unit of work: a bug, a feature, a question. A good one can be picked up by someone who
wasn't in the conversation:

```text
Title: Checkout crashes when the cart is empty

Steps to reproduce
1. Open /cart with no items
2. Click "Checkout"

Expected: a "Your cart is empty" message
Actual:   500 error, ZeroDivisionError in checkout.py line 88

Version: 1.4.0, Chrome 130
```

**Labels** make a long list searchable: `bug`, `enhancement`, `good first issue`, `priority: high`.
**Assignees** say who is on it; **milestones** group issues for a release. **Templates** in
`.github/ISSUE_TEMPLATE/` give every new issue the right questions, so you get steps to reproduce
without asking for them.

```sh
$ gh issue create --title "Checkout crashes when the cart is empty" --label bug
$ gh issue list --label bug --assignee @me
$ gh issue view 42
```

## The pull request flow

A **pull request** (PR) says "here is a branch; please review it and merge it into main". It holds the
diff, the discussion, the review and the test results in one place.

```sh
$ git switch -c fix/42-empty-cart
$ git commit -am "Show a message instead of crashing on an empty cart"   # after editing and testing
$ git push -u origin fix/42-empty-cart
$ gh pr create --fill --draft      # title and body from your commits; draft = not ready yet
$ gh pr ready                      # when it is ready for review
$ gh pr status                     # your pull requests and their checks
$ gh pr merge --squash --delete-branch
```

A description reviewers can work with:

```text
## What
Show "Your cart is empty" instead of a 500 when checking out with no items.

## Why
Closes #42. Checkout divided by the item count to show an average price.

## How to test
1. Empty the cart, click Checkout: you see the message.
2. Add an item: checkout works as before.

## Screenshots
(before / after)
```

`Closes #42` (or `Fixes`, `Resolves`) links the issue and closes it when the PR merges into the default
branch. A `.github/pull_request_template.md` pre-fills these headings in every new PR.

**Keep PRs small.** Reviewers do their best work on about 200–400 changed lines. A 2,000-line PR gets a
skim and "LGTM". Split big work into several PRs that each leave main working.

When review asks for changes, push more commits to the **same branch**: the PR updates itself. If main
moved on, update your branch (rebase it, or the **Update branch** button) so checks run against current
code.

> **Video.** [How to create a pull request in 4 min | GitHub for Beginners](https://www.youtube.com/watch?v=nCKdihvneS0) (GitHub)

## Pull requests from a fork

When you can't push to the repository (open source, another team), the PR comes from your fork:

```sh
$ gh repo fork owner/project --clone && cd project    # origin = your fork, upstream = original
$ git switch -c fix/typo-in-readme
$ git commit -am "Fix the install command in the README"
$ git push -u origin fix/typo-in-readme
$ gh pr create --repo owner/project --fill            # PR from your fork to the original
```

Before starting, read the project's `CONTRIBUTING.md` and check an issue exists or open one: a
maintainer may already have plans. Keep your fork current with `git fetch upstream` and
`git rebase upstream/main`. Leave **Allow edits by maintainers** ticked so they can fix small things on
your branch.

> **Fork PRs and secrets.** GitHub Actions doesn't give repository secrets to workflows triggered by pull requests from forks: a stranger's PR could otherwise print your deploy key. That's why some checks show as skipped on fork PRs. Don't work around it by switching to `pull_request_target` unless you know exactly what it runs.

## Code review that helps

**As the reviewer**, you're checking that the change is correct, safe and maintainable, not that it's
written the way you would have:

| Look for    | Ask                                                                             |
| ----------- | ------------------------------------------------------------------------------- |
| Correctness | Does it do what the issue asks? Edge cases: empty, huge, concurrent, bad input? |
| Safety      | Secrets, injection, permissions, data loss on failure?                          |
| Tests       | Is the new behaviour tested? Would the test fail without the fix?               |
| Readability | Will someone understand this in a year?                                         |

Write comments people can act on, and say how important they are:

```text
blocking: This runs one query per cart item. Can we load them in one query with an IN clause?
suggestion: `items_total` might read better than `t`.
nit: trailing space.
question: Why 30 seconds here? A constant with a name would explain it.
```

Use **suggested changes** (the ± button on a line) for small fixes the author can apply in one click.
Finish with **Approve**, **Request changes** or **Comment**: `gh pr review --approve`.

**As the author**, review your own diff first, answer every comment with a fix or a reason, and don't
take it personally: the review is about the code.

## Protecting main

Turn the good habits into rules. In _Settings → Rules → Rulesets_ (or the older _Branches → Branch
protection_), create a rule for `main`:

| Rule                                  | Effect                             |
| ------------------------------------- | ---------------------------------- |
| Require a pull request before merging | no direct pushes to main           |
| Required approvals: 1                 | someone else has read it           |
| Require status checks to pass         | CI must be green                   |
| Require review from Code Owners       | the owners of those files approve  |
| Block force pushes                    | history on main can't be rewritten |

### CODEOWNERS

A team of twenty can't have everyone review everything, and "someone approved it" isn't the same as "the
people who run the database approved the migration". **CODEOWNERS** maps paths to the people or teams
responsible for them. GitHub reads it from `.github/CODEOWNERS` (or the repository root, or `docs/`) on
the **base branch** of the pull request, and requests reviews from the matching owners automatically:

```text
# .github/CODEOWNERS
# Order matters: for each file, the LAST matching line wins.

# Fallback owner for everything
*                     @rajeev

# Terraform and Kubernetes manifests; CI workflows can reach deploy secrets
/infra/               @rajeev/platform-team
/.github/workflows/   @rajeev/platform-team

*.sql                 @rajeev/db-team
/services/payments/   @rajeev/payments-team @rajeev/security-team

# No owner: anyone with write access can approve docs
/docs/
```

A pull request that changes `services/payments/api.py` and `infra/rds.tf` asks for both the payments
team and the platform team. Because the last match wins, put the broad `*` line first and the specific
paths after it. A line with a path and no owner removes ownership, which is how you exempt `docs/`.
Owners must have write access to the repository, and teams must be visible.

On its own, CODEOWNERS only **requests** reviews. It becomes a gate when you pair it with **Require review
from Code Owners** in the ruleset: then the pull request can't merge until an owner of every changed path
has approved. If the file has a mistake, such as a team that doesn't exist, GitHub shows the error when you
open `CODEOWNERS` on the website, so check it after every edit.

Branch names from the _Branches_ lesson (`feature/`, `fix/`, `hotfix/`) matter here too: rulesets can
target patterns such as `release/*`, and CI can deploy by branch name.

> **In production.** Protect `main` on day one, even on a team of two. Add `.github/workflows/` to CODEOWNERS, because a workflow change can reach your deploy secrets. And merge with the button only when checks are green: `gh pr merge --auto --squash` merges by itself the moment they pass.

## Merge queue

Protecting main still leaves one gap. Two pull requests are each green, each tested against `main` as it
was when their checks ran. Merge the first, and the second is now going into a `main` its tests never saw.
One renamed a function; the other added a new call to the old name. Both passed, and `main` is broken.

The usual fix, **Require branches to be up to date before merging**, closes the gap but creates a treadmill
on a busy repository: every merge makes every other open pull request out of date, so each one has to update
and wait for CI again, and whoever merges first wins.

A **merge queue** does that waiting for you. Instead of merging, you add the pull request to the queue
(`gh pr merge --auto`, or the **Merge when ready** button). GitHub builds a temporary branch containing
`main` plus the pull requests ahead of yours plus yours, runs the required checks on that combination, and
merges only if they pass. If one fails, it's removed from the queue and the rest carry on without it.

```yaml
# .github/workflows/ci.yml: the checks must also run for the queue's temporary branches
on:
  pull_request:
  merge_group:
```

Turn it on with **Require merge queue** in the ruleset for `main`. It's worth it once several pull requests
merge into the same branch each day. On a team of three, the up-to-date rule is enough.

## Mission: Run the whole team flow on your own repository

Using your shop repository on GitHub, protect main, open an issue for a bug, fix it on a branch, open a pull request that closes the issue, review it, and squash-merge it. Finish with the issue closed automatically and the branch deleted.

- You need: The shop repository on GitHub (from the GitHub lesson), and gh logged in
- You'll have: A merged PR, a closed issue, a protected main

```sh
$ gh issue create --title "README doesn't say how to run the app" --body "Add the run command." --label documentation
https://github.com/rajeev/shop/issues/1
$ git switch main && git pull
$ git switch -c docs/1-run-command
$ echo 'Run it with: `python app.py`' >> README.md
$ git commit -am "Document how to run the app"
$ git push -u origin docs/1-run-command
$ gh pr create --title "Document how to run the app" --body "Closes #1"
$ gh pr view --web                       # read the diff as a reviewer would
$ gh pr merge --squash --delete-branch
$ gh issue view 1 --json state --jq .state
CLOSED
$ git switch main && git pull && git log --oneline -1
```

Then in _Settings → Rules → Rulesets_, add a ruleset for the default branch requiring a pull request,
and try `git push origin main` with a new commit: GitHub refuses it. On a personal repository you can't
approve your own PR, so set required approvals to 0 there; on a team, use at least 1.

## Try it

- Open an issue in a test repository with a clear title, steps to reproduce and an expected result.
- Create a branch, push it, and open a draft pull request with `gh pr create --draft --fill`.
- Put `Closes
- Review a pull request (yours or a friend's) and leave one suggestion with the suggestion button.
- Add a `.github/pull_request_template.md` and open a new pull request to see it filled in.
- Turn on a branch ruleset for main that requires a pull request before merging.

## Quiz

1. Which description text makes GitHub close issue 42 when the pull request merges into the default branch?
   - See 42
   - **Closes #42 (or Fixes #42, Resolves #42)** (answer)
   - Issue: 42
   - @42
   Why: Closing keywords link the pull request to the issue and close it on merge. A plain #42 just links it.

2. What is a draft pull request for?
   - Pull requests nobody can see
   - **Sharing work in progress for early feedback and CI, marked as not ready to merge** (answer)
   - Pull requests without commits
   - Saving a pull request offline
   Why: Drafts can't be merged and don't request reviews from code owners until you mark them ready. They are a good way to ask "am I on the right track?".

3. Why do teams protect main with a rule that requires a pull request and passing checks?
   - To slow developers down
   - **So nothing reaches main without a review and green tests, which keeps main deployable** (answer)
   - GitHub requires it
   - To save storage
   Why: One accidental direct push can break production for everyone. The rule makes the safe path the only path.

4. What does a CODEOWNERS file do?
   - Lists the repository owners for billing
   - **Automatically requests reviews from the right people or teams for the files a pull request changes** (answer)
   - Blocks people from reading files
   - Sets file permissions
   Why: Combined with "require review from code owners", it makes sure, for example, the database team approves migration changes.

5. A review comment says "this query runs once per item in the loop". What is the best response?
   - Ignore it if the tests pass
   - **Fix it, or explain why it's fine, then reply and let the reviewer resolve the thread** (answer)
   - Close the pull request
   - Argue in the comments until they give up
   Why: Reviews are a conversation about the code, not the person. Answer every comment with a change or a reason.

6. A team deploys its web service to production several times a day. Which branching strategy fits best?
   - **GitHub flow or trunk-based: short branches merged into a main that is always deployable** (answer)
   - GitFlow, with a release branch for every deploy
   - One long-lived branch per developer, merged monthly
   - No branches, everyone pushes to main without review
   Why: GitFlow's develop and release branches suit software shipped as versions. For continuous deploys they add merges and delay without adding safety.

7. Two pull requests are green and merge one after the other, and main breaks. What does a merge queue change?
   - It merges pull requests faster by skipping CI
   - It requires two approvals
   - **It tests each pull request combined with main and the pull requests queued ahead of it, and merges only if that passes** (answer)
   - It blocks force pushes
   Why: Each PR was tested against an older main. The queue tests the exact combination that will land, so two individually green changes can't break main together.

## Resources

- [GitHub Docs: about pull requests](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests) (GitHub Docs)
- [GitHub Docs: linking a pull request to an issue](https://docs.github.com/en/issues/tracking-your-work-with-issues/using-issues/linking-a-pull-request-to-an-issue) (GitHub Docs)
- [GitHub Docs: about rulesets](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/about-rulesets) (GitHub Docs)
- [GitHub Docs: about code owners](https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners) (GitHub Docs)
- [Google engineering practices: how to do a code review](https://google.github.io/eng-practices/review/reviewer/) (Google)
