انتقل إلى المحتوى
أمين أبوزيد
منشورBEG-046-L02

المستودعات والتجهيز والـ commits

  • الدرس 2 من 8
  • 11 دقيقة قراءة
  • مبتدئ
في هذا الدرس 11 موضوعات

هذا الدرس متاح حاليًا باللغة الإنجليزية فقط، ولم تُنشر نسخته العربية بعد.

Lesson Overview

In the last lesson you saw why a project needs a history. Now you will build one. You will turn a folder into a repository, choose what goes into a snapshot with staging, and record it with a commit. By the end you will have made real commits, with messages that a teammate (or you, six months from now) can understand.

This is the heart of everyday Git. Almost everything else in this module (history, branches, merging) is a way of looking at, or combining, the commits you learn to make here.

You need a terminal (BEG-006) and Git installed (git --version from the last lesson). All commands below were run with Git 2.44; your version may print slightly different wording. Hashes (the short codes such as 97a2799) will differ on your machine.

Learning Objectives

By the end of this lesson you will be able to:

  • Define a repository and say what git init creates.
  • Set your name and email once with git config.
  • Explain the three places a change can be in: working tree, staging area, and repository.
  • Stage files with git add and record them with git commit -m.
  • Read git status to see what is untracked, modified, or staged.
  • Write a commit message that says what changed and why, and rewrite a vague one.

Written Explanation

Repository and git init

A repository (repo) is a project folder that Git tracks, together with Git's database of its history. git init creates that database:

bash
mkdir greeter
cd greeter
git init
text
Initialized empty Git repository in C:/Users/.../greeter/.git/

Git created a hidden folder named .git inside your project. That folder is the history. Your normal files stay where they are; .git sits beside them. Deleting .git removes the history and turns the folder back into an ordinary folder, so never delete it by accident. Run git init once per project, in the project's top folder, never inside another repository.

By default a new repository's first branch is called master in Git itself (the manual says this will change to main in Git 3.0), but many installations are set up to use main. The branch name only matters from lesson L04 on. To choose it yourself: git init -b main, or once per computer git config --global init.defaultBranch main. This course's examples use main.

Telling Git who you are

Each commit records an author. Set it once per computer:

bash
git config --global user.name "Sara Student"
git config --global user.email "sara@example.com"

Use your own details. Without them, git commit stops with a message asking you to set them.

Three places a change can live

This is the most important idea in the lesson. A change travels through three areas:

AreaAlso calledWhat it holds
Working treeyour filesThe files you edit in your editor or IDE
Staging areathe indexThe changes you have chosen for the next snapshot
Repositoryhistory, .gitThe commits already recorded
text
edit            git add            git commit
working tree ---------> staging ---------------> repository

Why have a middle step? Because the work you did in the last hour might be two different things, such as a bug fix and an unrelated clean-up. Staging lets you record them as two separate commits with two honest messages. The Pro Git book describes the same three states: modified, staged, committed.

Tracked and untracked files

A file Git knows about (it is in the last commit, or you have staged it) is tracked. Everything else is untracked, and Git ignores it until you add it. That is why a brand-new file does nothing until you run git add.

git status: the command you will run most

bash
git status
text
On branch main

No commits yet

Untracked files:
  (use "git add <file>..." to include in what will be committed)
	Greeter.java

nothing added to commit but untracked files present (use "git add" to track)

git status tells you the branch, which files are untracked, which are staged ("Changes to be committed"), and which are modified but not staged ("Changes not staged for commit"). It also hints at the next command. Read it before every commit. A shorter form, git status -s, prints one line per file: the left column is the staging area and the right column is the working tree. ?? means untracked, A means newly staged, M means modified.

git add: choose what goes in

bash
git add Greeter.java

This copies the file's content as it is right now into the staging area. If you edit the file again afterwards, the new edit is not staged until you run git add again. You can name several files (git add A.java B.java). git add . stages everything in the current folder, which is quick but dangerous: it will also stage files you did not mean to include, such as compiled .class files. L06 and L07 deal with that. Until then, prefer naming files.

git commit: record the snapshot

bash
git commit -m "Add Greeter class that prints a greeting"
text
[main (root-commit) 97a2799] Add Greeter class that prints a greeting
 1 file changed, 5 insertions(+)
 create mode 100644 Greeter.java

The commit contains exactly what was staged, not what is in your working tree. -m gives the message on the command line. Without -m, Git opens a text editor for the message; which editor depends on your setup, so if one opens unexpectedly, write the message, save, and close it. The words root-commit appear only for the very first commit of a repository.

Run git status again and it says nothing to commit, working tree clean: the working tree, staging area, and last commit all agree.

Writing a good commit message

A message is a note to a future reader, and the reader is usually you. A good one:

  • is short (one line, readable at a glance in a list);
  • starts with a verb in the imperative: "Add", "Fix", "Rename", "Remove";
  • says what changed and, when it is not obvious, why;
  • describes one change, not "stuff".
BadBetter
fixFix negative balance after withdraw
changesRename amount to balance in Account
updateAdd input check for empty owner name

The imperative style ("Add", not "Added") is a widely used convention rather than a Git rule. What matters most is that your team uses a consistent style and that every message tells a reader something.

The workflow in one loop

  1. Edit files.
  2. git status to see what changed.
  3. git add the files that belong together.
  4. git commit -m "...".

Repeat. Small, frequent commits are much easier to understand and undo than one giant commit at the end of the week.

Examples

Example 1: The first commit (simple)

bash
mkdir greeter && cd greeter
git init -b main

Create Greeter.java:

java
public class Greeter {
    public static void main(String[] args) {
        System.out.println("Hello, Git!");
    }
}
bash
git add Greeter.java
git commit -m "Add Greeter class that prints a greeting"
git status

The last command prints nothing to commit, working tree clean, as long as you have not compiled the program. If you ran javac, Greeter.class is listed as untracked; L06 shows how to ignore such files. Your history has one snapshot.

Example 2: Two changes, two commits (practical)

You add a second class and, at the same time, fix a typo in the first. Instead of one commit called "changes", stage and commit separately:

bash
git add Greeter.java
git commit -m "Fix typo in greeting text"
git add Farewell.java
git commit -m "Add Farewell class"

Later, if the typo fix was wrong, you can undo or inspect it on its own. The staging area made that possible: you chose which file went into which snapshot.

Example 3: Forgetting to stage a second edit (realistic)

Greeter.java is already committed. You edit it, run git add Greeter.java, then edit it again and run git status -s:

text
MM Greeter.java

Two Ms: the file has a staged version (left) and a newer unstaged change (right). If you commit now, only the staged version is recorded. The fix is simple: run git add Greeter.java again to stage the latest content, then commit. This shows why git status before each commit pays off.

Backend Insight

Backend projects have many files and many changes in flight: a database script, a controller, a configuration file. A commit is the unit a team reviews, deploys, and, if needed, reverts. If every commit has one purpose and a clear message, "revert the commit that changed the fee rule" is an easy sentence to say. If it holds eight unrelated changes, undoing one means undoing all.

Staging is also a safety check. Before every commit, git status shows exactly which files are about to be recorded. In backend work that moment is where you notice a file that should not be there: a local settings file or a file containing a password. L06 returns to this.

Common Mistakes

Mistake 1: Vague commit messages

  • Incorrect: git commit -m "fix"
  • Correct: git commit -m "Fix negative balance after withdraw"

Why it happens: you know what you did right now, so the message feels unnecessary. How to avoid it: write for the reader six months from now, who remembers nothing.

Mistake 2: Committing before staging

Running git commit with nothing staged prints a message such as nothing added to commit but untracked files present, and no commit is made. The order is always: add, then commit.

Mistake 3: Editing after git add and assuming the edit is included

  • Incorrect: "I added the file, then changed it, so the commit has my last change."
  • Correct: "The commit has what was staged. I must git add again."

Mistake 4: One huge commit

A commit titled "Add everything" is hard to review and impossible to partly undo. Commit when one coherent step is done.

Exercises

Level A: Foundation

A1. What does git init create, and where?

أظهر الحل A1

A1. It creates a hidden .git folder in the project's top folder. That folder holds the whole history.

A2. Put these in the right order: git commit, edit a file, git add.

أظهر الحل A2

A2. Edit a file, git add, git commit.

A3. What does ?? mean in the output of git status -s?

أظهر الحل A3

A3. The file is untracked: Git sees it but has not been told to track it.

Level B: Application

B1. In a new folder named hello-git, initialise a repository, create Hello.java that prints a line, stage it, and commit it with a clear message. Write the commands you used.

أظهر الحل B1

B1.

bash
mkdir hello-git
cd hello-git
git init -b main
# create Hello.java with a text editor
git add Hello.java
git commit -m "Add Hello program that prints a greeting"

B2. Rewrite each message so it is clear. Use a bug-fix example of your own for the second one: stuff, fix, changes.

أظهر الحل B2

B2. Examples: stuff becomes Add Account class with deposit; fix becomes Fix wrong total when deposit is zero; changes becomes Rename amount to balance in Account. Any message that says what changed is acceptable.

B3. You edited Hello.java, ran git add Hello.java, then edited the file again. What does git status -s show, and what will a commit record?

أظهر الحل B3

B3. It shows MM Hello.java. The commit will record the first, staged version only. Run git add Hello.java again to include the second edit.

Level C: Challenge

C1. You changed two files: Account.java (a bug fix) and Bank.java (a new feature). Write the exact commands that record them as two commits with good messages.

أظهر الحل C1

C1.

bash
git add Account.java
git commit -m "Fix balance not updated after deposit"
git add Bank.java
git commit -m "Add method to list all accounts"

(The messages are examples.)

C2. A teammate says: "git add saves my work, so commit is optional." Explain what is wrong, using the three areas.

أظهر الحل C2

C2. git add only copies the change into the staging area. The change is not in the repository's history until git commit records it. Until then there is no snapshot to go back to.

Mini Challenge

Take a small Java program of yours (or create two small files). Put it in a new repository and make three commits: first the main class, then a second class, then a small edit to one of them. Before each commit, run git status. Finally run git status once more and confirm the tree is clean.

Check your work: each message starts with a verb and says what changed; no commit contains unrelated changes; the final status says nothing to commit, working tree clean.

Summary & Next Lesson

Key takeaways

  • git init makes a folder a repository by creating .git.
  • Changes flow from the working tree, through the staging area, into the repository.
  • git add chooses changes; git commit -m records them as a snapshot.
  • git status shows what is untracked, modified, or staged; read it before committing.
  • Good messages are short, start with a verb, and say what changed.

Next lesson

Next is "History and diffs": you will list your commits with git log and see exactly which lines changed with git diff.

Self-check

  1. Which comes first, add or commit?
  2. What is the staging area for?
  3. After git add A.java you edit A.java again. Is the new edit in the next commit?
  4. Which is a better message: update or Add deposit method to Account?
  5. What does git status say after a successful commit with nothing else changed?
أظهر الإجابات
  1. add, then commit.
  2. To choose which changes go into the next snapshot, so unrelated changes can be committed separately.
  3. No. Only the staged version is included until you run git add again.
  4. Add deposit method to Account.
  5. nothing to commit, working tree clean.

References

  • Pro Git book, "Recording Changes to the Repository". It supports the tracked/untracked distinction, the meaning of git status and git status -s columns, and that a commit records the staged snapshot.
  • Git documentation, git init. It supports what git init creates, -b / init.defaultBranch, and that the default is master until Git 3.0.
  • Pro Git book, "What is Git?". It supports the three states modified, staged, and committed.
  • I did not fetch an authoritative source for commit-message style; the imperative style is described here as a common convention. The command output was produced with Git 2.44 in a scratch repository.

التطبيق

طبّق هذا الدرس بمختبر الوحدة وتمارينها واختبارها.

المختبر والتمارين الاختبار

تعليم الدرس كمكتمل اختياري ويمكنك التراجع عنه في أي وقت. يبقى تقدمك محفوظًا في هذا المتصفح.

اكتب للبحث في المستويات والمراحل والوحدات والدروس.