Skip to content

Latest commit

 

History

History
1147 lines (886 loc) · 19.6 KB

File metadata and controls

1147 lines (886 loc) · 19.6 KB

Comprehensive GitHub and Git Command Guide

This comprehensive guide covers essential and advanced commands for managing local and remote repositories, branches, pull requests, and interactions with GitHub using both Git and GitHub CLI tools. Master these commands to become a GitHub power user.

📋 Table of Contents


1. Repository Setup & Cloning

Basic Cloning

Clone repository with SSH:

git clone git@github.com:owner/repo.git

Clone with HTTPS:

git clone https://github.com/owner/repo.git

Clone specific branch:

git clone -b branch-name https://github.com/owner/repo.git

Shallow clone (faster, less history):

git clone --depth 1 https://github.com/owner/repo.git

Forking and Cloning with GitHub CLI

Fork and clone in one command:

gh repo fork owner/repo --clone=true

Fork without cloning:

gh repo fork owner/repo

Clone existing fork:

git clone https://github.com/YOUR_USERNAME/repo.git

Setting Up Remotes

Add upstream remote:

git remote add upstream https://github.com/ORIGINAL_OWNER/repo.git

Rename origin to your fork:

git remote set-url origin https://github.com/YOUR_USERNAME/repo.git

Verify remote configuration:

git remote -v

2. Branch Management

Viewing Branches

List local branches:

git branch

List remote branches:

git branch -r

List all branches:

git branch -a

Show current branch:

git branch --show-current

Creating and Switching Branches

Create and switch to new branch:

git checkout -b feature/new-feature
# or
git switch -c feature/new-feature

Switch to existing branch:

git checkout existing-branch
# or
git switch existing-branch

Create branch from specific commit:

git checkout -b new-branch abc123

Branch Operations

Rename current branch:

git branch -m new-branch-name

Delete local branch:

git branch -d branch-name

Force delete local branch:

git branch -D branch-name

Delete remote branch:

git push origin --delete branch-name

Track remote branch:

git checkout --track origin/remote-branch

3. Fetching, Pulling, and Syncing

Fetch Operations

Fetch all branches from origin:

git fetch origin

Fetch from upstream:

git fetch upstream

Fetch specific branch:

git fetch origin branch-name

Pull Operations

Pull with merge (default):

git pull origin main

Pull with rebase (linear history):

git pull --rebase origin main

Pull specific branch:

git pull origin feature-branch

Syncing Forks

Sync fork with upstream:

git checkout main
git fetch upstream
git rebase upstream/main
git push origin main

Alternative merge approach:

git checkout main
git fetch upstream
git merge upstream/main
git push origin main

4. Committing Changes

Staging Changes

Stage specific file:

git add filename.txt

Stage all changes:

git add .

Stage interactively:

git add -p

Unstage file:

git reset filename.txt

Committing

Commit with message:

git commit -m "feat: add new feature"

Commit all staged changes:

git commit -a -m "fix: resolve bug"

Amend last commit:

git commit --amend

Amend without changing message:

git commit --amend --no-edit

Advanced Commit Techniques

Empty commit:

git commit --allow-empty -m "trigger: ci build"

Commit with specific author:

git commit --author="Name <email@example.com>" -m "message"

5. Pushing Changes

Basic Push

Push current branch:

git push origin current-branch

Push with upstream tracking:

git push -u origin feature-branch

Push all branches:

git push --all origin

Force Push (Use Carefully)

Safe force push:

git push --force-with-lease origin branch

Dangerous force push:

git push --force origin branch

Push Options

Push tags:

git push --tags

Push to different remote:

git push upstream main

Dry run push:

git push --dry-run origin branch

6. Working with Pull Requests Using GitHub CLI

PR Status and Information

Check PR status:

gh pr status

List PRs:

gh pr list

View PR details:

gh pr view 123

View PR in browser:

gh pr view --web 123

Creating PRs

Create PR interactively:

gh pr create

Create PR with options:

gh pr create --title "feat: add authentication" \
             --body "Implements user login..." \
             --base main \
             --head feature/auth

Create draft PR:

gh pr create --draft

PR Operations

Checkout PR locally:

gh pr checkout 123

Update PR branch:

gh pr update-branch 123

Merge PR:

gh pr merge 123

Merge with options:

gh pr merge 123 --squash --delete-branch

PR Reviews

List PR reviews:

gh pr review --list 123

Approve PR:

gh pr review 123 --approve

Request changes:

gh pr review 123 --request-changes --body "Please fix..."

7. Issues and Labels

Issue Management

List issues:

gh issue list

List issues with filters:

gh issue list --label "bug" --state open

View issue:

gh issue view 123

Create issue:

gh issue create --title "Bug: app crashes" --body "Steps to reproduce..."

Issue Operations

Close issue:

gh issue close 123

Reopen issue:

gh issue reopen 123

Edit issue:

gh issue edit 123 --title "New title"

Labels

List labels:

gh label list

Create label:

gh label create "priority: high" --color FF0000

Apply label to issue:

gh issue edit 123 --add-label "bug"

Remove label:

gh issue edit 123 --remove-label "bug"

8. Working with GitHub Actions and Checks

Workflow Management

List workflows:

gh workflow list

View workflow:

gh workflow view "CI"

Run workflow:

gh workflow run "CI"

Run Management

List runs:

gh run list

View run details:

gh run view 12345

Rerun failed run:

gh run rerun 12345

Download run artifacts:

gh run download 12345

PR Checks

View PR checks:

gh pr checks 123

Wait for checks:

gh pr checks 123 --watch

9. Custom Aliases (GitHub CLI)

Creating Aliases

Add simple alias:

gh alias set prc 'pr create --web'

Add complex alias:

gh alias set review 'pr checkout $1 && pr diff'

List aliases:

gh alias list

Delete alias:

gh alias delete prc

Useful Aliases

# Quick PR creation
gh alias set prnew 'pr create --fill'

# Status overview
gh alias set status 'repo view && echo "---" && pr status && echo "---" && issue list --limit 5'

# Branch cleanup
gh alias set clean-branches 'pr list --state merged --json number,headRefName --jq ".[].headRefName" | xargs -I {} git branch -D {}'

10. Advanced Git Techniques

Interactive Rebase

Rebase last 3 commits:

git rebase -i HEAD~3

Rebase onto different branch:

git rebase --onto main feature-branch

Cherry Picking

Cherry pick commit:

git cherry-pick abc123

Cherry pick range:

git cherry-pick abc123..def456

Stashing

Stash changes:

git stash push -m "work in progress"

Apply stash:

git stash pop

List stashes:

git stash list

Reflog

View reflog:

git reflog

Recover lost commit:

git checkout -b recovery abc123

11. GitHub CLI Extensions

Installing Extensions

Install extension:

gh extension install owner/gh-extension-name

List installed extensions:

gh extension list

Upgrade extensions:

gh extension upgrade --all

Popular Extensions

  • gh pr-cleanup - Clean up merged branches
  • gh notify - Notifications
  • gh dash - Dashboard
  • gh copilot - GitHub Copilot integration

12. Troubleshooting

Common Git Issues

Resolve merge conflicts:

git status
# Edit conflicted files
git add resolved-file
git commit

Undo last commit:

git reset --soft HEAD~1  # keep changes
git reset --hard HEAD~1  # discard changes

Recover deleted branch:

git reflog
git checkout -b recovered-branch abc123

GitHub CLI Issues

Authentication problems:

gh auth login
gh auth refresh

Permission denied:

gh auth status
# Check token scopes

Rate limiting:

gh api -H "Accept: application/vnd.github.v3+json" /rate_limit

13. Git Hooks and Automation

Local Git Hooks

Pre-commit hooks:

#!/bin/sh
# .git/hooks/pre-commit

# Run linting
npm run lint

# Run tests
npm test

# Check for secrets
git secrets --pre_commit_hook

Pre-push hooks:

#!/bin/sh
# .git/hooks/pre-push

# Run full test suite
npm run test:full

# Check code coverage
npm run coverage -- --check-coverage

Husky for Git Hooks

Setup Husky:

npm install husky --save-dev
npx husky install

# Add hooks
npx husky add .husky/pre-commit "npm run lint"
npx husky add .husky/pre-push "npm test"

Advanced Husky configuration:

// package.json
{
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged",
      "commit-msg": "commitlint -E HUSKY_GIT_PARAMS",
      "pre-push": "npm run test"
    }
  },
  "lint-staged": {
    "*.{js,ts}": ["eslint --fix", "prettier --write"],
    "*.{md,mdx}": ["prettier --write"]
  }
}

Server-Side Hooks

GitHub webhooks integration:

# .github/workflows/webhook-handler.yml
name: Handle Webhooks

on:
  repository_dispatch:
    types: [custom-event]

jobs:
  handle:
    runs-on: ubuntu-latest
    steps:
      - name: Process webhook
        run: |
          echo "Event: ${{ github.event.action }}"
          echo "Sender: ${{ github.event.sender.login }}"

14. Advanced Rebasing Techniques

Interactive Rebase

Rebase with editing:

git rebase -i HEAD~5
# Commands:
# pick - use commit
# reword - edit message
# edit - amend commit
# squash - merge with previous
# fixup - merge without message
# drop - remove commit

Rebase onto different branch:

git rebase --onto main feature-branch bugfix-branch

Rebase Conflict Resolution

During rebase conflicts:

# Resolve conflicts in files
git add resolved-file

# Continue rebase
git rebase --continue

# Skip conflicted commit
git rebase --skip

# Abort rebase
git rebase --abort

Rebase Strategies

Linear history maintenance:

# Before merging feature branch
git checkout feature-branch
git rebase main
git checkout main
git merge feature-branch  # Fast-forward merge

Squashing for clean history:

git rebase -i --autosquash main
# Automatically groups fixup! and squash! commits

15. Git Worktrees for Advanced Workflows

Worktree Basics

Create worktree:

git worktree add ../feature-branch feature-branch
cd ../feature-branch

List worktrees:

git worktree list

Remove worktree:

git worktree remove feature-branch

Advanced Worktree Usage

Worktree for hotfixes:

# Create worktree for hotfix
git worktree add -b hotfix/urgent-fix ../hotfix urgent-fix

# Work on hotfix
cd ../hotfix
# Make changes
git commit -m "fix: urgent security patch"

# Push and create PR
git push -u origin hotfix/urgent-fix
gh pr create --fill

# Remove worktree after merge
git worktree remove ../hotfix

Worktree for experiments:

# Create experimental worktree
git worktree add ../experiment experiment

# Experiment freely
cd ../experiment
git reset --hard HEAD~10  # Go back in history
# Test different approaches

# Discard experiment
cd ..
rm -rf experiment
git worktree prune

16. Git Configuration and Aliases

Global Git Configuration

Essential config:

git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
git config --global core.editor "code --wait"
git config --global init.defaultBranch main
git config --global pull.rebase true

Advanced config:

# Enable rerere (reuse recorded resolution)
git config --global rerere.enabled true

# Better diff output
git config --global diff.algorithm histogram

# Colored output
git config --global color.ui auto

# Push only current branch
git config --global push.default simple

Powerful Git Aliases

Workflow aliases:

git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
git config --global alias.unstage 'reset HEAD --'
git config --global alias.last 'log -1 HEAD'
git config --global alias.visual '!gitk'

Advanced aliases:

# Show contributors
git config --global alias.contributors 'shortlog -sn --no-merges'

# Find commits by message
git config --global alias.find 'log --all --grep'

# Show file history
git config --global alias.filelog 'log -p --follow --'

# Clean merged branches
git config --global alias.clean-branches '!git branch --merged | grep -v "\*" | xargs -n 1 git branch -d'

Conditional Configuration

Per-repository config:

# .git/config
[user]
    name = Work Name
    email = work@example.com
[core]
    sshCommand = ssh -i ~/.ssh/work_key

Include files:

# ~/.gitconfig
[include]
    path = ~/.gitconfig-work
[includeIf "gitdir:~/personal/"]
    path = ~/.gitconfig-personal

17. Git and GitHub Integration Patterns

GitHub Apps Integration

Custom GitHub Apps:

// GitHub App webhook handler
app.on('pull_request.opened', async (context) => {
  const pr = context.payload.pull_request;

  // Auto-label PR based on branch
  if (pr.head.ref.startsWith('feature/')) {
    await context.github.issues.addLabels({
      owner: pr.base.repo.owner.login,
      repo: pr.base.repo.name,
      issue_number: pr.number,
      labels: ['enhancement']
    });
  }
});

GitHub API Integration

Automated repository management:

# Create issue with GitHub CLI
gh issue create \
  --title "Automated: Dependency Update" \
  --body "Dependencies have been updated automatically." \
  --label "dependencies,automated"

# Bulk operations
gh issue list --label "stale" --json number --jq '.[].number' | \
  xargs -I {} gh issue edit {} --add-label "closing-soon"

CI/CD Integration

GitHub Actions with Git operations:

jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0  # Full history for tags

      - name: Create release branch
        run: |
          git checkout -b release/v${{ github.event.inputs.version }}
          git push -u origin release/v${{ github.event.inputs.version }}

      - name: Create tag
        run: |
          git tag -a v${{ github.event.inputs.version }} -m "Release v${{ github.event.inputs.version }}"
          git push origin v${{ github.event.inputs.version }}

18. Performance and Optimization

Git Performance Tips

Shallow clones for CI:

git clone --depth 1 https://github.com/user/repo.git

Partial clones:

git clone --filter=blob:none https://github.com/user/repo.git
# Download blobs on demand

GC optimization:

git config --global gc.auto 0  # Disable auto GC
git gc --aggressive --prune=now  # Manual optimization

Large Repository Handling

Git LFS for large files:

git lfs install
git lfs track "*.psd" "*.mov"
git add .gitattributes

Sparse checkout:

git sparse-checkout init --cone
git sparse-checkout set docs/

Network Optimization

SSH multiplexing:

# ~/.ssh/config
Host github.com
  ControlMaster auto
  ControlPath ~/.ssh/master-%r@%h:%p
  ControlPersist 10m

Parallel fetching:

git config --global fetch.parallel 0  # Use all CPUs

19. Security Best Practices

Git Security

Sign commits:

git config --global commit.gpgsign true
git config --global user.signingkey YOUR_KEY_ID

Verify signatures:

git log --show-signature

GitHub Security

Branch protection:

  • Require PR reviews
  • Require status checks
  • Include administrators
  • Restrict pushes

Token management:

# Use fine-grained tokens
gh auth login --scopes "repo,workflow"

# Rotate tokens regularly
gh auth refresh

Secret Management

GitHub secrets:

# Use in workflows
- name: Deploy
  run: |
    echo "API_KEY=${{ secrets.API_KEY }}" >> .env

Environment-specific secrets:

jobs:
  deploy:
    environment: production
    steps:
      - run: echo "Using ${{ secrets.PROD_API_KEY }}"

20. Future of Git and GitHub

Emerging Features

Git improvements:

  • Sparse index for large repos
  • Multi-pack index for performance
  • Commit graphs for faster operations
  • Partial clones evolution

GitHub innovations:

  • GitHub Copilot integration
  • Codespaces for cloud development
  • Discussions for community engagement
  • Projects for project management

Advanced Collaboration

GitHub Teams and Organizations:

  • Nested teams for complex hierarchies
  • Team sync with identity providers
  • Organization-wide insights
  • Enterprise features

Integration ecosystem:

  • Marketplace apps expansion
  • API evolution with GraphQL
  • Webhook enhancements
  • Real-time collaboration

Summary

Mastering Git and GitHub CLI commands transforms you from a basic user to a power contributor. Combine Git's version control with GitHub's collaboration features to streamline your development workflow. Regular practice and exploration of advanced features will make these commands second nature.

Additional Resources