Skip to content

Git and collaborating

Phase 1 · Working like an engineer · 14 min read

What you'll be able to do

  • Trace how commits, branches, and HEAD move during everyday Git work.
  • Merge a small change, recognize a conflict, and choose a safe way to undo a mistake.
  • Share work through a pull request that another person can review and reproduce.

Think in snapshots and labels

Git records a commit as a snapshot of tracked files, with a pointer to its parent commit. The commit also has a message and an ID. A branch is a movable label pointing at a commit. HEAD tells Git where you are: ordinarily, it points to the branch you have checked out. When you commit, that branch label moves to the new commit; the older snapshot remains in history.

A branch is a label on a commit; committing moves the label you are on (HEAD).

The arrows point from a commit toward its parent. git branch feature creates a label; it does not copy the files into a second repository. git switch feature moves HEAD to that label and updates the files you see. The new commit moves only feature. Two branches can therefore share history and then diverge without duplicating earlier commits.

Move a change through three places

Your working tree is the files you edit. The staging area is the proposed contents of the next commit. The repository holds committed snapshots. Staging is useful because you can edit two things but commit only one coherent change.

Three places a change can be: the working tree, the staging area, the repository.

Try this in a throwaway directory after configuring your Git name and email. The commands show exactly what each step includes:

git init
printf 'threshold = 0.7\n' > config.py
git status               # config.py is untracked
git add config.py
git diff --staged        # proposed commit
git commit -m "Set default score threshold"
printf 'threshold = 0.8\n' > config.py
git diff                 # unstaged change
git log --oneline

git status says which files are untracked, modified, or staged. git diff compares your working tree with the staging area and ignores untracked files, which is why it stays empty until the file is tracked. git diff --staged compares the staging area with the last commit (before the first commit, with an empty tree). Before committing, read the staged diff. A good commit does one understandable job and leaves the project in a usable state. Its message says what changed in a short imperative phrase; add a longer explanation when the reason is not obvious. “Set default score threshold” tells a reviewer more than “updates.”

Branch, merge, and resolve

Use git branch feature to create a branch and git switch feature to work on it. When ready, switch to the destination branch and run git merge feature. If the destination has not moved since the split, Git can fast-forward: it simply moves its label to the feature tip. No new merge commit is needed.

Fast-forward: when main has not moved, merging only slides the main label forward.

If both branches gained commits, Git compares each tip with their common ancestor, the newest commit both share. If only one side changed a piece of content, Git takes that side; if both made the same change, it keeps it. The result is usually a merge commit with two parents. If both sides change the same lines differently, Git stops and asks you to resolve the conflict. A conflicted file contains markers like these:

<<<<<<< HEAD
threshold = 0.7
=======
threshold = 0.8
>>>>>>> feature

The upper block is the version from your checked-out side; the lower block is from the branch being merged. Read the surrounding code and decide the intended final content. You may keep either value or write a third one. Remove every marker, run the relevant tests, then git add config.py and git commit to finish the merge. Blindly accepting one side can silently remove a needed change.

git rebase main replays your branch's commits on top of main, producing new commit IDs and a linear-looking history. It is useful for cleaning up your own unpublished branch before review. Do not rebase shared history: teammates may already have commits based on the old IDs. A merge preserves the existing commits and makes the joining point explicit.

Share changes and review them

A remote is another repository, usually the shared one. git clone <url> makes a local copy and records a remote. git fetch downloads its new commits and updates remote-tracking labels without merging them into your current branch. git pull does a fetch followed by a merge or rebase, depending on configuration. Fetch first when you want to inspect incoming changes before integrating them.

git push sends your commits to the remote. On the first push of a new branch, git push -u origin feature sets its upstream: the remote branch your local branch tracks. After that, plain git push and git pull can use that relationship. A remote-tracking label such as origin/main records the last fetched view of the remote; it is not a live connection.

Open a pull request from your feature branch into the shared main branch. Keep it small enough to review, explain why the change exists, summarize the approach, and state how you tested it. A reviewer should inspect behavior and risks, ask specific questions, and suggest changes respectfully. As the author, answer the question or change the code, then explain the resolution. Automated CI checks can run tests and linting on the proposed change and gate the merge; a green check is evidence from those checks, not proof that the design is right.

Teams often use short branches merged frequently into a shared trunk. This limits divergence and makes conflicts smaller. Long-lived branches can suit isolated release work, but the longer they diverge, the more integration work accumulates. Prefer the team's workflow and keep changes reviewable either way.

Undo the right thing

First ask whether the change is uncommitted, committed only locally, or already shared. These cases need different tools:

Situation Tool Effect
Discard an unstaged file edit git restore file Replace working-tree content with the staged version
Unstage a file, keep its edits git restore --staged file Reset its staged version to the last commit; keep working-tree edits
Move a local branch back, keep changes staged git reset --soft HEAD~1 Move label only
Move it back, keep changes unstaged git reset --mixed HEAD~1 Move label and reset staging
Discard a local commit and its file changes git reset --hard HEAD~1 Move label, reset staging and working tree
Undo a shared commit git revert <commit> Add a new commit that reverses it
Find a commit after a bad reset git reflog Show recent local HEAD movements
Set unfinished edits aside briefly git stash Save staged and unstaged changes, but not untracked files; git stash push -u includes them

reset --hard can destroy uncommitted work. If you moved a branch to the wrong commit, inspect git reflog before panicking; it often contains the previous commit ID. reflog is local recovery information, not a backup you can expect a teammate to have. For a commit others may have pulled, use revert rather than rewriting their history.

Keep the repository reproducible

Put local secrets, temporary files, and generated artifacts in .gitignore before staging; clear outputs embedded in notebooks before committing them. Review git status after git add ., because that command stages every eligible change in the directory. Ignore rules do not remove a file already tracked: stop tracking it separately. Never commit .env files, API keys, or large data and model checkpoints to ordinary Git history. For large versioned assets, investigate Git LFS or DVC by name and choose a storage policy with your team.

If a secret was committed, remove it from current files and rotate it. Rewriting history may reduce exposure but cannot make copies already fetched by others disappear. A commit is an excellent identity for code: tag the commit that produced an important result, and record its commit hash with each experiment run.

For AI engineers

For AI engineers

A training script can depend on a threshold file, preprocessing code, and prompt templates. A run labeled final_v2_REAL does not say which versions produced the result. Store the commit hash and relevant configuration beside the run metrics, then tag a release candidate you intend to reproduce. Clear notebook outputs before committing so reviews show code changes instead of large, noisy cell results. Keep a 2 GB checkpoint in suitable artifact storage rather than an ordinary Git commit.

Common mistakes

  • Combining refactors, data changes, and fixes in one giant commit or pull request.
  • Running git add . without checking git status and the staged diff.
  • Force-pushing a shared branch, invalidating teammates' view of its history.
  • Resolving a conflict by choosing one side without understanding the resulting code.
  • Committing .env, notebook outputs, or checkpoints; .gitignore cannot unpublish them.
  • Giving up after a bad reset --hard before checking git reflog for the lost commit.

Check yourself

main and feature both point to C. You switch to feature and commit D. Where do the labels and HEAD point?

feature moves to D, main stays at C, and HEAD remains on feature. D points back to C.

You edited two files but want the next commit to include only one. What do you inspect and run?

Run git status and git diff, stage only the intended file with git add <file>, then inspect git diff --staged before committing.

A teammate has already pulled a commit containing a bug. Should you reset or revert the shared branch?

Revert it. git revert <commit> creates a new undo commit without changing the IDs your teammate already has.

Both branches changed the same line to different values. What should happen during merge?

Git reports a conflict. Read both versions and their context, edit the file to the intended final value, remove markers, test it, then stage and commit the resolution.

Lab

Build a tiny in-memory repository at code/git-collaboration/. Implement snapshots, branch labels, first-parent logs, and two kinds of merge. Detect file-level conflicts when both sides change one file differently. Use the tests to progress from commits to conflict handling. Run cd code/git-collaboration && PYTHONPATH=starter python -m pytest tests -q. Then try the same branch and merge sequence in a throwaway real Git repository.

Go deeper