Staging and committing

Intermediate

Introduction

Git does not simply save whatever is in your folder. Between your files and the history sits the staging area, also called the index: a draft of the next commit. You decide exactly which changes go into it, so one commit can contain a bug fix while an unfinished experiment in another file waits for later. Understanding these three places explains almost everything git status tells you.

How it works

There are three versions of every file to think about:

  1. HEAD: the version in the last commit;
  2. the index: the version staged for the next commit;
  3. the working tree: the version in your folder now.

git add file copies the working-tree version into the index. git commit saves the index as a new commit, which becomes HEAD. After a commit, all three agree, and git status says the tree is clean.

git add app.py notes.txt      # stage these files (git add . stages everything)
git commit -m "Add notes"     # save the index as a commit
git rm old.txt                # delete a file and stage the deletion
git mv a.txt b.txt            # rename a file and stage the rename
git restore --staged app.py   # unstage, keeping the change in the working tree

git status --short prints two letters and a path. The first letter compares the index with HEAD (what is staged); the second compares the working tree with the index (what is not staged yet):

  • M modified, A added, D deleted, a space for no change;
  • ?? marks an untracked file: one Git is not following at all.

So M app.py is a change not yet staged, M app.py a change fully staged, and MM app.py a staged change with newer, unstaged edits on top. A notes.txt is a new file staged for the first time.

Example

head = {"app.py": "v1", "README.md": "v1"}
index = dict(head)
work = dict(head)


def status():
    lines = []
    for path in sorted(set(head) | set(index) | set(work)):
        if path not in head and path not in index:
            continue
        x = "A" if path not in head else "D" if path not in index else "M" if head[path] != index[path] else " "
        y = " " if path not in index else "D" if path not in work else "M" if work[path] != index[path] else " "
        if x + y != "  ":
            lines.append(f"{x}{y} {path}")
    lines += [f"?? {p}" for p in sorted(work) if p not in index]
    return lines or ["(nothing to commit, working tree clean)"]


def show(title):
    print(title)
    for line in status():
        print("   ", line)


work["app.py"] = "v2"
work["notes.txt"] = "v1"
show("after editing app.py and creating notes.txt:")
index["app.py"] = work["app.py"]
show("after git add app.py:")
work["app.py"] = "v3"
show("after editing app.py again:")
index["app.py"] = work["app.py"]
index["notes.txt"] = work["notes.txt"]
head = dict(index)
show("after git add . and git commit:")
Open in compiler

Line by line

  1. Three dictionaries stand for HEAD, the index and the working tree.
  2. status computes the two letters for each path exactly as described above, and lists untracked files with ??.
  3. After editing app.py and creating notes.txt, the edit is unstaged ( M) and notes.txt is untracked.
  4. After git add app.py the change is staged (M ); editing again adds an unstaged change on top (MM).
  5. Staging everything and committing makes HEAD equal to the index and the working tree, so the tree is clean.

Expected result

after editing app.py and creating notes.txt:
     M app.py
    ?? notes.txt
after git add app.py:
    M  app.py
    ?? notes.txt
after editing app.py again:
    MM app.py
    ?? notes.txt
after git add . and git commit:
    (nothing to commit, working tree clean)

In the real world

Developers use the index to make focused commits: git add -p even lets you stage some changes within a file and not others. Editors and IDEs show the same two kinds of change, staged and unstaged, in their source-control panels, and scripts read git status --porcelain, a stable version of the short format.

Common mistakes

  • Expecting git commit to include edits made after git add: it commits the index, not the working tree.
  • Using git add . without checking git status first, committing files you did not mean to.
  • Forgetting new files: untracked files are not committed until they are added.
  • Deleting a file with the system's delete command and forgetting to stage the deletion.

Best practices

  • Run git status before every commit, and git diff --staged to see exactly what will be committed.
  • Stage related changes together and commit them with one clear message.
  • Keep generated and secret files out of the repository with a .gitignore file (covered later).

Summary

The working tree holds your files, the index holds the next commit's snapshot, and HEAD is the last commit. git add copies changes into the index and git commit records it. git status --short shows each file's state as two letters: index against HEAD, then working tree against index, with ?? for untracked files.

Quick check

1. What does git commit save?
2. What does ' M app.py' (space, then M) mean in git status --short?
3. What does ?? mean?
4. How do you unstage app.py but keep your edits?

Key takeaways

  • git add copies the current version of a file into the index; git commit turns the index into a commit.
  • A file can have one change staged and a newer change not staged at the same time.
  • In short status, the first letter compares the index with HEAD, the second the working tree with the index.

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.