Skip to content

Git GitHub Operations

GitHub is the world's largest code hosting platform. This chapter details how to interact with GitHub using Git, including repository management, collaborative development, Pull Requests, and more.

GitHub Basic Concepts

What is GitHub?

GitHub is a Git-based code hosting platform that provides:

  • 🏠 Code Hosting: Remote repository storage
  • 👥 Collaborative Development: Team collaboration tools
  • 🔍 Code Review: Pull Request mechanism
  • 🚀 CI/CD: GitHub Actions automation
  • 📊 Project Management: Issues, Projects, Wiki

GitHub vs Git

Git (Local)              GitHub (Remote)
├── Version Control      ├── Code Hosting
├── Branch Management    ├── Collaboration Platform
├── Commit History       ├── Social Features
└── Local Operations     └── Cloud Services

Creating and Configuring GitHub Repositories

Creating a Repository on GitHub

  1. Log in to GitHub
  2. Click the "+" button in the top right corner
  3. Select "New repository"
  4. Fill in repository information:
    • Repository name
    • Description
    • Public/Private
    • Initialize with README
    • Add .gitignore
    • Choose a license

Connecting Local Repository to GitHub

Method 1: Clone an Existing Repository

bash
# Clone a GitHub repository to local
git clone https://github.com/username/repository.git

# Or use SSH (Recommended)
git clone git@github.com:username/repository.git

# Enter repository directory
cd repository

# View remote repository information
git remote -v

Method 2: Push an Existing Local Repository

bash
# Create a repository locally
mkdir my-project
cd my-project
git init

# Add remote repository
git remote add origin https://github.com/username/my-project.git

# Or use SSH
git remote add origin git@github.com:username/my-project.git

# Create initial commit
echo "# My Project" > README.md
git add README.md
git commit -m "Initial commit"

# Push to GitHub
git push -u origin main

SSH Key Configuration

Generating SSH Keys

bash
# Generate a new SSH key
ssh-keygen -t ed25519 -C "your.email@example.com"

# If the system does not support ed25519
ssh-keygen -t rsa -b 4096 -C "your.email@example.com"

# Start SSH agent
eval "$(ssh-agent -s)"

# Add key to SSH agent
ssh-add ~/.ssh/id_ed25519

Adding SSH Key to GitHub

bash
# Copy public key to clipboard
# macOS
pbcopy < ~/.ssh/id_ed25519.pub

# Linux
xclip -sel clip < ~/.ssh/id_ed25519.pub

# Windows (Git Bash)
clip < ~/.ssh/id_ed25519.pub

# Manually view and copy
cat ~/.ssh/id_ed25519.pub

Then on GitHub:

  1. Go to Settings → SSH and GPG keys
  2. Click "New SSH key"
  3. Paste the public key content
  4. Add a descriptive title
  5. Click "Add SSH key"

Testing SSH Connection

bash
# Test SSH connection
ssh -T git@github.com

# Example of successful output:
# Hi username! You've successfully authenticated, but GitHub does not provide shell access.

Basic GitHub Operations

Pushing Code to GitHub

bash
# Push current branch to remote
git push origin main

# Push and set upstream branch
git push -u origin feature-branch

# Push all branches
git push --all origin

# Push tags
git push origin v1.0.0
git push --tags origin

Pulling Updates from GitHub

bash
# Pull and merge remote changes
git pull origin main

# Equivalent to
git fetch origin
git merge origin/main

# Pull using rebase
git pull --rebase origin main

# Fetch all remote branches
git fetch --all

Viewing Remote Repository Information

bash
# View remote repositories
git remote -v

# View remote branches
git branch -r

# View all branches (local and remote)
git branch -a

# View detailed remote repository info
git remote show origin

Fork and Pull Request Workflow

Forking a Repository

  1. Find the project you want to contribute to on GitHub
  2. Click the "Fork" button in the top right corner
  3. Choose to Fork to your account

Cloning a Forked Repository

bash
# Clone your Forked repository
git clone git@github.com:yourusername/original-project.git
cd original-project

# Add original repository as upstream remote
git remote add upstream git@github.com:originalowner/original-project.git

# Verify remote repositories
git remote -v
# origin    git@github.com:yourusername/original-project.git (fetch)
# origin    git@github.com:yourusername/original-project.git (push)
# upstream  git@github.com:originalowner/original-project.git (fetch)
# upstream  git@github.com:originalowner/original-project.git (push)

Keeping Fork Synced

bash
# Fetch updates from upstream repository
git fetch upstream

# Switch to main branch
git checkout main

# Merge upstream changes
git merge upstream/main

# Push updates to your Fork
git push origin main

Creating Feature Branches

bash
# Ensure you are on the latest main branch
git checkout main
git pull upstream main

# Create a new feature branch
git checkout -b feature/add-user-authentication

# Do development work
echo "New feature code" > new_feature.py
git add new_feature.py
git commit -m "feat: Add user authentication"

# Push feature branch to your Fork
git push -u origin feature/add-user-authentication

Creating a Pull Request

  1. Visit your Fork on GitHub
  2. Click the "Compare & pull request" button
  3. Fill in PR information:
    • Title: Concisely describe the changes
    • Description: Explain changes in detail
    • Select the correct base branch and compare branch
  4. Click "Create pull request"

Pull Request Template

markdown
## Description of Changes
Briefly describe the purpose and content of this PR

## Type of Change
- [ ] Bug fix
- [ ] New feature
- [ ] Documentation update
- [ ] Refactoring
- [ ] Performance optimization
- [ ] Other

## Testing
- [ ] Added new tests
- [ ] All existing tests passed
- [ ] Manual testing completed

## Screenshots (if applicable)
Add screenshots to show UI changes

## Related Issues
Closes #123
Related to #456

## Checklist
- [ ] Code follows project coding standards
- [ ] Self-reviewed code changes
- [ ] Added necessary comments
- [ ] Updated related documentation
- [ ] My changes generate no new warnings
- [ ] Added tests to prove fix is effective or feature works

GitHub Issues Management

Creating an Issue

bash
# Create Issue via GitHub CLI
gh issue create --title "Fix login page style issue" --body "Login page displays abnormally on mobile devices"

# Add labels and assignees
gh issue create --title "Add user authentication" --label "enhancement,priority:high" --assignee username

Issue Template

markdown
<!-- .github/ISSUE_TEMPLATE/bug_report.md -->
---
name: Bug Report
about: Create a report to help us improve
title: '[BUG] '
labels: bug
assignees: ''
---

**Describe the Bug**
A clear and concise description of what the bug is.

**Steps to Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error

**Expected Behavior**
A clear and concise description of what you expected to happen.

**Screenshots**
If applicable, add screenshots to help explain your problem.

**Environment Info:**
 - OS: [e.g. iOS]
 - Browser [e.g. chrome, safari]
 - Version [e.g. 22]

**Additional Context**
Add any other context about the problem here.

Linking Issues in Commits

bash
# Reference Issue in commit message
git commit -m "fix: Fix login page style issue

Fixed issue where login form displayed abnormally on mobile devices.

Fixes #123"

# Other keywords
# Closes #123    - Close Issue
# Fixes #123     - Fix Issue  
# Resolves #123  - Resolve Issue
# Related to #123 - Related Issue

GitHub Actions Basics

Creating a Simple CI Workflow

yaml
# .github/workflows/ci.yml
name: CI

on:
  push:
    branches: [ main, develop ]
  pull_request:
    branches: [ main ]

jobs:
  test:
    runs-on: ubuntu-latest
    
    strategy:
      matrix:
        node-version: [14.x, 16.x, 18.x]
    
    steps:
    - name: Checkout code
      uses: actions/checkout@v3
    
    - name: Setup Node.js ${{ matrix.node-version }}
      uses: actions/setup-node@v3
      with:
        node-version: ${{ matrix.node-version }}
        cache: 'npm'
    
    - name: Install dependencies
      run: npm ci
    
    - name: Run linter
      run: npm run lint
    
    - name: Run tests
      run: npm test
    
    - name: Build project
      run: npm run build

Auto-Deployment Workflow

yaml
# .github/workflows/deploy.yml
name: Deploy

on:
  push:
    branches: [ main ]
    tags: [ 'v*' ]

jobs:
  deploy:
    runs-on: ubuntu-latest
    
    steps:
    - name: Checkout code
      uses: actions/checkout@v3
    
    - name: Setup Node.js
      uses: actions/setup-node@v3
      with:
        node-version: '18'
        cache: 'npm'
    
    - name: Install dependencies
      run: npm ci
    
    - name: Build
      run: npm run build
    
    - name: Deploy to GitHub Pages
      uses: peaceiris/actions-gh-pages@v3
      with:
        github_token: ${{ secrets.GITHUB_TOKEN }}
        publish_dir: ./dist

GitHub Advanced Features

GitHub Pages

bash
# Enable GitHub Pages
# 1. Go to repository Settings
# 2. Scroll to Pages section
# 3. Select source branch (usually main or gh-pages)
# 4. Select folder (/ or /docs)

# Create GitHub Pages branch
git checkout --orphan gh-pages
git rm -rf .
echo "<h1>Hello GitHub Pages</h1>" > index.html
git add index.html
git commit -m "Initial GitHub Pages commit"
git push -u origin gh-pages

GitHub Releases

bash
# Create tag
git tag -a v1.0.0 -m "Release version 1.0.0"
git push origin v1.0.0

# Create Release using GitHub CLI
gh release create v1.0.0 --title "Version 1.0.0" --notes "
## New Features
- Added user authentication
- Implemented data export

## Bug Fixes
- Fixed login issues
- Resolved performance issues
"

# Upload files to Release
gh release upload v1.0.0 dist/app.zip

GitHub Discussions

bash
# Enable Discussions
# 1. Go to repository Settings
# 2. Scroll to Features section
# 3. Check Discussions

# Create discussion using GitHub CLI
gh api repos/:owner/:repo/discussions \
  --method POST \
  --field title="Project Roadmap Discussion" \
  --field body="Let's discuss the future direction of the project" \
  --field category_id="DIC_kwDOExample"

Team Collaboration Best Practices

Branch Protection Rules

Configure branch protection in GitHub repository settings:

bash
# Recommended protection rules:
# 1. Require Pull Request reviews
# 2. Require status checks to pass
# 3. Require branches to be up to date
# 4. Restrict push access
# 5. Include administrators

Code Review Workflow

bash
# Reviewer's workflow:
# 1. Checkout PR branch for local testing
gh pr checkout 123

# 2. Run tests
npm test

# 3. Review code changes
gh pr diff 123

# 4. Add review comments
gh pr review 123 --approve
gh pr review 123 --request-changes --body "Please fix security issues"

# 5. Merge PR (if maintainer)
gh pr merge 123 --squash

Project Management

bash
# Use GitHub Projects
# 1. Create project board
# 2. Add columns (To Do, In Progress, Done)
# 3. Add Issues and PRs to project
# 4. Use automation rules

# Use Milestones for version management
# 1. Create milestone (e.g., v1.0.0)
# 2. Assign related Issues to milestone
# 3. Track progress

GitHub CLI Usage

Installing GitHub CLI

bash
# macOS
brew install gh

# Ubuntu/Debian
curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | sudo dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | sudo tee /etc/apt/sources.list.d/github-cli.list > /dev/null
sudo apt update
sudo apt install gh

# Windows
winget install GitHub.cli

Common GitHub CLI Commands

bash
# Authenticate
gh auth login

# Repository operations
gh repo create my-new-repo --public
gh repo clone username/repo
gh repo fork username/repo

# Issue operations
gh issue list
gh issue create --title "Bug report" --body "Description"
gh issue close 123

# Pull Request operations
gh pr list
gh pr create --title "New feature" --body "Description"
gh pr checkout 123
gh pr merge 123

# Release operations
gh release list
gh release create v1.0.0 --notes "Release notes"

# View repository status
gh repo view
gh pr status
gh issue status

Troubleshooting

Common GitHub Issues

bash
# Issue 1: Push rejected
# Cause: Remote repository has new commits
# Solution: Pull first then push
git pull origin main
git push origin main

# Issue 2: SSH connection failed
# Cause: SSH key configuration issue
# Solution: Reconfigure SSH key
ssh-keygen -t ed25519 -C "your.email@example.com"
# Then add to GitHub

# Issue 3: Fork synchronization issue
# Cause: Fork is behind original repository
# Solution: Sync Fork
git fetch upstream
git checkout main
git merge upstream/main
git push origin main

# Issue 4: Large file push failed
# Cause: File exceeds GitHub limit (100MB)
# Solution: Use Git LFS
git lfs track "*.zip"
git add .gitattributes
git add large-file.zip
git commit -m "Add large file with LFS"

GitHub API Limits

bash
# View API limits
gh api rate_limit

# Increase limits by authenticating
gh auth login

# For heavy usage, consider using Personal Access Token

Security Best Practices

Protecting Sensitive Information

bash
# Use .gitignore to exclude sensitive files
echo "*.env" >> .gitignore
echo "config/secrets.json" >> .gitignore
echo "*.key" >> .gitignore

# Use GitHub Secrets to store sensitive information
# Add in repository Settings → Secrets and variables → Actions

# Use Secrets in GitHub Actions
env:
  API_KEY: ${{ secrets.API_KEY }}
  DATABASE_URL: ${{ secrets.DATABASE_URL }}

Access Control

bash
# Repository access control:
# 1. Use teams for permission management
# 2. Regularly review collaborators
# 3. Use branch protection rules
# 4. Enable two-factor authentication
# 5. Monitor repository activity

Summary

Key points of GitHub operations:

Basic Operations

bash
git clone    # Clone repository
git push     # Push changes
git pull     # Pull updates
gh pr create # Create PR
gh issue create # Create Issue

Collaboration Workflow

  • 🍴 Fork Workflow: Suitable for open source contributions
  • 🌿 Branch Workflow: Suitable for team collaboration
  • 📋 Issue Tracking: Manage tasks and Bugs
  • 🔍 Code Review: Ensure code quality

Automation Tools

  • GitHub Actions: CI/CD automation
  • 🚀 GitHub Pages: Static website hosting
  • 📦 GitHub Releases: Version release management
  • 💬 GitHub Discussions: Community discussions

Best Practices

  • ✅ Configure SSH key authentication
  • ✅ Use branch protection rules
  • ✅ Write clear PR descriptions
  • ✅ Sync Fork timely
  • ✅ Protect sensitive information

After mastering GitHub operations, you will be able to:

  • 🤝 Collaborate efficiently with teams
  • 🔄 Contribute to open source projects
  • 🚀 Automate development and deployment processes
  • 📊 Effectively manage project progress

In the next chapter, we will learn the Git glossary.

Content is for learning and research only.