Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Chapter 3: Introduction to Git and GitHub

ASTR 596: Modeling the Universe

San Diego State University

Why Version Control Will Save Your Research

Imagine this: It’s 2 AM, three days before your thesis defense. You accidentally delete 400 lines of working code while trying to “clean up.” Or worse—your laptop dies, taking two years of work with it.

This happens to someone every semester.

Git prevents these disasters. It’s your safety net, collaboration tool, and scientific record all in one. By the end of this guide, you’ll never lose work again.

The Version Control Nightmare (Without Git)

We’ve all been here:

stellar_evolution.py
stellar_evolution_v2.py
stellar_evolution_v2_FIXED.py
stellar_evolution_v2_FIXED_actually_works.py
stellar_evolution_OLD_DO_NOT_DELETE.py
stellar_evolution_FINAL.py
stellar_evolution_FINAL_REAL.py
stellar_evolution_FINAL_FOR_REAL_USE_THIS_ONE.py

With Git, you have ONE file with complete history. Every change is tracked, documented, and reversible.

Understanding Git: The Mental Model

Think of Git as a time machine for your code with three areas:

  1. Working Directory: Your actual files

  2. Staging Area: Changes ready to be saved

  3. Local Repository: Your project’s history (on your computer)

  4. Remote Repository: Cloud backup (GitHub)

Initial Setup (One Time Only)

Step 1: Install Git

macOS
Linux
Windows

Git comes pre-installed. Verify with:

git --version

If not installed, it will prompt you to install Xcode Command Line Tools.

Step 2: Configure Your Identity

# Tell Git who you are (for commit messages)
git config --global user.name "Your Name"
git config --global user.email "your.email@sdsu.edu"

# Set default branch name to 'main' (GitHub's default)
git config --global init.defaultBranch main

# Set default editor (optional but helpful)
git config --global core.editor "code --wait"  # For VS Code

# Verify configuration
git config --list

Step 3: Set Up GitHub Account

  1. Go to https://github.com

  2. Sign up with your SDSU email (critical for Student Pack!)

  3. Verify your email address

  4. Apply for Student Developer Pack: https://education.github.com/pack

    • Free GitHub Pro account

    • GitHub Copilot Pro (free for students - normally $10/month)

    • GitHub Codespaces hours

    • Access to 100+ developer tools

Step 4: Set Up Authentication

Create a Personal Access Token:

  1. Go to GitHub → Click your profile picture → Settings

  2. In the left sidebar, click Developer settings

  3. Under Personal access tokens, click Tokens (classic)

  4. Click Generate new tokenGenerate new token (classic)

  5. Name it “ASTR 596 Course”

  6. Set expiration to after the semester ends

  7. Check these scopes:

    • ✓ repo (all)

    • ✓ workflow (if using GitHub Actions)

  8. Click Generate token

  9. COPY THE TOKEN NOW! You won’t see it again!

Save your token securely:

# Configure Git to remember credentials (so you don't paste token every time)
git config --global credential.helper cache  # Linux/Mac: remembers for 15 min
git config --global credential.helper manager  # Windows: saves permanently

# First time you push, Git asks for:
# Username: your-github-username
# Password: paste-your-token-here (NOT your GitHub password!)

The Essential Five Commands

Master these five commands and you can use Git for this entire course:

The Essential Five

Command - Purpose

git status - What’s changed? (USE THIS CONSTANTLY)

git add . - Stage all changes for commit

git commit -m "message" - Save changes with description

git push - Upload to GitHub

git pull - Download latest changes

GitHub Classroom: Assignment Workflow

Accepting Your First Assignment

  1. Click assignment link (provided on Canvas/Slack)

    • Link looks like: https://classroom.github.com/a/xyz123

  2. Accept the assignment

    • First time: Authorize GitHub Classroom

    • Select your name from the roster

    • Click “Accept this assignment”

  3. Wait for repository creation (~30 seconds)

    • You’ll see “Your assignment has been created”

    • Click the link to your repository

  4. Your repository is created!

    • URL format: github.com/sdsu-astr596/project1-yourusername

    • This is YOUR personal copy

Working on Assignments

# 1. Clone your assignment repository
git clone https://github.com/sdsu-astr596/project1-yourusername.git
cd project1-yourusername

# 2. Work on your code
# Edit files, test, debug...

# 3. Check what's changed
git status

# 4. Stage your changes
git add .

# 5. Commit with descriptive message
git commit -m "Implement stellar mass calculation"

# 6. Push to GitHub (this is your submission!)
git push

Verifying Your Submission

Always verify your submission:

  1. Go to your repository on GitHub.com

  2. Check that your latest changes are visible

  3. Look for the green checkmark on your commit

  4. Check the timestamp (must be before deadline!)

Basic Git Workflow

Let’s practice the complete workflow:

Creating a New Repository

# Create project folder
mkdir my_analysis
cd my_analysis

# Initialize Git repository
git init

# Create a Python file
echo "print('Hello ASTR 596!')" > hello.py

# Create a .gitignore file
cat > .gitignore << EOF
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
env/
venv/
.ipynb_checkpoints/
.pytest_cache/
.vscode/
.idea/
*.swp
*.swo

# Personal
scratch/
notes_to_self.txt
EOF

# Check status
git status

# Add everything
git add .

# First commit
git commit -m "Initial commit with hello.py and .gitignore"

Daily Workflow Cycle

# Start of work session
git pull                     # Get latest changes (if working with others)

# ... do your work ...

git status                    # What changed?
git diff                      # See specific changes
git add .                     # Stage everything
git commit -m "Clear message" # Save snapshot
git push                      # Backup to cloud

Writing Good Commit Messages

Commit Message Format

For longer commits:

git commit
# Opens editor for multi-line message:

# Fix incorrect gravitational constant in N-body simulation
#
# The constant was off by a factor of 4π due to unit conversion
# error. This affected all orbital period calculations.
# 
# Fixes #12

Common Scenarios and Solutions

“I Forgot to Pull First”

git push
# Error: failed to push some refs...

# Solution:
git pull
# If there are conflicts, resolve them (see below)
git push

“I Made a Mistake in My Last Commit”

# Fix the file
# Then amend the commit
git add .
git commit --amend -m "New message"
git push --force  # Only if you already pushed!

“I Need to Undo Changes”

# Discard changes to specific file (not staged)
git checkout -- file.py

# Undo last commit but keep changes
git reset --soft HEAD~1

# Nuclear option: discard ALL local changes
git reset --hard HEAD

Merge Conflicts

When Git can’t automatically merge:

  1. Git marks conflicts in files:

<<<<<<< HEAD
your changes
=======
their changes
>>>>>>> branch-name
  1. Edit file to resolve:

# Keep the version you want (or combine them)
combined final version
  1. Complete the merge:

git add .
git commit -m "Resolve merge conflict"
git push

Quick Reference Card

: :::{list-table} Git Commands Reference :header-rows: 1

Exercise 1: Your First Repository (15 min)

  1. Create a new repository called git-practice

  2. Add a Python file with a simple function

  3. Create a proper .gitignore

  4. Make your first commit

  5. Create a README.md file

  6. Make a second commit

  7. View your history with git log

Exercise 2: GitHub Workflow (20 min)

  1. Create a repository on GitHub.com (New → Repository)

  2. Clone it locally

  3. Add your practice code

  4. Push to GitHub

  5. Verify on GitHub.com

  6. Make changes on GitHub.com (edit README)

  7. Pull changes locally

Exercise 3: Recovery Practice (15 min)

  1. Make some changes to a file

  2. Use git diff to see changes

  3. Discard changes with git checkout

  4. Make new changes and commit them

  5. Undo the commit with git reset --soft HEAD~1

  6. Recommit with a better message

✅ Git Proficiency Checklist

You’re ready for this course when you can:

All checked? You’re ready to use Git for all assignments!

Troubleshooting

Beyond Basics: Useful Features

Viewing specific commits:

git show abc123    # Show specific commit
git diff HEAD~2    # Compare with 2 commits ago

Finding bugs with bisect:

git bisect start
git bisect bad      # Current version is broken
git bisect good v1.0  # v1.0 was working
# Git helps you find when bug was introduced

Aliases for efficiency:

git config --global alias.st status
git config --global alias.cm commit
git config --global alias.br branch
# Now use: git st, git cm, etc.

## Resources

- **Official Git Book** (free): <https://git-scm.com/book>
- **GitHub's Tutorial**: <https://try.github.io>
- **Visual Git Guide**: <https://marklodato.github.io/visual-git-guide/>
- **Oh Shit, Git!?!**: <https://ohshitgit.com> (recovery from mistakes)
- **GitHub Classroom Guide**: <https://classroom.github.com/help>

## Next Steps

1. ✅ Git is configured
2. ✅ GitHub account ready
3. ✅ Can clone, commit, and push
4. → Accept your first assignment on GitHub Classroom!

---

**Remember:** Git seems complex but you only need ~5 commands for this course. Focus on the essential workflow: `status`, `add`, `commit`, `push`, `pull`. Everything else is optional!