Git Workflow
This chapter explores Git workflows in depth, helping you understand how Git manages file versions and the role of different operations throughout the process.
Git Workflow Overview
Git workflow can be simplified into the following steps:
1. Modify files (Working Directory)
2. Stage changes (git add → Staging Area)
3. Commit changes (git commit → Repository)
4. Push to remote (git push → Remote Repository)Detailed Workflow Diagram
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Working │ │ Staging │ │ Local │ │ Remote │
│ Directory │ │ Area │ │ Repository │ │ Repository │
│ (Work Area) │ │ (Index) │ │ (Local Repo) │ │ (Remote Repo) │
└─────────────────┘ └─────────────────┘ └─────────────────┘ └─────────────────┘
│ │ │ │
│ git add │ │ │
├──────────────────────→│ │ │
│ │ git commit │ │
│ ├──────────────────────→│ │
│ │ │ git push │
│ │ ├──────────────────────→│
│ │ │ │
│ git checkout │ │ git pull/fetch │
←───────────────────────────────────────────────────────────────────────┤
│ │ │ │Four Working Areas Explained
1. Working Directory
Definition: The place where you actually edit files, which is the project folder you see in your file manager.
Characteristics:
- Contains the actual files of the project
- You can freely edit, create, and delete files
- Git monitors file changes in this area
Example Operations:
# Create file in working directory
echo "Hello World" > hello.txt
# Edit file
vim hello.txt
# Check working directory status
git status2. Staging Area (Index)
Definition: A temporary area used to store snapshots of files to be committed.
Characteristics:
- Acts as a buffer between working directory and repository
- Allows selective addition of file modifications
- Allows precise control over the content of each commit
Example Operations:
# Add file to staging area
git add hello.txt
# Add all modified files
git add .
# View staging area content
git status
# Remove file from staging area (but keep working directory changes)
git restore --staged hello.txt3. Local Repository
Definition: The place where the complete history of the project is stored, located in the .git folder.
Characteristics:
- Contains complete history of all commits
- Stores branch and tag information
- Works completely offline
Example Operations:
# Commit staging area content to local repository
git commit -m "Add hello.txt file"
# View local repository history
git log
# View branches
git branch4. Remote Repository
Definition: A copy of the repository hosted on the network, used for team collaboration.
Characteristics:
- Usually hosted on platforms like GitHub, GitLab
- Multiple people can access and collaborate
- Acts as the "authoritative" version of the project
Example Operations:
# Add remote repository
git remote add origin https://github.com/username/repo.git
# Push to remote repository
git push origin main
# Pull updates from remote repository
git pull origin mainTypical Workflow Example
Let's demonstrate the Git workflow with a complete example:
Scenario: Developing a New Feature
1. Preparation
# Create new project
mkdir git-workflow-demo
cd git-workflow-demo
git init
# Configure (if global config is not set)
git config user.name "John Doe"
git config user.email "johndoe@example.com"2. Create Initial Files
# Create file in working directory
cat > app.py << EOF
#!/usr/bin/env python3
def main():
print("Welcome to our app!")
if __name__ == "__main__":
main()
EOF
# Check status - File is in working directory, untracked
git statusOutput:
On branch main
No commits yet
Untracked files:
(use "git add <file>..." to include in what will be committed)
app.py
nothing added to commit but untracked files present (use "git add" to track)3. Add to Staging Area
# Add file to staging area
git add app.py
# Check status - File is now in staging area
git statusOutput:
On branch main
No commits yet
Changes to be committed:
(use "git rm --cached <file>..." to unstage)
new file: app.py4. Commit to Local Repository
# Commit to local repository
git commit -m "Initial commit: Add basic app structure"
# Check status - Working tree clean
git statusOutput:
On branch main
nothing to commit, working tree clean5. Develop New Feature
# Modify file (in working directory)
cat >> app.py << EOF
def greet_user(name):
return f"Hello, {name}!"
def get_user_name():
return input("Please enter your name: ")
EOF
# View changes
git diff6. Staged Commits
# Commit part of the changes
git add app.py
git commit -m "Add user greeting function"
# Continue modifying
sed -i 's/print("Welcome to our app!")/name = get_user_name(); print(greet_user(name))/' app.py
# Commit new changes
git add app.py
git commit -m "Integrate user greeting into main program"7. Push to Remote Repository
# Add remote repository (Assuming created on GitHub)
git remote add origin https://github.com/username/git-workflow-demo.git
# Push to remote
git push -u origin mainFile Status Lifecycle
Files in Git have four states:
Untracked ──git add──→ Staged ──git commit──→ Committed
↑ │ │
│ │ │
└──git rm─────────────┘ │
│
Modified ←──edit file────────────────────────────┘
│
└──git add──→ StagedFile States Explained
Untracked
- Newly created files
- Git does not automatically track them
- Need
git addto start tracking
Staged
- Files added to the staging area
- Ready to be included in the next commit
- Can be unstaged using
git restore --staged
Committed
- Files saved to the local repository
- Become part of the project history
- Safe to modify or delete
Modified
- Tracked files modified in the working directory
- Need to be added to the staging area again to be committed
Viewing File Status
# View detailed status
git status
# View concise status
git status -s
# Output example:
# M modified_file.txt # Modified and staged
# M modified_file2.txt # Modified but not staged
# A new_file.txt # New file staged
# ?? untracked_file.txt # Untracked fileCommon Workflow Patterns
1. Basic Personal Development Flow
# 1. Modify files
vim file.txt
# 2. View changes
git diff
# 3. Add to staging area
git add file.txt
# 4. Commit
git commit -m "Describe changes"
# 5. Push (if remote repository exists)
git push2. Feature Branch Development Flow
# 1. Create feature branch
git checkout -b feature/new-feature
# 2. Develop feature
# ... Edit files ...
git add .
git commit -m "Implement first part of new feature"
# 3. Continue development
# ... More changes ...
git add .
git commit -m "Complete new feature"
# 4. Switch back to main branch
git checkout main
# 5. Merge feature branch
git merge feature/new-feature
# 6. Delete feature branch
git branch -d feature/new-feature
# 7. Push updates
git push3. Collaborative Development Flow
# 1. Get latest code
git pull origin main
# 2. Create feature branch
git checkout -b feature/my-feature
# 3. Develop and commit
git add .
git commit -m "Implement my feature"
# 4. Push branch
git push origin feature/my-feature
# 5. Create Pull Request (on GitHub, etc.)
# 6. Code review and merge (done by maintainer)
# 7. Clean up local branch
git checkout main
git pull origin main
git branch -d feature/my-featureWorkflow Best Practices
1. Commit Frequency
# ✅ Good practice: Frequent small commits
git commit -m "Add user validation function"
git commit -m "Fix login page style issue"
git commit -m "Update user documentation"
# ❌ Avoid: One giant commit
git commit -m "Complete entire user system"2. Commit Message Conventions
# ✅ Good commit messages
git commit -m "feat: Add user login feature"
git commit -m "fix: Fix password validation error"
git commit -m "docs: Update API documentation"
# ❌ Bad commit messages
git commit -m "Modify"
git commit -m "Update code"
git commit -m "bug fix"3. Using Staging Area
# ✅ Selective staging
git add specific_file.py # Add only specific file
git add -p # Interactive add partial changes
# ✅ View staged content
git diff --staged # View diff between staging area and last commit4. Working Directory Management
# ✅ Keep working directory clean
git status # Check status frequently
git clean -n # Preview untracked files to be deleted
git clean -f # Delete untracked files
# ✅ Use .gitignore
echo "*.log" >> .gitignore
echo "node_modules/" >> .gitignore
git add .gitignore
git commit -m "Add .gitignore file"Workflow Troubleshooting
Common Issues and Solutions
1. Forgot to add file to staging area
# Problem: Committed but missed a file
git add forgotten_file.txt
git commit --amend --no-edit # Modify last commit2. Wrong commit message
# Modify last commit message
git commit --amend -m "Correct commit message"3. Working directory has unsaved changes, need to switch branch
# Method 1: Stash changes
git stash
git checkout other-branch
# After work is done
git checkout original-branch
git stash pop
# Method 2: Commit temporary changes
git add .
git commit -m "WIP: Temporarily save work progress"
# Clean up later using git reset or git commit --amend4. Accidentally deleted file
# Restore tracked file
git restore deleted_file.txt
# Or use old syntax
git checkout -- deleted_file.txtVisualization Tools
Command Line Visualization
# Graphically display branch history
git log --graph --oneline --all
# Display file modification statistics
git log --stat
# Display detailed changes of each commit
git log -pRecommended Graphical Tools
- GitKraken - Beautiful cross-platform client
- SourceTree - Free Git client
- GitHub Desktop - GitHub official client
- VS Code - Editor with built-in Git support
Summary
The core of Git workflow is understanding the relationship between the four areas:
- Working Directory →
git add→ Staging Area - Staging Area →
git commit→ Local Repository - Local Repository →
git push→ Remote Repository
After mastering this workflow, you will be able to:
- ✅ Effectively manage code versions
- ✅ Collaborate with team members
- ✅ Safely experiment with new features
- ✅ Track project history
In the next chapter, we will delve into specific concepts and operations of working directory, staging area, and repository.