Chapter 3: Introduction to Git and GitHub
ASTR 596: Modeling the Universe
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.pyWith 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:
Working Directory: Your actual files
Staging Area: Changes ready to be saved
Local Repository: Your project’s history (on your computer)
Remote Repository: Cloud backup (GitHub)
Initial Setup (One Time Only)¶
Step 1: Install Git¶
Git comes pre-installed. Verify with:
git --versionIf not installed, it will prompt you to install Xcode Command Line Tools.
# Ubuntu/Debian
sudo apt-get update
sudo apt-get install git
# Fedora
sudo dnf install gitDownload from https://
Important: During installation, select:
“Git from the command line and also from 3rd-party software”
“Use Visual Studio Code as Git’s default editor”
“Override default branch name” → type “main”
“Git Credential Manager” (helps with authentication)
After installation, use Git Bash for all Git commands (not Command Prompt).
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 --listStep 3: Set Up GitHub Account¶
Go to https://github.com
Sign up with your SDSU email (critical for Student Pack!)
Verify your email address
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:
Go to GitHub → Click your profile picture → Settings
In the left sidebar, click Developer settings
Under Personal access tokens, click Tokens (classic)
Click Generate new token → Generate new token (classic)
Name it “ASTR 596 Course”
Set expiration to after the semester ends
Check these scopes:
✓ repo (all)
✓ workflow (if using GitHub Actions)
Click Generate token
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 |
|---|
|
|
|
|
|
GitHub Classroom: Assignment Workflow¶
Accepting Your First Assignment¶
Click assignment link (provided on Canvas/Slack)
Link looks like:
https://classroom.github.com/a/xyz123
Accept the assignment
First time: Authorize GitHub Classroom
Select your name from the roster
Click “Accept this assignment”
Wait for repository creation (~30 seconds)
You’ll see “Your assignment has been created”
Click the link to your repository
Your repository is created!
URL format:
github.com/sdsu-astr596/project1-yourusernameThis 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 pushVerifying Your Submission¶
Always verify your submission:
Go to your repository on GitHub.com
Check that your latest changes are visible
Look for the green checkmark on your commit
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 cloudWriting 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 #12Common 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 HEADMerge Conflicts¶
When Git can’t automatically merge:
Git marks conflicts in files:
<<<<<<< HEAD
your changes
=======
their changes
>>>>>>> branch-nameEdit file to resolve:
# Keep the version you want (or combine them)
combined final versionComplete the merge:
git add .
git commit -m "Resolve merge conflict"
git pushQuick Reference Card¶
: :::{list-table} Git Commands Reference :header-rows: 1
Command - What it does
Basic Workflow -
git init- Create new repository
git clone <url>- Copy repository from GitHub
git status- Show what’s changed
git add <file>- Stage specific file
git add .- Stage all changes
git commit -m "msg"- Save snapshot with message
git push- Upload to GitHub
git pull- Download from GitHub
Viewing History -
git log- Show commit history
git log --oneline- Compact history view
git log --graph- Visual branch history
git diff- Show unstaged changes
git diff --staged- Show staged changes
Undoing Things -
git checkout -- <file>- Discard changes to file
git reset HEAD <file>- Unstage file
git reset --soft HEAD~1- Undo last commit, keep changes
git reset --hard HEAD- Discard ALL local changes
git revert <commit>- Undo specific commit
Branches (Advanced) -
git branch- List branches
git branch <name>- Create branch
git checkout <branch>- Switch branches
git merge <branch>- Merge branch into current
Practice Exercises (optional but recommended)¶
Exercise 1: Your First Repository (15 min)¶
Create a new repository called
git-practiceAdd a Python file with a simple function
Create a proper
.gitignoreMake your first commit
Create a README.md file
Make a second commit
View your history with
git log
Exercise 2: GitHub Workflow (20 min)¶
Create a repository on GitHub.com (New → Repository)
Clone it locally
Add your practice code
Push to GitHub
Verify on GitHub.com
Make changes on GitHub.com (edit README)
Pull changes locally
Exercise 3: Recovery Practice (15 min)¶
Make some changes to a file
Use
git diffto see changesDiscard changes with
git checkoutMake new changes and commit them
Undo the commit with
git reset --soft HEAD~1Recommit with a better message
✅ Git Proficiency Checklist¶
You’re ready for this course when you can:
Clone a repository from GitHub Classroom
Make changes and commit them with clear messages
Push changes to GitHub
Check status and diff before committing
Recover from basic mistakes
Verify your submission on GitHub.com
All checked? You’re ready to use Git for all assignments!
Troubleshooting¶
🔧 Common Issues and Fixes
“Permission denied (publickey)”¶
You’re using SSH but haven’t set up keys
Use HTTPS URLs instead:
https://github.com/...Or set up SSH keys (see GitHub docs)
“Authentication failed”¶
Personal Access Token issue
Create new token following steps above
Make sure to paste TOKEN, not password
“Cannot push to repository”¶
Check you’re in the right directory:
pwdVerify remote URL:
git remote -vMake sure you have commits:
git log
“Large files” error (>100MB)¶
Git won’t accept huge files
Add to
.gitignore:*.fits,*.hdf5, etc.Use
git rm --cached largefileto remove
“Accidentally committed sensitive data”¶
DO NOT push yet!
Remove with:
git reset --hard HEAD~1If already pushed, contact instructor immediately
Beyond Basics: Useful Features¶
🚀 Level Up Your Git Skills
Stashing (temporary storage):
git stash # Save changes temporarily
git stash pop # Restore changesViewing specific commits:
git show abc123 # Show specific commit
git diff HEAD~2 # Compare with 2 commits agoFinding 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 introducedAliases 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!