Github 视频台词整理
n5321 | 2024年11月16日 09:38
状态:
Git is the most popular version control system in the world。
功能。
records the changes made to our code over time in a special database called repository we can look at our project history and see who has made what changes when and why and if we screw something up we can easily revert our project back to an earlier state
without a version control system we'll have to constantly store copies of the entire project in various folders this is very slow and doesn't scale at all especially if multiple people have to work on the same project you would have to constantly toss around the latest code via email or some other mechanisms and then manually merge the changes
so in a nutshell with a version control system we can track our project history and work together now version control systems fall into two categories: centralized and distributed in a centralized system all team members connect to a central server to get the latest copy of the code and to share their changes with others subversion and microsoft team foundation server are examples of centralized version control systems the problem with the centralized architecture is the single point of failure If the server goes offline, we cannot collaborate or save snapshots of our project.集中式 So we have to wait until the server comes back online.
和分布式 In distributed systems, we don't have these problems. Every team member has a copy of the project with its history on their machine. So we can save snapshots of our project locally on our machine. If the central server is offline, we can synchronize our work directly with others.
Git and Mercurial are examples of distributed version control systems. Out of all these, Git is the most popular version control system in the world because it's free, open source, super fast, and scalable.
Operations like branching and merging are slow and painful in other version control systems like Subversion or TFS, but they're very fast in Git. We'll talk about this later.So Git is almost everywhere.
More than 90% of software projects in the world use Git. That's why almost every job description for a software developer mentions Git. So if you're looking for a job as a software developer, Git is one of the skills you must have on your resume.
You should know it inside out, how it works, and how to use it to track your project history and collaborate with others effectively. And that's exactly what you're going to learn in this course.
Let's talk about various ways to use Git. We can use Git on the command line. So we open a terminal or command prompt window to execute Git commands. This is the fastest and sometimes the easiest way to get the job done. That's why a lot of people use the command line. Now if you don't like the command line, well, you're in luck because most modern code editors or IDEs have built-in support for basic Git features. For example, in VS Code, we have this source control panel which gives us the essential Git features. There are also extensions available for bringing additional Git features for VS Code. The most popular extension is GitLens; it brings a ton of Git features in VS Code.There are also graphical user interfaces specifically made for using Git. Here on the Git website, you can find the complete list of these tools for different platforms.
We have tools for Windows, Mac, Linux, Android, and iOS. Out of all these, the two most popular tools are GitKraken and SourceTree.
GitKraken is my personal favorite GUI tool for Git. It's beautifully designed, works across different platforms, and integrates with other GitKraken products such as GitKraken Boards for issue tracking and GitKraken Timelines for project management. It's free for open-source projects, but for commercial projects, you have to pay an annual fee. Just to let you know, I'm not an affiliate of GitKraken; I'm just a fan.
The other option is SourceTree. It's completely free but only available for Windows and Mac. So if you're a Linux user, you have to use GitKraken or another GUI tool.
In this course, we'll be spending most of our time on the command line for a couple of reasons. The first reason is that pretty much all these GUI tools have limitations; they support the Git commands that people use most of the time. So even if you want to use a GUI tool, there are times you would have to revert back to the command line to get the job done. The other reason is that the command line is always available, whereas a GUI tool may not be accessible in certain situations.
Many people, including myself, use both the command line and a GUI tool. In this course, I'll show you when it makes sense to use a GUI tool and when the command line is faster and easier.
At the end of the day, you should use the right tool for the job. Don't be like this guy, you probably know him, our popular superstar developer called John Smith. He thinks he's better than everyone else because he does everything in the command line and looks down on people who use GUI tools. Let him think whatever he wants; if that makes him happy, who cares?
We'll be spending most of our time on the command line, but I'll show you examples in VS Code and GitKraken when it makes sense to use a GUI tool because those are the most popular tools.If you've never worked with a command line before, don't worry; I'll guide you step by step. It's a lot easier than you think.
Next, we're going to install Git. Let's see if you have Git on your machine or not and, if yes, what version you have installed. To do this, open a terminal or command prompt window. If you're on Mac, press Command and Space, then type Terminal. If you're on Windows, click the search icon on the bottom navigation bar and type CMD.Your terminal window might look different, but it doesn't matter. This is where we're going to execute Git commands.
Let's look at the version of Git on this machine. Type `git --version`.
In this machine, I'm using Git version 2.19.2, but the latest version at the time of recording this video is 2.27.0. I highly encourage you to download and install the latest version. Head over to git-scm.com/download for instructions on installing Git on different operating systems. It's really easy, and you're not going to run into any problems.
If you're on Windows, once you install Git, you'll get an application called Git Bash, which is short for "Bourne Again Shell."
This is basically a command prompt window like this one over here but it emulates Unix or Linux environments. So throughout this course, I encourage you to use Git Bash instead of the built-in command prompt window, so what you see on the screen looks closer to what I'm going to show you in this course.
So, go ahead and install Git. In the next lesson, I'm going to show you how to customize our Git environment. The first time we use Git, we have to specify a few configuration settings.
We have to specify our name, email, default editor, and how it should handle line endings.(用户)
We can specify these configuration settings at three different levels. At the very top, we have the system level. The settings that we have here apply to all users of the current computer. Below this level, we have the global level. The settings here apply to all repositories of the current user. And below this level, we have the local level. The settings here apply to the current repository or the repository in the current folder. So we can have different settings for different repositories or different projects.
So here, in the terminal window, we type git config
, then we type --global
to specify the level at which we are defining these settings. Next, we should specify the setting we want to configure. So, user.name
. Here we type double quotes and type our name. Now the reason we're adding double quotes is because we have a space in this value. Okay, so that was the first setting.
Once again, git config --global
. This time we're going to set user.email
. Now because we don't have a space in emails here, we don't need double quotes. So, let's add our email.
Alright, next, we need to specify our default editor. If you don't set this on Mac, by default Git is going to use Vim, which is a scary editor a lot of people are freaked out by. In this course, I'm going to use Visual Studio Code or VS Code. You can use any editor that you prefer, but if you want to follow along with me, I highly encourage you to download the latest version of Visual Studio Code from code.visualstudio.com
.
Now, on this machine, I've added Visual Studio Code to my path so I can open it from any folder on my machine without specifying the full path. So if I type code
, here's VS Code. If this doesn't work on your machine, you have to troubleshoot the issue yourself. Depending on your operating system, there are different instructions for adding VS Code to your path.
So back to the terminal, let's set the default editor. git config --global
, the setting we want to configure is core.editor
. Once again, we need double quotes because here we're going to have a space. The value for this setting is code --wait
. With the --wait
flag, we tell the terminal window to wait until we close the new VS Code instance. Okay, so let's go ahead.
Now, all these configuration settings are stored in a text file. We can edit that file using our default editor, in this case, VS Code. So we can type git config --global -e
. This will open our default editor to edit all the global settings. Let me show you.
Alright, here's our configuration file. You can see the full path to this file at the top. The name of this file is .gitconfig
. In this file, we have different sections. So we have the user section with two settings, name and email. We have the core section with these two settings, and so on. Now back in the terminal window, you can see the terminal is waiting for us to close VS Code. So as we close it, now we're back in the terminal and we can execute the next command.
Next, we're going to configure how Git should handle end of lines. This is a very important setting that a lot of people miss. So on Windows, end of lines are marked with two special characters: carriage return and line feed. On Mac and Linux systems, end of lines are indicated with line feed. So that means if we don't handle end of lines properly, we're going to run into some weird issues down the road. To prevent this, we have to configure a property called core.autocrlf
, which is short for "carriage return line feed".
Let me walk you through a real scenario. Let's say we have two people here, John and Julie, working with the same repository. John uses a Windows machine, Julie uses a Mac. As I told you, on Windows, end of lines are marked with carriage return and line feed. So when John wants to check in his code into the repository, Git will remove the carriage return character from end of lines. Similarly, when he checks out his code from the repository...
To achieve the desired behavior regarding end of lines and carriage return characters in Git, you should set the following properties:
-
For updating end of lines and adding the carriage return character:
- Set the property to true.
-
When Julie checks out the code and doesn't want the carriage return character:
- Git shouldn't touch the end of lines.
-
If carriage return characters are accidentally added to end of lines, perhaps because of the editor that Julie is using:
- Git should remove them when storing the code in the repository.
- Set this property to input.
To configure these settings, use the following command in the terminal:
git config --global core.autocrlf
# For Windows:
git config --global core.autocrlf true
# For macOS or Linux:
git config --global core.autocrlf input
For information on Git commands and configurations:
- To learn more about a specific command like
git config
, you can Google it or usegit config --help
in the terminal for detailed information. - For a quick summary, use
git config -h
.
https://www.atlassian.com/git/tutorials/setting-up-a-repository/git-config
这个网站没仔细看,但是感觉很厉害的样子。
In the next section, you'll learn about taking snapshots (commits) in Git, an essential part of the workflow. Make sure to grasp the fundamental concepts as they are often misunderstood by beginners.
To get started with a project in Git:
- Create a project directory.
- Initialize a new Git repository using
git init
. - The
git init
command creates a new Git repository. - Understand the Git repository structure and avoid modifying the
.git
directory. - Add and commit changes using the staging area to create snapshots of your project.
The basic Git workflow involves modifying files, staging changes, reviewing them, and committing them to the repository.
The staging area allows you to review and organize your changes before committing them. Remember, each commit represents a snapshot of your project at a specific point in time.
When working with a staging environment similar to releasing software to production,(一次commit等同于一次新版本发布) it reflects either the current state in production or the upcoming version destined for production.
For instance, during bug fixing, changes are made to file one. The staging area initially holds the old version of file one until these changes are staged using the add
command. Subsequently, a commit is made to record this state, resulting in two commits in the repository.
If a decision is made to delete file two, even though it's removed from the working directory, it remains in the staging area until the deletion is staged using the add
command. Another commit is then made to permanently store this deletion, resulting in three commits in the repository.
Each commit in the repository contains a unique identifier generated by Git, along with information about the changes made, the author, the timestamp, and a complete snapshot of the project at that time. Git doesn't store just the changes made (deltas), but the full content of each snapshot, facilitating quick restoration to previous states without needing to compute changes.(类似Windows的系统还原点)
The key to Git's efficiency in data storage lies in its compression of file contents and avoidance of storing duplicate content. (核心技术:对于文档的内容进行了压缩,并且避免储存相同的数据内容,所以他很快)This approach allows users to revert to any previous state quickly. While Git users don't need to know the specifics of how data is stored, understanding that each commit contains a complete snapshot of the project is crucial for leveraging the version control system effectively.
When fixing a bug and finding a typo in your app, avoid mixing changes in one commit. Make separate commits for each - one for the typo(打字错误) and another for the bug fix. If you accidentally stage both changes, you can easily unstage them as shown later. Create meaningful commit messages; cryptic messages are unhelpful. Committing single units of work makes crafting messages easier.
Use present tense for commit messages, e.g.(用一般时态), "Fix the bug," for clarity and consistency. Stick to a message convention for team cohesion. Always consider best practices when committing code.
For advanced Git learning beyond this video, check out my full course covering intermediate to advanced topics, with a certificate, notes, and refund guarantee. Enroll via the link below.
You don't always have to stage changes before committing. Learn how to skip the staging area cautiously. Remove unnecessary files with rm
and git rm
. Use git mv
for renaming or moving files.
To ignore files/directories, create a .gitignore
in the project root. Add entries like logs/
to exclude certain files. Remember, Git won't ignore files already committed.
Every time we compile our code, Git detects that the bin/app.bin file is changed(这就是一个很牛逼的技术), so we have to stage it and commit it. This doesn’t make sense. Why do we have to commit this file every time we compile our application?
Adding bin
to .gitignore
To solve this, let’s add the bin
directory to .gitignore
. Back in the terminal, let’s run git status
. Now, we have modified .gitignore
.
Steps:
- Stage and commit the change:
- However, Git still tracks the changes in this directory because it’s already being tracked.
Removing bin
from the staging area
Let’s modify the bin
file by adding some content, for example:
Then run git status
. Git will still say this file is modified, which is not what we want. To fix this, we need to remove this file from the staging area.
Use the git rm
command with the --cached
option to remove it only from the staging area, not from the working directory:
If you see an error saying "Not removing bin recursively without -r," add the recursive option:
Now, the entire directory is removed from the staging area. Verify this by running git ls-files
. The bin
directory is no longer there. Run git status
again, and you’ll see one change ready to be committed—removing the directory from the staging area.
Commit the change:
From this point forward, Git will no longer track changes in the bin
directory. You can still modify files like bin/app.bin
, and your working directory will remain clean.
GitHub .gitignore
templates
GitHub provides various .gitignore
templates for different programming languages. For example, in Java projects, it’s a good idea to exclude .class
files, as these are automatically generated during compilation. Visit the GitHub .gitignore
templates repository for more examples.
Simplified output with git status -s
The git status
command provides detailed but verbose output. Using the short format with git status -s
makes it easier to interpret:
- The left column represents the staging area.
- The right column represents the working directory.
Example:
Output:
M
(modified): A file has been modified but not staged.??
(untracked): A new file not being tracked by Git.
Reviewing changes before committing
Before committing, always review what’s in the staging area to ensure no bad or broken code gets committed. Use this command to check the staged changes:
In the output:
- Lines prefixed with
-
show what’s being removed. - Lines prefixed with
+
show what’s being added.
This allows you to ensure everything is correct before making a commit.
Understanding git diff
and git difftool
Comparing file versions with git diff
In this example, we're comparing two copies of file2
.
- Legend clarification:
- We don’t have an old copy of
file2
because it’s a new file. - The header
0,0
indicates that starting from line 0, no lines have been extracted since there is no old version of this file in the last commit.
- We don’t have an old copy of
Viewing changes in the working directory
To see changes in the working directory that are not staged:
Run
git diff
without arguments:
This compares the working directory with the staging area.- If there are no changes, there will be no output.
- If there are untracked changes, they will appear in the output.
Verify with
git status -s
:
Use this to check the working directory and staging area status.
Example:
Modify a file (
file1
):
Openfile1
in an editor (e.g., VS Code). Change the first line to:Save the file.
Run
git status -s
:- Shows changes in the working directory not yet staged.
Run
git diff
:- This compares the staging area (old copy) with the working directory (new copy).
- Lines prefixed with
-
are removed (old content). - Lines prefixed with
+
are added (new content).
Recap:
- Use
git diff
to see unstaged changes. - Use
git diff --staged
to see staged changes ready for the next commit.
Using Visual Diff Tools
Popular tools:
- Cross-platform:
kdiff
,p4merge
- Windows-only:
WinMerge
Using VS Code as the default diff tool:
Configure VS Code as your default diff tool:
Check the global configuration:
- This opens the
.gitconfig
file for editing. - Verify the
diff
section includes the tool and command you set.
- This opens the
Using
git difftool
:- Run
git difftool
to compare changes in the working directory with the staging area. - Add
--staged
to compare staged changes.
- Run
Example with VS Code:
Modify
file1.js
.Run
git difftool
:- Opens VS Code, showing the old copy (staged) and new copy (working directory).
- Review changes visually.
Close VS Code to return to the terminal.
Summary:
git diff
: Command-line diff comparison.git difftool
: Launches visual diff tools like VS Code for easier file comparison.Two files have been affected in the staging area. The first one is
file1.js
. Let’s look at the changes.In this case, the old copy is what we had before, and the new copy is what we have in the staging area. These are the changes that will be included in the next commit. From this, we can easily tell that two lines have been added.
Now, let's close this tab. Back in the terminal, Git is asking if we want to look at the changes in
file2.js
. In this case, I’ll ignore it and typeno
.Quite honestly, we don’t use diff tools as much these days. I covered it here because I want my course to be comprehensive. Modern editors and IDEs allow us to view staged and unstaged changes as part of our development environment. I’ll show you how to do this later in the course.
Viewing Commit History
We’ve made a few commits so far. But where are these commits? Let me show you. Use the
log
command to look at the history:Take a look! Here are all the commits we’ve created, sorted from the latest to the earliest.
The most recent commit is at the top. Each commit has a unique identifier, a 40-character hexadecimal string generated automatically by Git. Think of it like a revision number, but instead of incrementing, it’s unique and randomly generated.
Next to that, we see
HEAD
pointing tomaster
. What does this mean?- Master: The main branch or main line of work in Git. Other version control systems might call this the “trunk.”
- HEAD: A reference to the current branch, indicating where we are working.
For each commit, we can see:
- Author: The name and email of the author.
- Date and time: When the commit was created.
- Description: A one-line summary.
To navigate through the log:
- Press
space
to move to the next page. - Press
q
to quit.
Log Options
The
log
command has a few useful options:One-line Summary:
This shows a short summary of each commit with the identifier shortened to 7 characters and the description only.
Reverse Order:
This displays the commits from the oldest to the newest.
Viewing Specific Commits
If you want to see the exact changes in a specific commit, use the
show
command. For example, to inspect the most recent commit:Alternatively, you can use the
HEAD
reference:- To view the last commit:
- To view the second-to-last commit:
In the commit details, you’ll see:
- Author and date: Information about the commit.
- Diff: What was removed or added.
If you want to see the exact file version stored in a commit:
Viewing Files in a Commit
To list all files and directories in a specific commit:
This displays all the files and directories (as a tree structure) in the commit. Files are represented by blobs, and directories by trees.
For example, to view a file or directory:
Managing Staged Changes
Let’s say we reviewed the changes in the staging area and realized that the changes in
file1.js
shouldn’t be in the next commit (perhaps they belong to a different task). To undo the staging of this file:This restores
file1.js
to its state before it was staged. It’s worth noting that older Git versions used thereset
command for this purpose, but therestore
command simplifies the process.Make sure you’re using Git 2.28 or later, as the
restore
command won’t work in older versions.To restore a file in the staging area, use the
--staged
flag followed by the file name. You can list multiple files here or use patterns. If you want to restore everything in the staging area, simply use a period (.
). For example:After running this command, if you check the status again with
git status
, you’ll notice that the green "M" indicating a modified file is gone. All changes in the staging area are now in the working directory. For a short status:You’ll see that file1 no longer has any changes in the staging area, as those changes have moved to the working directory.
The
git restore
command works by taking a copy of the file from the next environment. For files in the staging area, this next environment is the last commit in the repository. For example, restoringfile1.js
copies it from the last snapshot into the staging area.Now let’s look at file2. It's a new file, indicated by a green "A" (added) in the staging area. However, since this file doesn’t exist in the last commit, restoring it will remove it from the staging area and return it to its previous state as an untracked file. Here's how:
After running
git status
, you’ll see file2 marked with "??" as an untracked file.If you have code changes in the working directory that you want to discard, you can also use
git restore
. For instance:This command copies the version of the file from the staging area back into the working directory, effectively discarding local changes. You can use a period (
.
) to undo all local changes:However, note that
git restore
won’t affect untracked files (e.g., file2). To clean up untracked files, you use thegit clean
command. By default, Git requires you to force this operation since it is irreversible. Use:This command removes all untracked files and directories. Checking the status again with
git status -s
will show that file2 is gone.Git tracks all versions of a file once it's committed, meaning you can always restore a file or directory to a previous version. For example, let’s delete
file1.js
. Using therm
command in Unix-based systems only removes the file from the working directory. To remove it from both the working directory and the staging area, use:After staging this change, you can commit it:
If you later decide you shouldn’t have deleted the file, you can restore it to a previous version. For example, to restore
file1.js
from the commit before the last one, identify the commit usinggit log
, then run:This command restores
file1.js
to its state in the specified commit (HEAD~1
refers to the commit before the last one). After restoring, the file will appear as an untracked file.