Git là gì? Các lệnh thường dùng khi đi làm, Github & Gitlab, Source Control trong VSCode, Git Graph, Git Blame, Sourcetree
Hướng dẫn chi tiết về Git từ cơ bản đến nâng cao: các lệnh Git thường dùng, làm việc với Github/Gitlab, sử dụng Source Control VSCode, Git Graph, Git Blame và Sourcetree
Git là gì?
Git là một hệ thống quản lý phiên bản phân tán (Distributed Version Control System - DVCS) được tạo ra bởi Linus Torvalds vào năm 2005. Git giúp theo dõi các thay đổi trong mã nguồn, cho phép nhiều lập trình viên cùng làm việc trên một dự án mà không gây xung đột.
Tại sao cần sử dụng Git?
- Quản lý phiên bản: Theo dõi lịch sử thay đổi của code
- Làm việc nhóm: Nhiều người có thể làm việc đồng thời trên cùng một dự án
- Backup tự động: Mã nguồn được lưu trữ an toàn trên nhiều máy
- Branching & Merging: Phát triển tính năng mới mà không ảnh hưởng code chính
- Code Review: Dễ dàng xem xét và phê duyệt thay đổi
Các khái niệm cơ bản
- Repository (Repo): Kho chứa mã nguồn và lịch sử thay đổi
- Commit: Một snapshot của code tại một thời điểm
- Branch: Nhánh phát triển độc lập
- Merge: Gộp các thay đổi từ branch này sang branch khác
- Remote: Repository ở trên server (Github, Gitlab)
- Clone: Sao chép repo từ remote về local
- Push: Đẩy commit từ local lên remote
- Pull: Lấy commit từ remote về local
Cài đặt Git
Windows
Tải từ website chính thức
https://git-scm.com/download/winLinux (Ubuntu/Debian)
sudo apt update
sudo apt install gitKiểm tra cài đặt
git --versionCấu hình Git lần đầu
# Cấu hình tên và email (bắt buộc)
git config --global user.name "Tên của bạn"
git config --global user.email "email@example.com"
# Kiểm tra cấu hình
git config user.name
git config user.emailCác lệnh Git thường dùng khi đi làm
1. Khởi tạo và Clone Repository
# Khởi tạo repo mới
git init
# Clone repo từ remote
git clone https://github.com/username/repo.git
# Clone với tên thư mục khác
git clone https://github.com/username/repo.git my-project
# Clone một branch cụ thể
git clone -b branch-name https://github.com/username/repo.git2. Làm việc với Staging và Commit
# Xem trạng thái working directory
git status
git status -s # Short format
# Thêm file vào staging area
git add file.txt
git add . # Thêm tất cả file đã thay đổi
git add *.c # Thêm tất cả file .c
# Bỏ file khỏi staging area
git reset file.txt
git reset # Bỏ tất cả file khỏi staging
# Commit thay đổi
git commit -m "Message mô tả thay đổi"
git commit -am "Add and commit in one" # Chỉ với file đã tracked
# Sửa commit cuối cùng
git commit --amend -m "New message"
git commit --amend --no-edit # Giữ nguyên message
# Xem lịch sử commit
git log
git log --oneline # Compact format
git log --graph --oneline # Với graph
git log --author="Tên" # Lọc theo tác giả
git log -n 5 # 5 commit gần nhất
git log --since="2024-01-01" # Từ ngày cụ thể3. Làm việc với Branch
# Xem danh sách branch
git branch
git branch -a # Bao gồm cả remote branch
# Tạo branch mới
git branch feature-x
# Chuyển sang branch khác
git checkout feature-x
git switch feature-x # Cách mới (Git 2.23+)
# Tạo và chuyển sang branch mới
git checkout -b feature-x
git switch -c feature-x
# Đổi tên branch
git branch -m old-name new-name
git branch -m new-name # Đổi tên branch hiện tại
# Xóa branch
git branch -d feature-x # Xóa branch đã merge
git branch -D feature-x # Force xóa
# Xóa remote branch
git push origin --delete feature-x4. Merge
# Merge branch vào branch hiện tại
git merge feature-x
git merge feature-x --no-ff # Luôn tạo merge commit
# Hủy merge (khi có conflict)
git merge --abort5. Làm việc với Remote
# Xem danh sách remote
git remote -v
# Thêm remote
git remote add origin https://github.com/username/repo.git
# Đổi URL remote
git remote set-url origin https://github.com/username/new-repo.git
# Xóa remote
git remote remove origin
# Lấy thông tin từ remote (không merge)
git fetch origin
git fetch --all
# Pull = Fetch + Merge
git pull origin main
git pull --rebase origin main # Dùng rebase thay vì merge
# Push lên remote
git push origin main
git push -u origin main # Set upstream
git push --all # Push tất cả branch
git push --tags # Push tất cả tag
# Force push (cẩn thận!)
git push --force origin main
git push --force-with-lease # An toàn hơn6. Xử lý Conflict
# Khi có conflict, Git sẽ báo
# 1. Mở file conflict, tìm các dấu hiệu:
# <<<<<<< HEAD
# Code của bạn
# =======
# Code từ branch khác
# >>>>>>> branch-name
# 2. Sửa file, giữ lại code mong muốn
# 3. Add file đã resolve
git add file-with-conflict.txt
# 4. Tiếp tục merge
git merge --continue7. Undo Changes
# Hủy thay đổi file trong working directory
git restore file.txt # Cách mới
# Hủy tất cả thay đổi chưa commit
git reset --hard HEAD
# Unstage file (giữ thay đổi)
git reset HEAD file.txt
git restore --staged file.txt # Cách mới
# Quay về commit trước (giữ thay đổi)
git reset --soft HEAD~1
# Quay về commit trước (xóa thay đổi)
git reset --hard HEAD~1
# Tạo commit mới để đảo ngược commit cũ
git revert HEAD
git revert <commit-hash>8. Xem Changes
# So sánh giữa các branch
git diff main feature-x
# So sánh giữa các commit
git diff commit1 commit2
# Xem thay đổi của một file cụ thể
git diff file.txt9. Github vs Gitlab
Github
Github là nền tảng hosting Git phổ biến nhất, thuộc sở hữu của Microsoft.
Ưu điểm:
- Cộng đồng lớn nhất
- Giao diện thân thiện
- Github Actions (CI/CD miễn phí)
- Github Pages (hosting static website)
- Nhiều integration và marketplace
Tính năng nổi bật:
- Pull Request: Review code, discussion
- Issues: Quản lý bug, feature request
- Projects: Kanban board
- Actions: CI/CD workflows
- Codespaces: Dev environment trên cloud
- Copilot: AI code assistant
Làm việc với Github:
# Clone repo
git clone https://github.com/username/repo.git
# Thêm SSH key (recommended)
# 1. Generate SSH key
ssh-keygen -t ed25519 -C "your_email@example.com"
# 2. Copy public key
cat ~/.ssh/id_ed25519.pub
# 3. Add vào Github Settings > SSH Keys
# Clone bằng SSH
git clone git@github.com:username/repo.gitGitlab
Gitlab là nền tảng DevOps hoàn chỉnh, có thể self-hosted.
Ưu điểm:
- Có thể tự host (self-hosted)
- CI/CD mạnh mẽ (Gitlab CI)
- Hoàn toàn miễn phí cho private repo
- Tích hợp DevOps tools
Tính năng nổi bật:
- Merge Request: Tương tự Pull Request
- CI/CD Pipelines: Rất mạnh, dùng
.gitlab-ci.yml - Container Registry: Lưu Docker images
- Wiki: Documentation
- Issue Boards: Kanban
So sánh Github vs Gitlab:
| Tính năng | Github | Gitlab |
|---|---|---|
| Cộng đồng | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ |
| Self-hosted | ❌ | ✅ |
| CI/CD miễn phí | 2000 phút/tháng | 400 phút/tháng |
| Private repo miễn phí | ✅ | ✅ |
| Pages | ✅ | ✅ |
| Container Registry | ✅ (packages) | ✅ |
Source Control trong VSCode
VSCode có tích hợp Git rất mạnh mẽ, dễ sử dụng.
Mở Source Control
- Shortcut:
Ctrl+Shift+G(Windows/Linux) hoặcCmd+Shift+G(Mac) - Hoặc: Click icon Source Control ở sidebar
Các thao tác cơ bản:
1. Initialize Repository
Click "Initialize Repository" trong Source Control panel
2. Stage Changes
- Click dấu
+bên cạnh file để stage - Click
+bên cạnh "Changes" để stage tất cả - Shortcut: Hover vào file và bấm
+
3. Unstage Changes
- Click dấu
-bên cạnh file đã stage
4. Commit
- Nhập commit message vào ô text box
- Click ✓ (checkmark) hoặc
Ctrl+Enter
5. Discard Changes
- Right-click file → "Discard Changes"
- Cẩn thận: Không thể undo!
6. View Changes
- Click vào file trong Source Control panel
- VSCode hiển thị diff view với:
- ❌ Red: Dòng đã xóa
- ✅ Green: Dòng đã thêm
- Split view: So sánh trực quan
Làm việc với Branch:
Tạo/Switch branch:
- Click branch name ở status bar (góc dưới trái)
- Chọn "Create new branch" hoặc chọn branch có sẵn
Merge branch:
- Command Palette (
Ctrl+Shift+P) - Gõ "Git: Merge Branch"
- Chọn branch muốn merge
Sync với Remote:
Push/Pull:
- Click ↑↓ icon trên status bar
- Hoặc click
...trong Source Control → "Push" / "Pull"
Fetch:
- Click
...→ "Fetch"
Settings hữu ích:
{
// Auto fetch
"git.autofetch": true,
// Confirm trước khi sync
"git.confirmSync": false,
// Enable smart commit (tự stage all khi commit)
"git.enableSmartCommit": true,
// Số dòng context trong diff view
"diffEditor.renderSideBySide": true
}Git Graph - Visualize Repository
Git Graph là extension tuyệt vời để visualize Git history dạng graph.
Cài đặt:
Extensions → Search "Git Graph" → Install
Sử dụng:
Mở Git Graph:
- Click icon "Git Graph" trên status bar
- Hoặc Command Palette → "Git Graph: View Git Graph"
Tính năng chính:
-
Xem Graph:
- Hiển thị tree của tất cả commit
- Các branch được hiển thị bằng màu khác nhau
- Dễ thấy merge, branch points
-
Thông tin Commit:
- Click vào commit để xem chi tiết
- Xem files changed
- Xem diff
-
Thao tác với Commit:
- Right-click commit:
- Checkout
- Cherry-pick
- Revert
- Create branch
- Create tag
- Copy hash
- Right-click commit:
-
Thao tác với Branch:
- Right-click branch:
- Checkout
- Delete
- Merge into current branch
- Rebase current branch on branch
- Push
- Pull
- Right-click branch:
-
Filter:
- Filter theo branch
- Search commit message
- Filter theo author
Settings hữu ích:
{
// Số commit tối đa hiển thị
"git-graph.maxCommits": 500,
// Hiển thị uncommitted changes
"git-graph.showUncommittedChanges": true,
// Date format
"git-graph.dateFormat": "ISO Date & Time",
// Fetch automatically
"git-graph.fetchAvatars": true
}Workflow thực tế với Git Graph:
1. Mở Git Graph để xem overview
2. Xem branch nào đang active
3. Xem commits gần đây
4. Click vào commit để xem changes
5. Right-click để thực hiện operations
Git Blame - Xem ai sửa dòng code nào
Git Blame giúp xác định ai là người cuối cùng sửa từng dòng code.
Sourcetree - Git GUI Client
Sourcetree là Git GUI client miễn phí của Atlassian, rất mạnh mẽ và dễ dùng.
Download và cài đặt:
https://www.sourcetreeapp.com/
Tính năng chính:
1. Visual Repository
- Xem graph của toàn bộ repository
- Branches hiển thị rõ ràng
- Dễ thấy merge points, conflicts
2. Staging và Commit
- File Status: Xem file nào đã thay đổi
- Hunk Staging: Stage từng phần của file (không phải cả file)
- Diff View: So sánh changes trực quan
- Commit: Nhập message và commit
3. Branch Management
- Create Branch: Click chuột phải → Create Branch
- Checkout: Double-click branch
- Merge: Drag & drop branch
- Delete: Right-click → Delete
4. Remote Operations
- Push/Pull: Các button rõ ràng trên toolbar
- Fetch: Lấy thông tin từ remote
- Remote Branches: Xem tất cả remote branch
5. Stash
- Stash Changes: Lưu tạm thời changes
- Apply Stash: Apply stash đã lưu
- Stash Manager: Quản lý nhiều stash
6. Search
- Search commit by:
- Message
- Author
- Date
- Hash
- File
7. Git Flow
- Tích hợp Git Flow workflow
- Tự động tạo feature/release/hotfix branch
Workflow thực tế với Sourcetree:
1. Clone/Add repository
2. Xem graph để hiểu current state
3. Create branch cho feature mới
4. Code...
5. Xem File Status để review changes
6. Stage changes (có thể stage từng hunk)
7. Commit với message rõ ràng
8. Push lên remote
9. Tạo Pull Request trên Github/Gitlab
10. Sau khi merge, pull về và xóa local branch
Ưu điểm của Sourcetree:
✅ Giao diện đẹp, trực quan ✅ Không cần nhớ lệnh Git ✅ Hunk staging rất tiện ✅ Conflict resolution tool tốt ✅ Git Flow integration ✅ Miễn phí
Nhược điểm:
❌ Hơi nặng, khởi động chậm ❌ Đôi khi bị lag với repo lớn ❌ Không có trên Linux
Lựa chọn khác:
- GitKraken: Đẹp hơn, nhưng trả phí
- Fork: Nhẹ, nhanh, trả phí
- GitHub Desktop: Đơn giản, free, nhưng ít tính năng
- Tortoise Git: Free, Windows only
Workflow Git khi đi làm
1. Feature Branch Workflow
# 1. Pull main branch mới nhất
git checkout main
git pull origin main
# 2. Tạo feature branch
git checkout -b feature/user-authentication
# 3. Develop feature
# ... code ...
git add .
git commit -m "feat: implement user login"
# 4. Push feature branch
git push -u origin feature/user-authentication
# 5. Tạo Pull Request trên Github/Gitlab
# 6. Sau khi review và merge
git checkout main
git pull origin main
git branch -d feature/user-authentication2. Hotfix Workflow
# 1. Từ main, tạo hotfix branch
git checkout main
git checkout -b hotfix/fix-login-bug
# 2. Fix bug
git add .
git commit -m "fix: resolve login session timeout"
# 3. Push và tạo PR
git push -u origin hotfix/fix-login-bug
# 4. Sau khi merge, tag version
git checkout main
git pull origin main
git tag -a v1.0.1 -m "Hotfix: login session timeout"
git push origin v1.0.14. .gitignore
Tạo file .gitignore để ignore files không cần track:
# Build outputs
dist/
build/
*.log
# Environment variables
.env
.env.local
# IDE
.vscode/
.idea/
*.swp
*.swo
# Python
__pycache__/
*.py[cod]
venv/5. Best Practices
✅ Commit thường xuyên: Nhỏ và atomic ✅ Write good commit messages: Rõ ràng, có ý nghĩa ✅ Pull trước khi Push: Tránh conflict ✅ Review code: Không merge PR mà không review ✅ Use branches: Không code trực tiếp trên main ✅ Keep main stable: Main branch luôn deployable ✅ Delete merged branches: Giữ repo sạch sẽ ✅ Tag releases: Dễ rollback và tracking
❌ Force push lên shared branch: Nguy hiểm! ❌ Commit credentials: API keys, passwords ❌ Large files: Dùng Git LFS cho files lớn ❌ Generated files: Build outputs, node_modules
Tổng kết
Checklist cho người mới:
- Cài đặt Git
- Cấu hình user.name và user.email
- Học các lệnh cơ bản: add, commit, push, pull
- Tạo Github/Gitlab account
- Cài đặt VSCode + GitLens extension
- Cài đặt Git Graph extension
- Thực hành với repo test
- Đọc về Git Flow workflow
- Học cách resolve conflicts
- Thực hành Pull Request
Resources học thêm:
- Official Git Book: https://git-scm.com/book/en/v2
- Atlassian Git Tutorials: https://www.atlassian.com/git/tutorials
- Git Cheat Sheet: https://education.github.com/git-cheat-sheet-education.pdf
- Interactive Git: https://learngitbranching.js.org/
Kết luận
Git là công cụ không thể thiếu trong lập trình hiện đại. Việc thành thạo Git không chỉ giúp bạn quản lý code tốt hơn mà còn là yêu cầu bắt buộc của hầu hết các công ty công nghệ.
Hãy thực hành nhiều, đừng ngại thử nghiệm (với repo test), và dần dần bạn sẽ trở nên tự tin với Git. Remember: Git is your friend, not your enemy! 🚀
Bài viết liên quan
Docker Best Practices cho Production
Từ development đến production - học cách build Docker images secure, efficient, và production-ready.
Neural Networks từ Zero: Backpropagation
Backpropagation là trái tim của deep learning. Hiểu rõ thuật toán này giúp bạn master được cách neural networks học từ data.
Smart Pointers trong C++ Modern
Smart pointers là một trong những tính năng quan trọng nhất của C++ hiện đại, giúp tự động quản lý bộ nhớ và tránh memory leaks.