-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit_github_tutorial.qmd
More file actions
665 lines (450 loc) Β· 17.7 KB
/
Copy pathgit_github_tutorial.qmd
File metadata and controls
665 lines (450 loc) Β· 17.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
---
title: "IEcU Getting Started with Git & GitHub"
author: "Tony Gardella"
date: today
format:
typst:
toc: true
toc-depth: 1
highlight-style: github
---
---
## What is Git? {#what-is-git}
**Git** is a distributed version control system that tracks changes in your code over time. Think of it like a detailed "save history" for your project that allows you to:
- πΈ Take snapshots of your code at any point in time
- π Revert back to previous versions if something breaks
- π€ Collaborate with others without overwriting each other's work
- πΏ Work on new features in isolation without affecting the main codebase
## What is GitHub? {#what-is-github}
**GitHub** is a cloud-based platform that hosts Git repositories online. It adds a layer of collaboration tools on top of Git, including:
- A web interface to view your code and history
- **Pull Requests** β a way to propose and review changes before merging them
- Issue tracking, project boards, and team management
- A place to share and discover open source projects
> π‘ **How are they related?** Git is the software engine that enables version control on your computer/local network, GitHub is cloud/web tool that enables you to extend version control across multiple computers.
---
## β οΈ Security & Best Practices at IEc {#security}
Before using Git and GitHub for any work at IEc, it is essential to understand the security responsibilities that come with it. Git is a powerful tool, but used carelessly it can expose sensitive data, client information, or proprietary code to the public internet.
### Talk to Your Supervisor First
**Before creating any repository or pushing any code to GitHub for a work project, speak with your supervisor.** They will help you determine:
- Whether the project is appropriate for GitHub (public vs. private repositories)
- Whether the client has any restrictions on where code or data can be stored
- Whether IEc has an existing organizational GitHub account or workflow you should follow
- What level of access teammates and collaborators should have
> π΄ **Important:** When in doubt, do not push. It is much easier to add files to a repository later than to scrub sensitive data from one that has already been made public.
### Consult the Client
Many IEc projects involve sensitive client data, proprietary models, or confidential business information. Before using GitHub on a client project:
- **Review the contract or data use agreement** for any restrictions on data storage or sharing
- **Ask the client directly** if there are any concerns about hosting code on a third-party platform like GitHub
- Confirm whether the repository should be **private** and who is permitted to have access
### Consult a Git Expert at IEc
If you are new to Git or unsure about how to structure a repository for a work project, **reach out to a Git-experienced colleague before getting started.** Getting the setup right from the beginning β branching strategy, access controls, what to include or exclude β is much easier than fixing mistakes after the fact.
---
### The `.gitignore` File {#gitignore}
One of the most important files in any Git repository is the **`.gitignore`** file. This file tells Git which files and folders to **intentionally ignore** and never track or commit.
#### Why It Matters
Once a file is committed and pushed to GitHub β especially a public repository β it is very difficult to fully remove. Even if you delete it in a later commit, it may remain in the repository's history. This is especially dangerous for:
- π **API keys and tokens** (e.g., OpenAI, AWS, Google Cloud)
- π **Passwords and credentials**
- π **Environment variable files** (e.g., `.env`)
- π **Sensitive or confidential data files** (e.g., `.csv`, `.xlsx` with client data)
- ποΈ **Large or proprietary datasets**
#### How It Works
Create a file named `.gitignore` in the root of your repository. Each line specifies a pattern for files or folders to ignore.
```bash
# Example .gitignore
# Environment variable files
.env
.env.local
.env.*
# API keys or config files with secrets
secrets.R
config_private.yml
# Data files that should not be shared
data/raw/
*.csv
*.xlsx
# R-specific
.Rhistory
.RData
.Rproj.user/
# Python-specific
__pycache__/
*.pyc
.venv/
# OS-generated files
.DS_Store
Thumbs.db
```
#### Using a `.env` File for Secrets
A common best practice is to store all sensitive values β API keys, database passwords, tokens β in a `.env` file and load them into your scripts at runtime. **Never commit this file.**
Example `.env` file:
```bash
# .env β this file should NEVER be committed
API_KEY=your_secret_api_key_here
DB_PASSWORD=your_database_password
CLIENT_TOKEN=abc123xyz
```
In R, you can load these values using the `dotenv` or `usethis` packages:
```r
# Load environment variables from .env
dotenv::load_dot_env()
api_key <- Sys.getenv("API_KEY")
```
In Python, use the `python-dotenv` package:
```python
from dotenv import load_dotenv
import os
load_dotenv()
api_key = os.getenv("API_KEY")
```
> β
**Best Practice:** Add `.env` to your `.gitignore` before you write a single line of code. Make it the first thing you do when setting up a new repository.
#### GitHub's Secret Scanning
GitHub automatically scans public repositories for known secret patterns (API keys, tokens, etc.) and will alert you if one is detected. However, **do not rely on this as a safety net.** The best protection is to never commit secrets in the first place.
---
### Security Checklist Before Your First Push
Before pushing a repository to GitHub β especially for the first time β run through this checklist:
- [ ] I have spoken with my supervisor about using GitHub for this project
- [ ] I have confirmed there are no client restrictions on code/data storage
- [ ] My repository is set to **Private** if it contains any sensitive or proprietary content
- [ ] I have created a `.gitignore` file and it includes `.env` and any data files
- [ ] I have checked that no API keys, passwords, or tokens are present in any file
- [ ] I have confirmed that no client data files are being tracked by Git (`git status`)
---
## Installation & Setup
### Step 1: Install Git
At IEc, ask CR to install Git.
For educational purposes, on your own non-IEc computer you could go to the [Git download page](https://git-scm.com/download/), choose your operating system, and install it.
### Step 2: Verify Installation
Open your Git terminal and run:
```bash
git --version
```
You should see something like: `git version 2.53.0` or something similair.
### Step 3: Configure Git
Before you start using Git, tell it who you are. This information will be attached to every commit you make. Write these down so that we can use the same name and email for GitHub.
```bash
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
```
Verify your configuration:
```bash
git config --list
```
### Step 4: Create a GitHub Account
Go to [https://github.com](https://github.com), click **Sign Up**, and follow the prompts using the `user.name` and email you configured above. Verify your email address.
### Step 5: Authenticate with GitHub
To push code to GitHub, you need to authenticate. The recommended method is SSH keys.
**Generate an SSH Key** in your Git terminal:
```bash
ssh-keygen -t ed25519 -C "your.email@example.com"
```
Press Enter to accept the default file location and optionally set a passphrase.
**Add the SSH Key to GitHub**
Copy your public key:
```bash
cat ~/.ssh/id_ed25519.pub | clip
```
Go to **GitHub β Settings β SSH and GPG Keys β New SSH Key**, paste your key, and click **Add SSH Key**.
**Test Your Connection:**
```bash
ssh -T git@github.com
```
You should see: `Hi username! You've successfully authenticated...`
---
## Core Concepts
Understanding these key concepts will make Git much easier to work with.
### The Three States of Git
```
Working Directory β Staging Area β Repository
(your files) (git add) (git commit)
```
- **Working Directory** β Where you edit files on your computer
- **Staging Area** β A holding area where you prepare changes before committing
- **Repository** β The permanent record of all your committed snapshots
### Branches
A branch is an independent line of development. Think of it like a parallel universe for your code.
```
main branch: A --- B --- C
\
feature branch: D --- E
```
- The `main` branch is typically the stable, production-ready code
- You create a feature branch to work on something new
- When your work is ready, you merge it back into `main`
> β
**Best Practice:** Never work directly on `main`. Always create a new branch for your changes.
---
## Essential Git Commands
### Starting a Repository
```bash
# Initialize a new Git repo in the current folder
git init
# Clone (download) an existing repo from GitHub
git clone <repository-url>
```
### Checking Status & History
```bash
# See the current state of your working directory and staging area
git status
# View commit history
git log
# Compact, one-line commit history
git log --oneline
```
### Staging & Committing
```bash
# Stage a specific file
git add filename.txt
# Stage all changed files
git add .
# Commit staged changes with a message
git commit -m "Your descriptive commit message"
```
> π‘ **Write good commit messages!** A good message clearly describes what changed and why.
>
> - β Bad: `git commit -m "fix stuff"`
> - β
Good: `git commit -m "Fix login button not responding on mobile"`
### Branching
```bash
# List all local branches
git branch
# Create a new branch
git branch branch-name
# Switch to an existing branch
git checkout branch-name
# Create AND switch to a new branch (shortcut)
git checkout -b branch-name
# Modern syntax for switching branches
git switch branch-name
# Modern syntax for creating and switching
git switch -c branch-name
# Merge a branch into your current branch
git merge branch-name
```
### Working with GitHub (Remote)
```bash
# View remote connections
git remote -v
# Add a remote repository
git remote add origin <repository-url>
# Push your branch to GitHub
git push origin branch-name
# Push and set upstream tracking (first push of a branch)
git push -u origin branch-name
# Pull latest changes from GitHub
git pull origin main
```
---
## GitHub Basics
### Key GitHub Concepts
| Term | Definition |
|---|---|
| Repository (Repo) | Your project folder hosted on GitHub |
| Fork | Your personal copy of someone else's repository |
| Clone | A local copy of a repository on your computer |
| Pull Request (PR) | A request to merge your branch into another branch |
| Merge | Combining changes from one branch into another |
| Issues | A way to track bugs, features, and tasks |
### The GitHub Workflow
This is the standard workflow used by professional teams:
1. Clone the repo β `git clone <url>`
2. Create a branch β `git checkout -b feature/my-feature`
3. Make your changes β *(edit files)*
4. Stage your changes β `git add .`
5. Commit your changes β `git commit -m "Add my feature"`
6. Push to GitHub β `git push -u origin feature/my-feature`
7. Open a Pull Request β *(on GitHub.com)*
8. Review & Merge β *(approved and merged on GitHub)*
---
## π― Follow Along Exercise: Add Your Name & Fun Fact {#exercise}
Now it's time to put everything you've learned into practice! In this exercise, you will:
- Clone a shared repository
- Create your own branch
- Add your name and a fun fact to a file
- Commit your changes
- Push your branch to GitHub
- Open a Pull Request
Let's go!
### Step 1: Clone the Repository
Open your terminal and clone the exercise repository:
```bash
cd ~/Documents
git clone git@github.com:tonygard-indecon/IEcU_github_tutorial.git
```
Navigate into the project folder:
```bash
cd IEcU_github_tutorial/git-workshop
```
Confirm you're on the `main` branch:
```bash
git status
```
### Step 2: Create Your Own Branch
Create a new branch using your name. Use lowercase letters and hyphens β no spaces.
```bash
git checkout -b add/your-name
```
Example:
```bash
git checkout -b add/jane-doe
```
Verify you're on your new branch:
```bash
git branch
```
You should see your branch highlighted with an asterisk (`*`).
### Step 3: Add Your Name & Fun Fact
Open the file called `participants.txt` in your text editor. It looks something like this:
```
# Workshop Participants
# Format: Name | Fun Fact
#
Example Person | I once ate 47 pancakes in one sitting π₯
```
Add your own line at the bottom following the same format:
```
Your Name | Your fun fact here π
```
Example entries:
```
Jane Doe | I have visited 23 countries and counting βοΈ
John Smith | I can solve a Rubik's cube in under 2 minutes π§©
Alex Johnson | I once met my favorite author at a grocery store π
```
Save the file when you're done.
### Step 4: Stage Your Changes
Check what changed:
```bash
git status
```
You should see `participants.txt` listed as modified. Stage the file:
```bash
git add participants.txt
```
Confirm it's staged:
```bash
git status
```
The file should now appear in green under "Changes to be committed".
### Step 5: Commit Your Changes
Write a clear, descriptive commit message:
```bash
git commit -m "Add [Your Name] to participants list"
```
Example:
```bash
git commit -m "Add Jane Doe to participants list"
```
View your commit in the log:
```bash
git log --oneline
```
### Step 6: Push Your Branch to GitHub
Push your branch up to the remote repository:
```bash
git push -u origin add/your-name
```
Example:
```bash
git push -u origin add/jane-doe
```
You should see output similar to:
```
Enumerating objects: 5, done.
Counting objects: 100% (5/5), done.
...
To github.com:<org>/git-workshop.git
* [new branch] add/jane-doe -> add/jane-doe
Branch 'add/jane-doe' set up to track remote branch 'add/jane-doe' from 'origin'.
```
### Step 7: Open a Pull Request on GitHub
1. Go to the repository on GitHub.com
2. You should see a yellow banner saying "Your branch had recent pushes" β click **"Compare & pull request"**
3. If you don't see the banner, click the **"Pull Requests"** tab β **"New Pull Request"**
4. Fill out the Pull Request form:
- **Title:** `Add [Your Name] to participants list`
- **Description:** Write a brief description of what you did (e.g., *"Added my name and fun fact to the participants file as part of the Git workshop exercise."*)
5. Click **"Create Pull Request"** β
### Step 8: Review Someone Else's PR (Bonus!)
While you wait for your PR to be reviewed:
1. Go to the **Pull Requests** tab in the repository
2. Open a classmate's Pull Request
3. Click **"Files changed"** to see what they added
4. Leave a comment or an emoji reaction π
5. If everything looks good, you can **Approve** their PR
---
### π You Did It!
Once your PR is approved and merged, your name will be part of the project's `main` branch forever! Here's a summary of what you accomplished:
| Step | Command Used |
|---|---|
| Clone the repo | `git clone` |
| Create a branch | `git checkout -b` |
| Check your changes | `git status` |
| Stage your changes | `git add` |
| Save your changes | `git commit -m` |
| Upload to GitHub | `git push` |
| Propose your changes | Pull Request on GitHub |
---
## Quick Reference Cheat Sheet
```bash
# ---- SETUP ----
git config --global user.name "Name"
git config --global user.email "email"
# ---- STARTING ----
git init # New local repo
git clone <url> # Copy remote repo
# ---- DAILY WORKFLOW ----
git status # What's changed?
git add . # Stage everything
git add <file> # Stage one file
git commit -m "message" # Save a snapshot
git push origin <branch> # Upload to GitHub
git pull origin main # Download latest changes
# ---- BRANCHING ----
git branch # List branches
git checkout -b <name> # Create + switch branch
git switch <name> # Switch branch
git merge <branch> # Merge into current branch
# ---- HISTORY ----
git log --oneline # Compact history
git diff # See unstaged changes
```
---
## Useful Software Tools for Git & GitHub
GUI Clients (Visual Git Interfaces)
GitKraken - Feature-rich, cross-platform GUI
Sourcetree - Free GUI by Atlassian
GitHub Desktop - Official GitHub client, beginner-friendly
Tower - Professional Git client (paid)
Fork - Fast and friendly Git client
Code Editors / IDEs with Git Integration
VS Code - Built-in Git support + GitLens extension
JetBrains IDEs (IntelliJ, PyCharm) - Excellent built-in Git tools
Sublime Merge - Git client by Sublime Text team
Productivity Extensions & Plugins
GitLens (VS Code) - Enhanced Git visualization
Git Graph (VS Code) - Visual branch/commit history
GitHub Copilot - AI code assistance
Code Review & Collaboration
Reviewable - Advanced code review tool
Codecov - Code coverage reporting
SonarQube - Code quality analysis
CI/CD Integration Tools
GitHub Actions - Built-in automation
Jenkins - Open-source automation server
CircleCI - Cloud-based CI/CD
Travis CI - Continuous integration service
Terminal Enhancements
Oh My Zsh - Git aliases and plugins
Git Bash - Unix-style terminal for Windows
Lazygit - Terminal UI for Git commands
diff-so-fancy - Improved diff output
Repository Management
BFG Repo Cleaner - Remove sensitive data from history
Git LFS - Large file storage
Husky - Git hooks made easy
Project Management (GitHub Adjacent)
ZenHub - Agile project management in GitHub
Jira - Issue tracking with GitHub integration
Linear - Modern issue tracking
Happy coding! Remember: every expert was once a beginner. The more you use Git, the more natural it becomes. π±