📘 GIT AND GITHUB BASICS
- 📘 GIT AND GITHUB BASICS
- 🎯 General Objectives
- 🧑🏫 Lesson 1: Introduction to Git and GitHub
- 🧑🏫 Lesson 2: Basic Git Commands
- 🧑🏫 Lesson 3: Working with GitHub
- 🧑🏫 Lesson 4: Branching and Merging
- 🧑🏫 Lesson 5: Teamwork and Conflict Resolution
- 🧑🏫 Lesson 6: Git Flow and Development Workflow
- 🧑🏫 Lesson 7: Advanced Git Techniques
- 🧪 FINAL PROJECT: Create and Manage Code for Future Course Sections Using Git and GitHub
🎯 General Objectives
- Get familiar with Git and GitHub, basic commands for source code management.
- Know how to create and manage repositories on GitHub.
- Practice operations like commit, push, pull, branch and merge.
- Understand how to work in teams with Git and GitHub, resolve source code conflicts.
- Master software development workflow with Git Flow.
- Practice source code management techniques like tag, rebase and cherry-pick.
🧑🏫 Lesson 1: Introduction to Git and GitHub
What is Git?
Git is a Distributed Version Control System (DVCS) developed by Linus Torvalds in 2005. Git allows tracking source code changes, coordinating teamwork, and easily reverting to previous versions when needed.
Benefits of Git
- Work offline: Can commit and view history even without network connection
- Distributed: Everyone has a complete copy of the repository
- Fast: Operations on local repository are faster than centralized systems
- Powerful branching: Easy to create, merge and manage branches
- Ensure integrity: Uses hash codes to ensure data integrity
What is GitHub?
GitHub is a cloud-based Git hosting service, providing a web interface to manage Git repositories, along with many additional features such as:
- Issue tracking
- Pull requests
- Code review
- Project management
- CI/CD integration
- Wiki and documentation
Basic Concepts in Git
Repository (Repo): Storage for source code and change history
- Local repository: Repo on personal computer
- Remote repository: Repo on server (like GitHub)
Commit: Save current state of source code with a unique identifier (hash)
Branch: Independent development branch of source code
- master/main: Main branch, contains stable code
- feature branches: Branches for developing new features
Merge: Combine changes from one branch to another
Clone: Create a copy of repository from remote to local
Pull: Fetch changes from remote repository to local repository
Push: Push changes from local repository to remote repository
Working Directory: Working directory containing project files
Staging Area (Index): Intermediate area where changes are prepared before commit
Git Workflow Diagram
+------------+ git add +-------------+ git commit +----------------+
| Working | -------------> | Staging | --------------> | Local |
| Directory | | Area | | Repository |
+------------+ +-------------+ +----------------+
^ |
| |
| git checkout git push|
| |
| V
| git pull +----------------+
+-----------------------------------------------| Remote |
| Repository |
+----------------+🧑🏫 Lesson 2: Basic Git Commands
Initialize Repository
# Create new repository
git init
# Clone existing repository
git clone https://github.com/username/repository.gitView Status and History
# View current status
git status
# View commit history
git log
# View compact history on one line
git log --oneline
# View detailed changes
git diffManage Changes
# Add file to staging area
git add filename.txt
# Add all changed files
git add .
# Commit changes in staging area
git commit -m "Description of changes"
# Add and commit simultaneously (only for tracked files)
git commit -am "Description of changes"Undo Changes
# Discard changes in working directory (not yet added)
git checkout -- filename.txt
# Unstage changes already added to staging area
git reset HEAD filename.txt
# Undo last commit (keep changes in working directory)
git reset --soft HEAD~1
# Completely undo last commit (delete changes too)
git reset --hard HEAD~1Working with Remote Repository
# View list of remotes
git remote -v
# Add remote
git remote add origin https://github.com/username/repository.git
# Fetch changes from remote (without merge)
git fetch origin
# Fetch changes and merge into current branch
git pull origin main
# Push changes to remote
git push origin main.gitignore File
The .gitignore file lists files and directories that Git will ignore when tracking changes:
# Example .gitignore file
node_modules/
.env
*.log
.DS_StoreCommon .gitignore templates by language available at: github.com/github/gitignore
🧑🏫 Lesson 3: Working with GitHub
Create Account and Repository
- Register at github.com
- Create new repository:
- Click "New" from GitHub homepage
- Fill in name, description, choose access rights (public/private)
- Choose to initialize with README if needed
- Click "Create repository"
Link Local Repository with GitHub
# With new repository created on GitHub
git remote add origin https://github.com/username/repository.git
git branch -M main
git push -u origin main
# With existing repository on local
cd existing-project
git init
git add .
git commit -m "Initial commit"
git remote add origin https://github.com/username/repository.git
git push -u origin mainUsing SSH with GitHub
Generate SSH key:
bashssh-keygen -t ed25519 -C "[email protected]"Add SSH key to SSH agent:
basheval "$(ssh-agent -s)" ssh-add ~/.ssh/id_ed25519Add SSH key to GitHub account:
- Copy key:
cat ~/.ssh/id_ed25519.pub - Add to GitHub: Settings > SSH and GPG keys > New SSH key
- Copy key:
Test connection:
bashssh -T [email protected]
GitHub Pages
GitHub Pages is GitHub's free static hosting service:
- Create repository named
username.github.io - Clone repository to local
- Add HTML, CSS, JavaScript code
- Push to GitHub
- Access
https://username.github.io
GitHub Actions
GitHub Actions is GitHub's integrated CI/CD service:
Create file
.github/workflows/main.yml:yamlname: CI on: push: branches: [main] pull_request: branches: [main] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Run tests run: | npm install npm testPush to GitHub
View results in "Actions" tab
🧑🏫 Lesson 4: Branching and Merging
Manage Branches
# List all branches
git branch
# Create new branch
git branch feature-login
# Switch to another branch
git checkout feature-login
# Create and switch to new branch simultaneously
git checkout -b feature-register
# Delete branch
git branch -d feature-login
# Delete branch pushed to remote
git push origin --delete feature-loginMerge Branches
# Switch to destination branch (usually main)
git checkout main
# Merge another branch into current branch
git merge feature-login
# Merge and create new merge commit (no fast-forward)
git merge --no-ff feature-loginRebasing
Rebase is a way to reorganize commits for linear history:
# In feature branch
git rebase main
# If conflicts occur, resolve and continue
git rebase --continue
# Or abort rebase
git rebase --abortFast-forward vs. No-fast-forward
# Fast-forward merge (default when possible)
A---B---C (main)
\
D---E (feature)
After merge:
A---B---C---D---E (main, feature)
# No-fast-forward merge (git merge --no-ff)
A---B---C (main)
\
D---E (feature)
After merge:
A---B---C---F (main)
\ /
D---E (feature)Stashing
Stash temporarily saves uncommitted changes:
# Save current changes temporarily
git stash
# View stash list
git stash list
# Apply latest stash and keep in stash list
git stash apply
# Apply latest stash and remove from stash list
git stash pop
# Delete stash
git stash drop stash@{0}
# Delete all stashes
git stash clear🧑🏫 Lesson 5: Teamwork and Conflict Resolution
Pull Request (PR)
Pull Request is a way to propose changes in GitHub:
- Fork repository (if no direct access)
- Create new branch for feature
- Commit changes
- Push branch to GitHub
- Create Pull Request from this branch to main
- Wait for review and approval
- Merge PR
Code Review
- View PR in GitHub
- View changes (Files changed)
- Add comments to individual code lines if needed
- Approve or Request changes
- Submit review
Resolving Conflicts
Conflicts occur when the same part of a file is changed:
# When merge or pull causes conflict
Auto-merging file.txt
CONFLICT (content): Merge conflict in file.txt
Automatic merge failed; fix conflicts and then commit the result.Resolution steps:
Open conflicted file, find marked sections:
text<<<<<<< HEAD Changes from current branch ======= Changes from branch being merged >>>>>>> feature-branchEdit to keep desired changes (remove conflict markers)
Mark as resolved:
bashgit add file.txtComplete merge:
bashgit commit -m "Resolved merge conflict in file.txt"
Teamwork Best Practices
- Pull frequently: Get latest changes before starting work
- Commit small and often: Easy to review and debug
- Clear commit descriptions: Help understand purpose of changes
- One branch per feature: Avoid mixing multiple features in one branch
- Code review: Always have someone else review code before merge
- Test before push: Ensure code works correctly
- Update documentation: Ensure documentation is always up-to-date
🧑🏫 Lesson 6: Git Flow and Development Workflow
What is Git Flow?
Git Flow is a branching model that helps manage software projects. It defines specific branch types and how they interact with each other.
Branch Types in Git Flow
+----------------------+
| |
| Production |
| (master/main) |
| |
+------+------+--------+
| ^
hotfixes | | releases
| |
+-----------+ | | +-----------+
| | | | | |
| hotfix +----v------+----+ release |
| branches | ^ | branches |
| | | | |
+-----------+ | +-----------+
|
|
+-------+--------+
| |
| Development |
| (develop) |
| |
+-------+--------+
^
|
+-------+--------+
| |
| Feature |
| branches |
| |
+----------------+- master/main: Main branch, contains production code
- develop: Development branch, integrates new features
- feature/: Branches for specific features
- release/: Branch preparing for new version
- hotfix/: Branch for urgent fixes on production
Git Flow Workflow
Feature development:
bash# Create feature branch from develop git checkout -b feature/login develop # Work, commit... # When complete, merge back to develop git checkout develop git merge --no-ff feature/login git push origin develop # Delete feature branch (optional) git branch -d feature/loginRelease preparation:
bash# Create release branch from develop git checkout -b release/1.0.0 develop # Fix minor bugs, update version, etc. # Merge to master and develop git checkout master git merge --no-ff release/1.0.0 git tag -a v1.0.0 -m "Version 1.0.0" git checkout develop git merge --no-ff release/1.0.0 # Delete release branch git branch -d release/1.0.0Hotfix:
bash# Create hotfix branch from master git checkout -b hotfix/1.0.1 master # Fix bug # Merge to master and develop git checkout master git merge --no-ff hotfix/1.0.1 git tag -a v1.0.1 -m "Version 1.0.1" git checkout develop git merge --no-ff hotfix/1.0.1 # Delete hotfix branch git branch -d hotfix/1.0.1
Extensions and Variants
- GitHub Flow: Simplified with only main and feature branches
- GitLab Flow: Add environment branches (production, staging)
- Trunk-based Development: Develop mainly on main branch, short feature branches
🧑🏫 Lesson 7: Advanced Git Techniques
Tagging
Tags mark important versions in history:
# Create annotated tag
git tag -a v1.0.0 -m "Version 1.0.0"
# List tags
git tag
# Push tags to remote
git push origin v1.0.0
# Or push all tags
git push origin --tags
# Checkout to a tag
git checkout v1.0.0Cherry-picking
Cherry-pick applies specific commit to current branch:
# View commits on another branch
git log feature-branch
# Cherry-pick one commit
git cherry-pick abc123def
# Cherry-pick multiple commits
git cherry-pick abc123def..ghi456jklInteractive Rebase
Interactive rebase allows adjusting commit history:
# Interactive rebase last 3 commits
git rebase -i HEAD~3Commands in interactive rebase:
pick: Keep commitreword: Edit commit messageedit: Stop to edit commitsquash: Combine commit with previous commitfixup: Combine commit but drop messagedrop: Delete commit
Reflog - Recovering History
Reflog saves all changes on local repository:
# View reflog
git reflog
# Recover to previous state
git reset --hard HEAD@{2}Git Hooks
Git hooks are scripts that automatically run before/after Git actions:
Pre-commit hook:
.git/hooks/pre-commitbash#!/bin/sh # Run linter before commit npm run lint # If error, prevent commit if [ $? -ne 0 ]; then echo "Linting failed!" exit 1 fiPre-push hook:
.git/hooks/pre-pushbash#!/bin/sh # Run test before push npm test # If test fails, prevent push if [ $? -ne 0 ]; then echo "Tests failed!" exit 1 fi
Submodule and Subtree
Submodule: Embed another repository as a subdirectory:
bash# Add submodule git submodule add https://github.com/user/repo.git libs/repo # Update submodule git submodule update --remoteSubtree: Integrate another repository into project:
bash# Add subtree git subtree add --prefix=libs/repo https://github.com/user/repo.git main # Update subtree git subtree pull --prefix=libs/repo https://github.com/user/repo.git main
Git Bisect
Git bisect helps find the commit that caused a bug:
# Start bisect
git bisect start
# Mark current commit as bad
git bisect bad
# Mark old commit as good
git bisect good v1.0.0
# Git will checkout commits to test
# After each checkout, test and mark:
git bisect good # If no bug
# or
git bisect bad # If bug exists
# End bisect when bug-causing commit is found
git bisect resetGit Aliases
Create shortcuts for complex Git commands:
# Create alias
git config --global alias.st status
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.last 'log -1 HEAD'
git config --global alias.visual '!gitk'🧪 FINAL PROJECT: Create and Manage Code for Future Course Sections Using Git and GitHub
- Register and login to GitHub account.
- Create a new repository with a name of your choice (e.g.,
self-learning). - Create a new folder on your computer with a similar name.
- Create subfolders within this folder for each section of the course.
- Use
git initcommand to initialize Git in this folder. - Use
git add .command to add all files to staging area. - Use
git commit -m "Initial commit"command to commit changes. - Use
git remote add origin <repository-url>command to link with GitHub repository. - Use
git push -u origin maincommand to push changes to GitHub. - Continue working on course sections and commit changes frequently.
- When completing a section, create a new branch for the next section and repeat the commit and push process.
