📖 Using Git
Description
Git is a powerful version control system used by developers to manage changes to code over time. Whether you're working on a personal project or collaborating with a team, Git helps track changes, revert mistakes, and maintain an organized development workflow.
Getting Started
Git organizes your work into repositories, allowing you to save versions of your project as it evolves. This involves three key steps:
- Modified
- Files have been edited but are not yet tracked by Git.
- Staged
- Changes are marked for inclusion in the next commit.
- Committed
- Changes are saved to the repository as a new version.
Git is tightly integrated with VS Code, offering an intuitive GUI for managing your projects. Alternatively, you can use Git Bash for command-line interaction.
Create a Git Repository
Using VS Code
- Open a folder in VS Code where your project files are stored.
- Click the
Source Control
icon in the left-hand toolbar. - Click
Initialize Repository
to create a new repository in the selected folder. - Press
Ctrl+Enter
to create an initial commit with a required commit message, such as "init commit." - Git is now tracking your project files.
Using Git Bash
- Open your project folder in VS Code and launch the terminal (
Ctrl+`
). - Run the following commands:
git init
git add .
git commit -m "init commit"
- Git will now track all files in the repository.
Note: The first commit skips the staging step for simplicity. Future commits allow more granular control over what changes to include.
Managing Content Changes
Using VS Code
To manage changes to your project content, Git needs you to initiate the tracking. You do this through a process of staging and committing changes. Git monitors your project for changes and can tell if a file is new (untracked) or modified. It won't save the changes to the version control system until you stage and/or commit the changes.
- Click the
Source Control
icon in the VS Code toolbar. - Files with changes will appear under
Changes
, marked with:U
for untracked filesM
for modified filesD
for deleted files
- Hover over a file and click the
+
icon to stage it. - Write a descriptive commit message and click
Commit
to save the changes.
Reviewing File Changes
In VS Code, you can preview changes by clicking on a file in the Changes
list. A side-by-side view will display the old content (highlighted in red) and the new content (highlighted in green). This feature helps ensure accuracy before committing.
Command Line Interface
While VS Code provides a GUI, learning Git's CLI commands can be invaluable for understanding its core operations. Here are some commonly used commands:
- Check Git Status
git status
- Stage Files
git add [file]
orgit add .
- Commit Changes
git commit -m "message"
- View Log
git log
Cheat Sheets
Mastering Git takes time, but cheat sheets can help streamline the learning process. Explore these resources: