Nội dung

DaiPhan

DaiPhan

Full-Stack Developer

Full-stack developer passionate about modern web technologies, best practices, and sharing knowledge with the community.

Skills & Expertise

JavaScript TypeScript React Node.js DevOps
150+
Articles
50k+
Readers
4.9
Rating

Git Best Practices: Quy trình làm việc hiệu quả với Git

Hướng dẫn các best practices khi làm việc với Git, bao gồm branching strategy, commit message, và collaboration workflow

Git Best Practices: Quy trình làm việc hiệu quả với Git

Git là công cụ thiết yếu cho developer. Việc sử dụng Git đúng cách giúp team làm việc hiệu quả và tránh conflicts. Bài viết này chia sẻ các best practices cho Git workflow.

1. Branching Strategy

Git Flow

# Main branches
main (or master)    # Production-ready code
develop            # Integration branch

# Supporting branches
feature/*          # New features
release/*          # Release preparation
hotfix/*          # Production fixes

GitHub Flow (Đơn giản hơn)

main               # Production code
feature/*          # Feature development

Ví dụ workflow thực tế

# 1. Clone repository
git clone https://github.com/username/project.git
cd project

# 2. Tạo feature branch từ main
git checkout -b feature/user-authentication

# 3. Làm việc trên feature branch
# ... viết code ...

# 4. Commit thay đổi
git add .
git commit -m "feat: implement user login functionality"

# 5. Push feature branch
git push origin feature/user-authentication

# 6. Tạo Pull Request trên GitHub
# 7. Code review và merge vào main

2. Commit Message Convention

Format chuẩn

<type>(<scope>): <subject>

<body>

<footer>

Các type chính

  • feat: New feature
  • fix: Bug fix
  • docs: Documentation changes
  • style: Code style changes (formatting, semicolons, etc)
  • refactor: Code refactoring
  • test: Adding or modifying tests
  • chore: Maintenance tasks

Ví dụ commit messages

# Good commit messages
git commit -m "feat(auth): add JWT token validation"
git commit -m "fix(api): resolve user profile data fetching issue"
git commit -m "docs(readme): update installation instructions"
git commit -m "style(components): format code with prettier"
git commit -m "refactor(utils): simplify date formatting function"
git commit -m "test(auth): add unit tests for login service"

Commit body chi tiết

git commit -m "feat(api): implement rate limiting for API endpoints

- Add express-rate-limit middleware
- Configure 100 requests per 15 minutes per IP
- Skip rate limiting for authenticated admin users
- Add custom error message for rate limit exceeded

Closes #123"

3. Pull Request Best Practices

PR Template

## Description
Brief description of changes

## Type of Change
- [ ] Bug fix
- [ ] New feature
- [ ] Breaking change
- [ ] Documentation update

## Testing
- [ ] Unit tests pass
- [ ] Integration tests pass
- [ ] Manual testing completed

## Screenshots (if applicable)
Add screenshots here

## Checklist
- [ ] Code follows project style guidelines
- [ ] Self-review completed
- [ ] Comments added for complex code
- [ ] Documentation updated
- [ ] No new warnings generated

PR Size Guidelines

  • Tốt nhất: < 250 lines
  • Chấp nhận được: < 500 lines
  • Cần review cẩn thận: > 500 lines
  • Nên chia nhỏ: > 1000 lines

4. Interactive Rebase

Sửa commit history

# Xem 5 commit gần nhất
git log --oneline -5

# Bắt đầu interactive rebase
git rebase -i HEAD~3

# Trong editor, có thể:
# - pick: giữ commit
# - reword: sửa commit message
# - edit: sửa commit content
# - squash: gộp commit
# - drop: xóa commit

Ví dụ rebase thực tế

# Before rebase
abc1234 feat: add login functionality
def5678 fix: resolve typo in login
ghi9012 feat: add logout functionality

# Sau khi rebase và squash
git rebase -i HEAD~3
# Chọn squash cho commit def5678 và ghi9012
# Kết quả:
abc1234 feat: add login functionality
jkl3456 feat: add authentication features (login & logout)

5. Stash và Cherry-pick

Git Stash

# Lưu thay đổi tạm thời
git stash save "Work in progress on user profile"

# Xem danh sách stash
git stash list

# Apply stash
git stash apply stash@{0}

# Apply và xóa stash
git stash pop

Cherry-pick

# Áp dụng commit cụ thể từ branch khác
git cherry-pick abc1234

# Cherry-pick nhiều commit
git cherry-pick abc1234..def5678

6. Git Hooks

Pre-commit Hook

# File: .git/hooks/pre-commit
#!/bin/sh
# Run tests before commit
npm test

# Run linter
npm run lint

# Check code formatting
npm run format:check

# If any command fails, prevent commit
if [ $? -ne 0 ]; then
  echo "Pre-commit checks failed!"
  exit 1
fi

Husky (Quản lý hooks)

// package.json
{
  "husky": {
    "hooks": {
      "pre-commit": "npm test && npm run lint",
      "commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
    }
  }
}

7. Collaboration Workflow

Daily Workflow

# 1. Start day - update local main
git checkout main
git pull origin main

# 2. Create/switch to feature branch
git checkout -b feature/my-feature
# hoặc
git checkout feature/my-feature
git rebase main

# 3. Work and commit
git add .
git commit -m "feat: implement feature X"

# 4. Push changes
git push origin feature/my-feature

# 5. Create PR và request review

Resolve Conflicts

# 1. Update main branch
git checkout main
git pull origin main

# 2. Rebase feature branch
git checkout feature/my-feature
git rebase main

# 3. Giải quyết conflicts (nếu có)
# Edit conflicted files
# git add .
# git rebase --continue

# 4. Force push (sau khi rebase)
git push origin feature/my-feature --force-with-lease

8. Git Aliases

Tạo aliases thông dụng

# Thêm vào ~/.gitconfig
[alias]
  st = status
  co = checkout
  br = branch
  ci = commit
  unstage = reset HEAD --
  last = log -1 HEAD
  visual = !gitk
  
  # Advanced aliases
  lg = log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit
  
  undo = reset --soft HEAD~1
  amend = commit --amend --no-edit
  
  # Branch management
  cleanup = "!git branch --merged | grep -v '\\*\\|main\\|develop' | xargs -n 1 git branch -d"

Sử dụng aliases

# Thay vì
git status
git checkout main
git log --oneline -10

# Dùng
git st
git co main
git lg -10

9. Git Configuration

Global Configuration

# User information
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"

# Editor
git config --global core.editor "code --wait"  # VS Code
git config --global core.editor "vim"         # Vim

# Line endings
git config --global core.autocrlf true        # Windows
git config --global core.autocrlf input       # macOS/Linux

# Push behavior
git config --global push.default simple

Repository-specific config

# File: .git/config
[core]
  editor = code --wait
  
[branch "main"]
  mergeoptions = --no-ff
  
[alias]
  deploy = push origin main

10. Security Best Practices

Không commit sensitive data

# File: .gitignore
# Dependencies
node_modules/
npm-debug.log*

# Environment variables
.env
.env.local
.env.production

# Build outputs
dist/
build/

# IDE files
.vscode/
.idea/
*.swp
*.swo

# OS files
.DS_Store
Thumbs.db

# Logs
logs/
*.log

Git Secret Scanning

# Kiểm tra lịch sử commit
git log --all --full-history -- .env
git log --all --full-history -- "*password*"

# Xóa sensitive data khỏi history
git filter-branch --force --index-filter \
'git rm --cached --ignore-unmatch path/to/sensitive/file' \
--prune-empty --tag-name-filter cat -- --all

Kết luận

Git best practices giúp:

  1. Team collaboration hiệu quả hơn
  2. Code quality được maintain
  3. History clean và meaningful
  4. Conflicts được minimize
  5. Deployment trở nên dễ dàng

💡 Pro tip: Hãy bắt đầu với những thay đổi nhỏ - commit messages chuẩn, PR size hợp lý, rồi dần dần implement thêm branching strategy và automation tools.