Git is a powerful version control system used by developers to manage and track code changes. Below, we’ll walk through the essential Git commands and how to use them effectively in a project.
Step 1: Create a Project in VSCode
Before initializing a Git repository, ensure you have a project to work with. This can be a folder with files or a new project in VSCode.
Create a folder for your project:
Open VSCode.
Select File > Open Folder and create a new folder.
Initialize a Git repository in VSCode:
Open the terminal in VSCode (Ctrl + `).
Run the following command to initialize a new Git repository:
git init
Step 2: Create a Git Repository
After initializing Git in your project, you’ll want to connect it to a remote repository (e.g., GitHub, GitLab, or Bitbucket) to push your changes online.
Create a repository on GitHub:
Go to GitHub and log in.
Click the + icon at the top right and select New repository.
Name your repository and choose other options (public or private).
Click Create repository.
Link your local project to the GitHub repository:
Copy the URL of your GitHub repository (e.g., https://github.com/username/repository.git).
In the VSCode terminal, add the remote URL:
git remote add origin https://github.com/username/repository.git
Step 3: Track Files and Commit Changes
Once your repository is initialized, you can start adding files to it and commit changes.
Check the status of your files:
To see which files are being tracked or untracked by Git, use:
git status
Add files to the staging area:
Use the following command to add all files:
git add .
Or add specific files:
git add filename
Commit changes:
Commit the changes with a descriptive message:
git commit -m “Initial commit”
Step 4: Push to the Remote Repository
Once you’ve committed your changes, you need to push them to GitHub or any other remote repository.
Push your changes to the remote repository:
Push to the main branch (or your default branch):
git push -u origin main
For other branches, replace main with the branch name.
Step 5: Create and Manage Branches
Branching allows you to work on different features without affecting the main codebase. Here’s how to manage branches:
Create a new branch:
To create a new branch:
git branch new-branch
Switch to a different branch:
Use this command to switch to your newly created branch:
git checkout new-branch
Alternatively, you can combine the previous two commands:
git checkout -b new-branch
List all branches:
To list all branches in your repository:
git branch
Merge a branch into the main branch:
To merge new-branch into main:
git checkout main
git merge new-branch
Delete a branch:
After merging, you may want to delete the branch:
git branch -d new-branch
To force delete a branch (if it hasn’t been merged):
git branch -D new-branch
Step 6: Collaborating with Others
Git allows multiple people to work on the same project. You can add collaborators and give them permissions to push and pull changes.
Add a collaborator on GitHub:
Go to your repository on GitHub.
Click Settings > Manage access.
Click Invite a collaborator and enter their username.
They’ll receive an invitation to join the project.
Pull changes from the remote repository:
If someone else has made changes to the repository, you can pull their updates:
git pull origin main
Replace main with the relevant branch if needed.
Forking and Pull Requests (PR):
If you’re contributing to someone else’s project, you can fork the repository, create a branch, make changes, and then create a pull request for the repository owner to review and merge.
To create a pull request:
Go to the GitHub repository.
Select Pull requests > New pull request.
Choose your branch and submit the PR.
Step 7: Git Permissions (Optional)
If you’re working with a team, it’s important to manage permissions on your GitHub repository.
Set permissions for collaborators:
In the Manage access settings, you can assign roles to collaborators:
Read: Can view the repository.
Write: Can push changes to the repository.
Admin: Can manage repository settings and collaborators.
Other Useful Git Commands
Clone a repository:
To clone an existing repository:
git clone https://github.com/username/repository.git
View commit history:
To view the commit history:
git log
Undo changes:
To discard changes to a file (unstaged):
git checkout — filename
To undo a commit (before pushing):
git reset –soft HEAD~1
Stash changes (temporarily save work):
If you’re in the middle of work but need to switch branches, you can stash changes:
git stash
Apply stashed changes later:
git stash apply
More Advanced Git Concepts and Commands
1. Git Ignore
Sometimes, you don’t want certain files (like temporary files or sensitive data) to be tracked by Git. This is where .gitignore files come in.
Create a .gitignore file:
In your project’s root directory, create a file named .gitignore and add patterns to ignore specific files or directories. For example:
# Ignore Node.js dependencies
node_modules/
# Ignore log files
*.log
Git will now ignore the files matching the patterns in .gitignore.
2. Git Tags
Tags are often used to mark specific points in a repository’s history, such as release versions.
Create a tag:
To create a tag for a specific commit (e.g., version 1.0):
git tag -a v1.0 -m “Version 1.0”
Push a tag to the remote repository:
git push origin v1.0
List tags:
git tag
3. Rebasing
Rebasing allows you to integrate changes from one branch into another, but it does so differently than merging. Rebasing rewrites commit history, which can make the history cleaner.
Rebase a branch:
You can rebase your feature branch onto the latest version of the main branch:
git checkout feature-branch
git rebase main
Resolve conflicts during rebase:
If there are conflicts during rebase, Git will stop and allow you to resolve them.
After resolving conflicts, continue the rebase:
git rebase –continue
Abort a rebase:
If something goes wrong, you can abort the rebase and return to the original state:
git rebase –abort
4. Git Hooks
Git hooks are scripts that are automatically triggered by certain Git actions. They can be used to enforce code quality checks, run tests, or perform other actions before or after commits, pushes, etc.
Pre-commit hook:
Example: A pre-commit hook could run tests before allowing a commit:
In the .git/hooks/ folder, create a file named pre-commit.
Add a script to run your tests. For example, in a Node.js project, you might add:
#!/bin/sh
npm test
Make the file executable:
chmod +x .git/hooks/pre-commit
Post-commit hook:
A post-commit hook could be used to automatically deploy code after each commit:
#!/bin/sh
./deploy.sh
5. Forking and Contributing to Open Source
If you’re contributing to open-source repositories or collaborating across teams, forking is a common workflow.
Fork a repository on GitHub:
Click on the Fork button on the top-right of the repository’s page.
Clone your forked repository:
After forking a repo, clone it to your local machine:
git clone https://github.com/yourusername/repository.git
Keep your fork up to date with the original repository:
Add the original repository as a remote to your fork:
git remote add upstream https://github.com/original-owner/repository.git
Fetch the latest changes from the original repo:
git fetch upstream
Merge them into your local branch:
git merge upstream/main
6. Undoing Changes
Sometimes you may need to undo certain changes or commits. Here are a few ways to do that:
Undo the last commit (without deleting changes):
If you want to uncommit the last commit but keep the changes in your working directory:
git reset –soft HEAD~1
Undo all changes and reset to the last commit:
If you want to discard all uncommitted changes and reset to the last commit:
git reset –hard HEAD
7. Workflows for Large Projects
In large teams or open-source projects, Git workflows help to streamline development and avoid conflicts. Some of the common workflows include:
Feature Branch Workflow: Developers create branches for each feature they are working on. Once the feature is complete, they submit a pull request to merge the feature into the main branch.
Git Flow: A more structured branching model that defines specific branches for different purposes, such as feature, develop, release, and hotfix branches.
Forking Workflow: Often used in open-source projects. Contributors fork the repository, make changes in their forked copy, and then create pull requests to the main repository.
8. Git Blame
If you want to see who made a specific change to a line of code, git blame can help.
Blame a file:
This command shows the author of each line in a file:
git blame filename
9. Git Cherry-pick
If you want to apply a specific commit from another branch to your current branch, use cherry-pick.
Cherry-pick a commit:
Get the commit hash using git log.
Apply the commit to your current branch:
git cherry-pick <commit-hash>
Very useful information!