Your Local Git repo and The Three Trees - or, "Intro to git reset"

When I last checked (end of March 2023), six of the top twelve stackoverflow questions were git questions!!

For at least a couple of those, the answer is git reset.

git reset is an essential command for moving changes around in your local git repo. We'll learn to use git reset to move changes back and forth between the "three trees" - working tree, index, and HEAD. To go more in-depth, work thru The Objects and Trees Exercise.

Vocabulary:

  • working tree, index, HEAD
  • "detached HEAD" state

Commands:
git reset --soft, git reset --mixed, git reset --hard,
git diff, git diff --staged,
git reflog, git stash

A busy diagram, but worth pondering nonetheless. It shows the objects as well as the trees.

LAB - Commit changes and then modify them with git reset

Use each of git reset's --soft, --mixed, and --hard options at least once.

  1. Make a change and commit it (do not git push!).
  2. Undo the change using git reset.
  3. Make another change, and commit.
  4. Undo it, using another option of git reset. Commit.
  5. Undo it, using another option of git reset. Commit.

🤔 So far, we've only used git reset to move our current branch back one commit. But with git reset, we can move our current branch anywhere we want. When might this be useful?

Scenario 1: You accidentally make commits on main, but then realize you should be on a different branch--for instance, in order to push that branch and submit a Pull Request for it (we'll discuss PR's soon).

🤔 When might git reset be the wrong way to back out changes? (TODO: Instructor, be sure to cover this!)

Scenario 2: Same as above, except that you've already pushed those changes 😬, which means your teammates may have pulled them. If you git reset, you'll get a merge conflict when you try to push. And if you git push --force, your teammates will very likely be upset with you! How do you "gracefully" undo those changes?

Show a solution

No problem; just use git revert!

(Instructor TO-DO: Cover how git revert differs from git reset, and exctly why/when it's more palatable to your teammates.)

LAB - Simulate branching "after-the-fact"

  1. Make 3 or 4 commits on main. Then realize, "Ooops, I should be on another branch".
  2. Make a branch at your current location. Hover here for a hint.
  3. Use git reset to move main back to where it should be.

Key Learning Points:

✅ git doesn't care as much about your working tree as you might assume. It mostly cares about the objects in its database and frequently uses its database to overwrite your working tree. That said, git is not reckless; it will give you warnings about git operations that might be destructive to your local work.

✅ If you can understand and make the round-trip through the "Managing Local Changes" diagram in the Cheat Sheet, you have a great foundation for understanding how git works!