Git is a distributed version control system that allows multiple people to work on a project simultaneously without overriding each other's changes. GitHub is a web-based platform that uses Git for version control and also provides collaboration features like pull requests, issue tracking, and project management.
- Repository (Repo): A directory that contains your project files and a
.git
subdirectory with all the version control information. - Commit: A snapshot of your repository at a specific point in time.
- Branch: A parallel version of your repository. The default branch is usually called
main
ormaster
. - Merge: Combining changes from different branches.
- Clone: Creating a local copy of a remote repository.
- Pull: Fetching changes from a remote repository and merging them into your local repository.
- Push: Sending your local changes to a remote repository.
- Remote: A common repository that all team members use to exchange their changes.
-
Installing Git
- On Linux:
sudo apt-get install git
- On macOS:
brew install git
- On Windows: Git for Windows
- On Linux:
-
Configuring Git
git config --global user.name "Your Name" git config --global user.email "your.email@example.com"
-
Initializing a Repository
mkdir my_project cd my_project git init
-
Basic Commands
git status
: Check the status of your repository.git add <file>
: Stage changes for commit.git commit -m "commit message"
: Commit changes.git log
: View commit history.
-
Create a New Repository
mkdir my_project cd my_project git init
-
Add Files and Commit
echo "Hello World" > hello.txt git add hello.txt git commit -m "Add hello.txt"
-
Create a New Branch
git checkout -b feature_branch echo "Some feature" > feature.txt git add feature.txt git commit -m "Add feature"
-
Merge Branches
git checkout main git merge feature_branch
-
Push to Remote Repository
git remote add origin https://github.com/yourusername/my_project.git git push -u origin main
-
Forking a Repository
- Fork a repository to your GitHub account.
- Clone your forked repository to your local machine.
-
Making Changes and Creating a Pull Request
git clone https://github.com/yourusername/forked_repo.git cd forked_repo git checkout -b new_feature # Make your changes git add . git commit -m "Add new feature" git push origin new_feature
-
Creating a Pull Request
- Go to your forked repository on GitHub.
- Click on "Compare & pull request".
- Submit the pull request.
-
Rebase
git checkout feature_branch git rebase main
Rebasing re-applies your changes on top of another branch's history.
-
Stashing
git stash git stash pop
Temporarily save your changes without committing.
-
Cherry-picking
git cherry-pick <commit-hash>
Apply a specific commit from one branch to another.
-
Revert
git revert <commit-hash>
Create a new commit that undoes changes from a specific commit.
- Write Descriptive Commit Messages
- Make Small, Frequent Commits
- Use Branches for Features and Fixes
- Regularly Pull Changes from the Main Branch
- Review Code via Pull Requests
Git and GitHub are powerful tools for version control and collaboration. Understanding the basic commands and workflow is essential for any software engineer. As you gain more experience, you'll encounter advanced features and best practices that will make your workflow more efficient and productive.
By practicing these commands and workflows, you'll become proficient in Git and GitHub, ensuring you can manage your projects effectively.
let's delve deeper into some more advanced features and best practices of Git and GitHub.
Interactive rebase allows you to edit, reorder, or squash commits.
git rebase -i HEAD~3
This command opens an editor where you can modify the last three commits.
Sometimes you need to change the last commit. You can do this with the --amend
option.
git commit --amend -m "Updated commit message"
Git bisect helps you find the commit that introduced a bug by binary search.
git bisect start
git bisect bad # Mark the current commit as bad
git bisect good <commit-hash> # Mark an earlier commit as good
# Follow the prompts to find the bad commit
git bisect reset # End the bisect session
Resetting changes the state of your repository.
git reset --soft HEAD~1 # Moves HEAD back but keeps changes in the index
git reset --mixed HEAD~1 # Moves HEAD back and resets the index but keeps changes in the working directory
git reset --hard HEAD~1 # Moves HEAD back and discards all changes
Reflog is used to record updates to the tip of branches and other references.
git reflog
This command shows a log of changes to the repository, including actions like checkout
and reset
.
GitHub Actions allows you to automate workflows.
- Create a
.github/workflows
directory in your repository. - Add a YAML file to define your workflow.
Example:
name: CI
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Set up Node.js
uses: actions/setup-node@v1
with:
node-version: '14'
- name: Install dependencies
run: npm install
- name: Run tests
run: npm test
Project boards help you organize and prioritize your work.
- Go to your repository and click on "Projects".
- Create a new project and add cards for tasks.
You can host static websites using GitHub Pages.
- Create a repository named
<username>.github.io
. - Push your static site files to the
main
branch. - Access your site at
https://<username>.github.io
.
- Feature Branching: Create a new branch for each feature or bug fix.
- Git Flow: A branching model with specific roles for branches and a defined release process.
- Conventional Commits: Use a structured commit message format.
Example:
feat: add new user login feature
fix: resolve issue with user session
docs: update API documentation
- Pull Requests: Use pull requests for code reviews. Assign reviewers, add comments, and discuss changes.
- Automate Testing: Use CI/CD tools to run automated tests on every push.
- Deploy Automatically: Set up automatic deployments to staging or production environments.
- Forking: Copy someone else's repository to your GitHub account.
- Pull Requests: Contribute back to the original repository by submitting a pull request.
- Issues: Use GitHub Issues to track bugs, enhancements, and other tasks.
- Labels and Milestones: Organize issues with labels and milestones.
- Discussion Forum: Enable Discussions in your repository for broader conversations.
When two branches have changes to the same part of a file, a merge conflict occurs.
# Merge conflict example
git merge feature_branch
Resolve the conflict in your editor, then:
git add <conflicted_file>
git commit
Rebasing can also result in conflicts.
git rebase main
Resolve conflicts similarly, then:
git rebase --continue
- SSH Keys: Use SSH keys for secure authentication.
- Protected Branches: Protect important branches by enforcing restrictions.
- Secrets Management: Use GitHub Secrets to store sensitive data for GitHub Actions.
Git hooks are scripts that run automatically on certain Git events.
- Client-Side Hooks: Run on your local machine.
- Server-Side Hooks: Run on the server where your central repository resides.
Example of a pre-commit hook:
#!/bin/sh
# .git/hooks/pre-commit
# Check for trailing whitespace
if grep -q '[[:blank:]]$' "$@"; then
echo "Trailing whitespace found!"
exit 1
fi
Mastering Git and GitHub involves understanding a wide range of commands, workflows, and best practices. This comprehensive guide covers both basic and advanced topics, ensuring you can handle everything from simple version control to complex collaboration and automation tasks. Regular practice and staying updated with new features will help you maintain your proficiency.
let's go over a few more advanced topics and best practices, including some less commonly discussed areas but still essential for a thorough understanding:
Submodules allow you to include other Git repositories within a repository.
-
Adding a Submodule
git submodule add https://github.com/example/repo.git path/to/submodule git commit -m "Add submodule"
-
Cloning a Repository with Submodules
git clone https://github.com/your/repo.git cd repo git submodule init git submodule update
-
Updating Submodules
cd path/to/submodule git pull origin main cd ../ git add path/to/submodule git commit -m "Update submodule"
Git LFS is an extension for managing large files.
-
Install Git LFS
git lfs install
-
Track Large Files
git lfs track "*.psd" git add .gitattributes git add example.psd git commit -m "Add PSD file" git push origin main
Git hooks are scripts that run automatically at specific points in your Git workflow. There are two types:
- Client-Side Hooks: Triggered by operations such as commit and merge.
- Server-Side Hooks: Triggered by network operations such as receiving pushed commits.
Common Hooks:
- Pre-commit: Runs before a commit is made.
- Pre-push: Runs before a push is made.
Example: Pre-commit hook to check commit messages
#!/bin/sh
# .git/hooks/commit-msg
# Ensure commit message contains a ticket number
if ! grep -q 'JIRA-[0-9]\+' "$1"; then
echo "Aborting commit. Your commit message must contain a JIRA ticket number."
exit 1
fi
To activate this hook, save it in the .git/hooks
directory of your repository and make it executable.
Continuous Integration (CI) automatically builds and tests your code every time you push changes to GitHub. Here’s an example using GitHub Actions:
-
Create a Workflow File Create a file at
.github/workflows/ci.yml
:name: CI on: [push, pull_request] jobs: build: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v2 - name: Set up Node.js uses: actions/setup-node@v1 with: node-version: '14' - name: Install dependencies run: npm install - name: Run tests run: npm test
Git aliases can simplify your workflow by creating shortcuts for Git commands.
-
Creating 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
-
Using Aliases
git co main # Short for git checkout main git br feature # Short for git branch feature
To ensure your repository stays clean and performant, consider regular maintenance tasks:
-
Garbage Collection
git gc
-
Repacking Repository
git repack -ad
-
Pruning Unreachable Objects
git prune
-
Global Ignore File Set up a global
.gitignore
for files you want Git to ignore in all your repositories.git config --global core.excludesfile ~/.gitignore_global
-
Rebase as Default for Pull
git config --global pull.rebase true
-
Auto-Correct Git Commands
git config --global help.autocorrect 1
-
GitHub CLI GitHub CLI (
gh
) provides a command-line interface for GitHub.gh auth login gh repo create gh issue create gh pr create
-
GitHub Insights GitHub provides insights and analytics on repository activities.
- Pulse: See recent activity in your repository.
- Contributors: View contributors and their contributions.
- Traffic: Monitor repository traffic.
-
Security Alerts GitHub automatically detects vulnerabilities in your dependencies and alerts you.
- Enable security alerts in the repository settings.
- View and resolve alerts in the "Security" tab.
-
Define a Contribution Guide
- Create a
CONTRIBUTING.md
file with guidelines for contributing. - Include coding standards, commit message conventions, and pull request procedures.
- Create a
-
Code Ownership
- Use
CODEOWNERS
to define individuals or teams responsible for code.
# Example CODEOWNERS file * @team-leads docs/* @docs-team
- Use
-
Automated Code Review
- Use tools like Code Climate or SonarQube to automate code reviews.
-
Regularly Review and Update Dependencies
- Use Dependabot to keep your dependencies up-to-date.
-
Documentation
- Maintain a
README.md
for project overview. - Use
docs/
directory for detailed documentation.
- Maintain a
With these advanced features and best practices, you should have a comprehensive understanding of Git and GitHub. This knowledge will help you manage projects efficiently, collaborate effectively, and maintain high standards of code quality and security. Regular practice and staying updated with new features and tools will ensure your proficiency remains sharp.