2025-02-14 Programming, Productivity

Understanding the Git Workflow

By O. Wolfson

Git operates through three main areas:

  1. Working Directory: This is where you modify files in your project. Any changes made here are considered unstaged.
  2. Staging Area (Index): Files added to this area are prepared for the next commit. This allows you to control which changes are included.
  3. Repository: The committed changes are stored here as a permanent part of the project's history. This can be local or remote (on GitHub, GitLab, etc.).

The workflow generally follows this sequence:

  1. Modify files in the working directory.
  2. Add specific files to the staging area (git add).
  3. Commit the staged changes to the repository (git commit).
  4. Push commits to a remote repository for backup or collaboration (git push).

Creating a New Repository (git init)

To start tracking files with Git, initialize a new repository:

sh
mkdir my_project
cd my_project
git init

This creates a hidden .git directory that holds all version control information.

Tracking Files & Making Commits

After initializing a repository, Git does not automatically track files. You must explicitly add them:

sh
echo "# My Project" > README.md

Check the status of the repository:

sh
git status

Stage the file:

sh
git add README.md

Commit the changes with a meaningful message:

sh
git commit -m "Initial commit: Added README"

Viewing Changes (git status, git diff)

  • git status shows which files are modified, staged, or untracked.
  • git diff displays differences between the working directory and the staging area.
  • git diff --staged compares the staging area with the last commit.

Understanding Commit History (git log, git show)

  • git log displays the commit history in reverse chronological order.
  • git log --oneline gives a concise summary of commits.
  • git show <commit_hash> provides details of a specific commit.

Example:

sh
git log --oneline

Output:

text
4f6b3c2 Initial commit: Added README

To view details of a commit:

sh
git show 4f6b3c2

Hands-on Exercise: Create a New Repo, Track Changes, and Commit with Meaningful Messages

  1. Initialize a new Git repository:
    sh
    mkdir my_git_project
    cd my_git_project
    git init
    
  2. Create a new file and check Git status:
    sh
    echo "Hello, Git!" > hello.txt
    git status
    
  3. Stage and commit the file:
    sh
    git add hello.txt
    git commit -m "Added hello.txt with a greeting message"
    
  4. Modify the file and view changes:
    sh
    echo "Welcome to version control." >> hello.txt
    git diff
    
  5. Stage and commit the changes:
    sh
    git add hello.txt
    git commit -m "Updated hello.txt with an additional message"
    
  6. View commit history:
    sh
    git log --oneline
    

This exercise helps solidify the Git workflow and best practices for managing source code effectively.