Git and GitHub: Complete Practical Guide
Complete practical guide to Git version control and GitHub collaboration including branching strategies, pull requests, CI/CD integration, and advanced Git workflows.
# Git and GitHub: Complete Practical Guide
Introduction
Git is a distributed version control system that tracks changes in source code during software development. GitHub is a cloud-based hosting service for Git repositories that adds collaboration features, CI/CD integration, project management, and community tools. Together, they form the foundation of modern software development workflows.
This tutorial provides a comprehensive practical guide to Git and GitHub, covering everything from basic commands to advanced workflows, branching strategies, and DevOps integration.
Learning Objectives
By the end of this tutorial, you will be able to:
- Initialize and configure Git repositories
- Use Git commands for daily development workflows
- Create and manage branches, merges, and rebases
- Collaborate using pull requests and code reviews
- Implement branching strategies (GitFlow, GitHub Flow, Trunk-Based)
- Integrate GitHub with CI/CD pipelines
- Use advanced Git features (submodules, worktrees, bisect, rebase)
- Manage GitHub repositories, teams, and permissions
Technical Background
Distributed Version Control
flowchart LR
Remote[(Remote Repository<br/>GitHub)] <-->|push/pull| Local[(Local Repository)]
Local -->|commit| Working[Working Directory]
Working -->|add| Staging[Staging Area]
Staging -->|commit| Local
Local1[(Developer A<br/>Clone)] <-->|push/pull| Remote
Local2[(Developer B<br/>Clone)] <-->|push/pull| RemoteGit Object Model
| Object Type | Description | Command | |-------------|-------------|---------| | Blob | File content | `git hash-object` | | Tree | Directory structure | `git write-tree` | | Commit | Snapshot with metadata | `git commit` | | Tag | Named reference to commit | `git tag` | | Branch | Pointer to commit | `git branch` |
GitHub Features
- **Repositories:** Host Git code with issue tracking
- **Pull Requests:** Code review and merge workflow
- **Actions:** CI/CD automation
- **Projects:** Project management (Kanban boards)
- **Packages:** Container and package registry
- **Pages:** Static website hosting
- **Advanced Security:** Code scanning, secret scanning, dependabot
Prerequisites
- Git installed (v2.30 or later)
- GitHub account
- Understanding of command line interface
- Basic knowledge of software development
Hardware and Software Requirements
| Component | Requirement | |-----------|-------------| | Operating System | Linux, macOS, or Windows with Git | | Git Client | v2.30 or later | | GitHub Account | Free or organization account | | SSH Client | For SSH authentication to GitHub | | Text Editor | VS Code, Vim, or any editor | | Web Browser | For GitHub web interface |
Step-by-Step Implementation
Phase 1: Git Installation and Configuration
#### Install Git
# Ubuntu/Debian
sudo apt update && sudo apt install git -y
# macOS
brew install git
# Verify installation
git --version#### Configure Git
# Set user identity
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
# Set default branch name
git config --global init.defaultBranch main
# Enable color output
git config --global color.ui auto
# Set default merge tool
git config --global merge.tool vimdiff
# Configure credential helper (cache for 1 hour)
git config --global credential.helper 'cache --timeout=3600'
# View configuration
git config --list#### SSH Authentication Setup
# Generate SSH key
ssh-keygen -t ed25519 -C "your.email@example.com"
# Start ssh-agent
eval "$(ssh-agent -s)"
# Add key to agent
ssh-add ~/.ssh/id_ed25519
# Copy public key to clipboard
cat ~/.ssh/id_ed25519.pub
# Add public key to GitHub account (Settings > SSH and GPG keys)
# Test connection
ssh -T git@github.comPhase 2: Repository Creation and Basic Operations
#### Create a New Repository
# Create local repository
mkdir my-project
cd my-project
git init
# Create README
echo "# My Project" > README.md
# Stage and commit
git add README.md
git commit -m "Initial commit"
# Add remote
git remote add origin git@github.com:username/my-project.git
# Push to GitHub
git push -u origin main#### Clone an Existing Repository
# Clone repository
git clone git@github.com:username/my-project.git
# Clone specific branch
git clone -b develop git@github.com:username/my-project.git
# Clone into specific directory
git clone git@github.com:username/my-project.git my-project-dir#### Basic Git Workflow
# Check status
git status
# Stage changes
git add .
git add specific-file.js
# Commit changes
git commit -m "Add user authentication feature"
# View commit history
git log --oneline --graph
# Push to remote
git push origin main
# Pull latest changes
git pull origin mainPhase 3: Branching Strategies
#### Create and Switch Branches
# Create new branch
git checkout -b feature/login-page
# Switch to existing branch
git checkout develop
# List all branches
git branch -a
# Delete branch
git branch -d feature/login-page
git branch -D feature/login-page # Force delete#### Merge Strategies
# Fast-forward merge (default)
git checkout main
git merge feature/login-page
# No-fast-forward merge (creates merge commit)
git checkout main
git merge --no-ff feature/login-page
# Squash merge (combines all commits into one)
git checkout main
git merge --squash feature/login-page
git commit -m "Add user authentication feature"#### Rebase vs. Merge
# Rebase feature branch onto main
git checkout feature/login-page
git rebase main
# Interactive rebase (squash, reorder, edit commits)
git rebase -i HEAD~5
# Abort rebase if conflicts
git rebase --abort
# Continue rebase after resolving conflicts
git rebase --continuePhase 4: Branching Strategies
#### GitHub Flow (Recommended for Web Applications)
1. Create branch from `main` 2. Make commits and push branch 3. Open pull request 4. Review and discuss 5. Deploy to staging from PR branch 6. Merge to `main` after approval 7. Deploy to production from `main`
# GitHub Flow example
git checkout -b feature/new-payment-gateway main
# ... make changes ...
git add .
git commit -m "Integrate Stripe payment gateway"
git push origin feature/new-payment-gateway
# Open PR on GitHub, review, merge to main#### GitFlow (Recommended for Release-Based Software)
main -----------o-----------o-----------o (releases)
\ / /
develop -o---o----o---o----o---o------o (integration)
/ \ / \ /
feature/xxx -o---o \ / \ / \
\ / \ / \
hotfix/xxx -o---o \ / \ /# Initialize GitFlow
git flow init
# Start feature
git flow feature start user-authentication
# Finish feature
git flow feature finish user-authentication
# Start release
git flow release start v1.0.0
# Finish release
git flow release finish v1.0.0
# Start hotfix
git flow hotfix start critical-security-patch
# Finish hotfix
git flow hotfix finish critical-security-patch#### Trunk-Based Development
All developers commit directly to `main` (trunk) with short-lived feature branches (hours, not days):
1. Create branch from `main` 2. Work for hours (not days) 3. Merge to `main` via PR 4. Deploy from `main` continuously
Phase 5: Pull Requests and Code Review
#### Create a Pull Request
# Push feature branch
git push origin feature/new-feature
# Open PR via GitHub web interface or CLI
gh pr create --title "Add new feature" \
--body "Description of changes" \
--base main \
--head feature/new-feature#### Code Review Checklist
- [ ] Code follows project style guide
- [ ] Unit tests pass
- [ ] Integration tests pass
- [ ] Security vulnerabilities addressed
- [ ] Documentation updated
- [ ] No secrets or credentials in code
- [ ] Performance impact considered
#### Review and Merge
# Approve PR via GitHub CLI
gh pr review 123 --approve
# Merge PR
gh pr merge 123 --squash
# Delete branch after merge
git branch -d feature/new-feature
git push origin --delete feature/new-featurePhase 6: GitHub Actions CI/CD
#### Basic CI Workflow
# .github/workflows/ci.yml
name: CI
on:
push:
branches: [main, develop]
pull_request:
branches: [develop]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run linting
run: npm run lint
- name: Run tests
run: npm test
- name: Upload coverage
uses: codecov/codecov-action@v4#### CD Workflow with Deployment
# .github/workflows/cd.yml
name: CD
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
environment: production
steps:
- uses: actions/checkout@v4
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789012:role/github-actions-role
aws-region: us-east-1
- name: Deploy to ECS
run: |
aws ecs update-service \
--cluster my-cluster \
--service my-service \
--force-new-deploymentPhase 7: Advanced Git Features
#### Git Submodules
# Add submodule
git submodule add git@github.com:username/shared-library.git lib/shared
# Initialize submodules after clone
git submodule update --init --recursive
# Update submodule to latest
git submodule update --remote#### Git Worktrees
# Create worktree for hotfix
git worktree add ../hotfix-branch hotfix/critical-fix
# List worktrees
git worktree list
# Remove worktree
git worktree remove ../hotfix-branch#### Git Bisect (Find Bug-Introducing Commit)
# Start bisect
git bisect start
git bisect bad # Current commit is bad
git bisect good v1.0.0 # Known good commit
# Git will checkout a commit; test it
git bisect good # or git bisect bad
# Finish bisect
git bisect reset#### Git Reflog (Recover Lost Commits)
# View all operations
git reflog
# Recover lost commit
git checkout -b recovered-branch abc1234#### Git Cherry-Pick
# Apply specific commit to current branch
git cherry-pick abc1234
# Apply range of commits
git cherry-pick abc1234..def5678Phase 8: GitHub Repository Management
#### Repository Settings
- **Branches:** Configure branch protection rules
- **Code owners:** Define CODEOWNERS file for automatic review assignment
- **Secrets:** Store CI/CD secrets in repository settings
- **Environments:** Configure deployment environments with protection rules
#### Branch Protection Rules
# .github/CODEOWNERS
# Syntax: pattern @username @team
/docs/ @docs-team
/src/security/ @security-team
/src/frontend/ @frontend-team#### GitHub Advanced Security
- **Code scanning:** Detect vulnerabilities in code
- **Secret scanning:** Detect accidentally committed credentials
- **Dependabot:** Automatically update dependencies
- **Secret protection:** Prevent pushing secrets to repository
Expected Output
- Git repositories with proper branching strategy
- Pull request workflow with code review
- CI/CD pipelines integrated with GitHub Actions
- Protected branches with required reviews
- Team collaboration on GitHub
- Advanced Git skills for troubleshooting
Verification Procedures
| Check | Method | Expected Result | |-------|--------|-----------------| | Git configuration | `git config --list` | User name and email set | | Clone repository | `git clone <url>` | Repository cloned successfully | | Create branch | `git checkout -b feature` | Branch created and switched | | Push changes | `git push origin <branch>` | Changes pushed to remote | | Pull request | Create PR on GitHub | PR created and reviewable | | CI pipeline | Push to branch | GitHub Actions runs successfully |
Troubleshooting Scenarios
| Issue | Diagnosis | Resolution | |-------|-----------|------------| | Permission denied (publickey) | SSH key not added to GitHub | Add public key to GitHub SSH settings | | Push rejected (non-fast-forward) | Remote has changes you don't have | Pull and rebase/merge before pushing | | Merge conflicts | Conflicting changes in same file | Edit file to resolve conflicts; `git add` and commit | | Detached HEAD | Checked out a commit instead of branch | Create branch from current position: `git checkout -b branch-name` | | Accidental commit | Committed wrong changes | `git reset --soft HEAD~1` to undo commit, keep changes | | Large file in repo | File too large for Git | Use Git LFS: `git lfs track "*.psd"` |
Best Practices
- **Commit often:** Small, focused commits are easier to review and revert
- **Write meaningful commit messages:** Explain why, not just what
- **Use feature branches:** Never commit directly to main (except trunk-based)
- **Keep branches short-lived:** Merge within days, not weeks
- **Use .gitignore:** Exclude build artifacts, dependencies, and secrets
- **Protect main branch:** Require PR reviews and status checks
- **Use tags for releases:** Tag every production release
- **Clean up branches:** Delete merged feature branches
Security Considerations
- **Never commit secrets:** Use environment variables or secret managers
- **Enable 2FA on GitHub:** Protect your account with two-factor authentication
- **Use SSH or HTTPS with tokens:** Avoid password authentication
- **Review third-party actions:** Audit GitHub Actions before using them
- **Enable branch protection:** Require PR reviews for main branch
- **Use CODEOWNERS:** Automatically assign reviewers based on file paths
Conclusion
Git and GitHub are essential tools for modern software development. Git provides distributed version control with powerful branching and merging, while GitHub adds collaboration, CI/CD, and project management. Mastering Git commands, branching strategies, and GitHub workflows enables teams to collaborate effectively, maintain code quality, and deliver software reliably.
References
- Git Documentation: https://git-scm.com/doc
- GitHub Docs: https://docs.github.com/
- Pro Git Book: https://git-scm.com/book/en/v2
- GitHub Flow: https://docs.github.com/en/get-started/quickstart/github-flow
- GitFlow: https://nvie.com/posts/a-successful-git-branching-model/
- GitHub Actions: https://docs.github.com/en/actions