Git

What you are looking at

Git keeps the history of a folder. The file box is the working directory, with a sheet for each file in it; a sheet is green until a commit holds it. The row of cylinders beside it is the repository, a hidden folder named .git that holds every commit ever made. Each cylinder is one commit: a snapshot of the staged files, with a message, your name, the time, and a short id. Each commit points back at the one before it. That chain is the history, and main is the name that points at the newest commit.

Between an edit and a commit sits the staging area. git add copies the files as they are now into the next commit, drawn as the dashed ring. git commit turns that into a real commit. Git can take any file back to any node on the chain.

Before the first commit

Install Git from git-scm.com, then tell it who you are. This goes into every commit you make.

git config --global user.name "Your Name"
git config --global user.email "you@example.com"

Then, in a project folder, make it a repository.

git init

The commands you use every day

CommandWhat it does
git statusWhich files changed, which are staged, which Git does not track.
git add notes.txtStage one file. git add . stages everything that changed.
git commit -m "Message"Turn what is staged into a commit.
git diffThe lines that changed and are not staged yet.
git log --onelineThe history, one commit per line.
git restore notes.txtPut the file back as it was in the last commit.

A good commit is one change with a message that says what it does: Add the reading list, Fix the due date. Commit often. Small commits are easy to read, and easy to undo.

Why the staging area exists

You may have changed three files but want to commit only two of them. Stage those two, commit, and the third stays in the working directory for a later commit. The staging area lets you say what one commit means, instead of saving everything you happened to touch.

Files Git should not track

Build output, downloaded packages and secrets do not belong in the history. List them in a file named .gitignore at the top of the project, one pattern per line, and git add . will skip them.

node_modules/
*.log
.env

What is safe

Once a change is committed it is very hard to lose. git log shows every commit, and git restore --source=<id> notes.txt takes a file back to any of them. The only edits Git cannot recover are ones that were never committed, so commit before you try something risky.

Check your understanding

  1. You edit two files and run git commit -m "Done" without git add. What goes into the commit?
  2. After git add notes.txt you edit the file again. What does git status show?
  3. What does git restore notes.txt do to a change you have already committed?
  4. Why should a password never be committed, even if you delete it in the next commit?

Summary

Takeaways