Learn Git easily (3): Master the remote operation of Git


Preface

Version control systems are an indispensable tool in modern software development, helping team collaboration, code management, and tracking the evolution history of a project. Among version control systems, Distributed Version Control System (DVCS) has become the first choice of developers because of its powerful and flexible features. This article will delve into the working principles and advantages of distributed version control systems, help us better understand and apply Git, and become a Git master.

I hope that reading the content of this article will help us better master Git and easily cope with various needs for team collaboration and version control.

1. Understanding of distributed version control systems

Version control systems are a vital part of software development, helping with team collaboration, code management, and tracking the evolution of a project. Among version control systems, Distributed Version Control System (DVCS) is a powerful and flexible approach. This article will take an in-depth look at how distributed version control systems work and their advantages.

1.1 What is a distributed version control system?

Distributed version control system (DVCS) is a version control system that is different from traditional centralized version control systems. In a centralized version control system, all code is stored on a central server, and developers communicate with the server to obtain and submit code. In DVCS, each developer's local environment contains a complete code version library and no longer relies on a real-time connection to a central server. This means each developer can work locally and independently without the need for a constant network connection.

1.2 Working principle

The working principle of a distributed version control system can be briefly summarized as follows:

  1. Local repository: Each developer has a complete repository on their own computer, containing all the history and files of the project.

  2. Independent work: Developers can make modifications, add new files, delete files and other operations in the local workspace without interacting with the central server.

  3. Submitting changes: When developers complete a part of their work, they submit their changes to their local repository to form a new version.

  4. Branching and merging: Developers can create branches to independently develop a feature or fix a bug. The merge operation of branches allows changes from different branches to be merged into the master branch or other branches.

  5. Remote collaboration: Developers can choose to share their code changes with other developers. This can be achieved by pushing changes from the local repository to the remote repository. The remote repository is usually located on a central server, but can also be another developer's computer.

  6. Synchronous updates: Developers can pull other people's changes from the remote repository and merge them into their own local repository to keep the code up to date.

1.3 Advantages of distributed version control systems

Using a distributed version control system brings many advantages:

  1. Work offline: Developers can continue working without an internet connection because everyone has a local repository.

  2. Security: Each local repository is complete, so even if one developer's computer is damaged, others can still maintain the integrity of their code.

  3. Efficient branch management: Branch and merge operations become easier and more flexible, supporting parallel development of multiple features or fixing multiple bugs.

  4. Collaboration flexibility: Developers can exchange changes directly without relying on a central server. This is especially useful for open source projects and distributed teams.

  5. Backup and restore: Each local repository can be treated as a backup, and historical versions can be easily restored if needed.

In short, the distributed version control system is one of the indispensable tools for modern software development. It provides more powerful version control and collaboration capabilities, making the development team more flexible and efficient. By understanding its working principles and advantages, developers can better utilize distributed version control systems to manage and track the project's code.

2. First introduction to Git remote warehouse

Git is a powerful distributed version control system that allows the same Git warehouse to be distributed on different machines. However, you may ask, I only have one computer, how can I experience the remote warehouse? In fact, even if you only have one computer, you can clone multiple repositories as long as they are not in the same directory. But this is rare in practical applications, because there is no need to create multiple remote libraries on one computer, and there is a risk that all libraries will be lost if the hard disk hangs. So, let's understand how to use remote libraries, i.e. work together on multiple machines.

2.1 The concept of remote warehouse

A remote repository is a Git repository located elsewhere. It can be on a different machine, a different location, or even a different network. The existence of remote warehouse makes collaborative development by multiple people possible, and it is the basis for code sharing and collaboration.

2.2 Git remote operation

Git remote operations include the following key concepts:

  1. Clone: ​​The clone operation allows you to copy the contents of a remote repository to your local computer and create a local repository. This local repository is a copy of the remote library and can be used for local development and modification.

  2. Push: The push operation allows you to upload changes from your local repository to a remote repository so that other developers can access and merge these changes.

  3. Pull: The pull operation allows you to get the latest changes from the remote repository and merge them into the local repository, keeping the local code in sync with the remote code.

2.3 Remote warehouse hosting service

It is possible to set up your own Git remote warehouse server, but it is usually not necessary, especially during the learning stage. Fortunately, there are many online hosting services that provide Git remote repositories for free. Among them, GitHub is the most well-known international service, while Gitee is a common choice for domestic users.

These managed services allow us to easily create remote repositories, collaborate with other developers, track the progress of the project, and provide a range of tools and features to manage code. Just register an account and you can create your own remote warehouse on these platforms without worrying about setting up a server or complicated configuration.

In the next blog, I will take Gitee as an example to learn how to use remote warehouses from scratch, including creating remote warehouses, cloning remote warehouses locally, pushing changes to remote warehouses, and pulling updates from remote warehouses. .

3. Create a new remote warehouse

To create a new remote warehouse on Code Cloud, we first need to register an account. There is no doubt about this. Once you have an account, you can create a new remote warehouse.

Fill in the basic information of the warehouse:

Created successfully:

From the created remote warehouse, we can see that the branches we have learned locally before also exist in the remote warehouse and are managed. The newly created warehouse has one and only one default master branch.

4. Clone the remote warehouse to local

To clone a remote warehouse locally, you need to use git clonethe command, followed by the link address of our remote warehouse. The link to the remote warehouse can be found in the warehouse: select "Clone/Download" to obtain the remote warehouse link.

You can find clone/download addresses with many different protocols, among which SSH protocol and HTTPS protocol are the two most commonly used data transfer protocols in Git.

  • The SSH protocol uses public key encryption and public key login mechanisms, which reflects practicality and security. Using this protocol requires the public key to be placed on the server and managed by the Git server.
  • When using HTTPS, there are no requirements and you can clone it directly, so it is simpler.

Below is a demonstration of cloning using two different protocols.

4.1 Clone using HTTPS


Note that cloning here requires us to enter Usernamethe email address we used when filling in the registration code cloud.

4.2 Clone using SSH

If you try to clone directly:

You can find that when using SSH to clone the repository, the server rejected our clone request because we did not add the public key to the remote repository. Therefore, we first need to set up the public key:

Step 1: Create SSH Key

In the current user's home directory, check to see if there is .ssha directory. If so, check to see if there are two files id_rsa(private key) and (public key) in this directory. If they already exist, you can jump directly to the next step. id_rsa.pub. If not, you need to create an SSH Key. The command used is ssh-keygen -t rsa -C "注册码云的邮箱":

The creation is successful at this time. You can see that there are two files and in .sshthe directory . These two are the secret key pairs of the SSH Key. They are private keys and cannot be leaked. , is a public key that can be shared with anyone with confidence.id_rsaid_rsa.pubid_rsaid_rsa.pub

Step 2: Add your own public key to the remote warehouse

Enter the code cloud settings:

select the SSH public key in the security settings:

Just copy and paste the content in the generated above id_rsa.pubverbatim. At this time, the configuration of the remote public key is completed.

At this point, perform the cloning operation again and find that the remote warehouse can be successfully cloned locally.


If there are multiple people collaborating on development, GitHub/Gitee allows adding multiple public keys. As long as the Key on everyone's computer is added to GitHub/Gitee, each computer can submit pushes to GitHub/Gitee. .

4.3 View cloned warehouse information

When we clone from the remote repository, Git will actually automatically map the local masterbranch to the remote branch master, and the default name of the remote repository is origin. Locally we can use git remotethe command to view the information of the remote library, such as:

Or, use to git remote -vdisplay more detailed information:


The above shows originthe addresses that can be fetched and pushed. If you don't have push permission, you won't be able to see pushthe address of . So what does push mean? Let’s continue reading.

5. Push to remote warehouse

5.1 Add files to the local warehouse

After the remote warehouse has been successfully cloned locally, we can submit content to the warehouse, such as adding a new file.txtfile:

At this time, use to vimadd and edit file.txtthe file, and then use addthe and commitcommand to store it in the local repository. If you use git statusthe command at this time:


As you can see, we are prompted to use pushthe command to push it to the remote warehouse.

In addition, please note when submitting that if we have set the global nameand before email, these two configurations need to be consistent with the user name and email configured on the current code cloud, otherwise an error will occur; if the global and have never been set, then nameour emailfirst time An error will also be reported when submitting, which requires us to reconfigure it.

5.2 Push local files to remote warehouse

At this point we have submitted the content to the local warehouse. How to push the content of the local warehouse to the remote warehouse? You need to use the command. This command is used to git pushupload the local branch version to the remote and merge it. The command format is as follows:

git push <远程主机名> <本地分⽀名>:<远程分⽀名>
# 如果本地分⽀名与远程分⽀名相同,则可以省略冒号 `:`
git push <远程主机名> <本地分⽀名>

masterAt this point we want to push the local branch to originthe host masterbranch, then we can:


Push successful! Since we are using the SSH protocol here, we do not need to enter a password every time we push, which facilitates our push operation. If the HTTPS protocol is used, without additional settings, you may have to enter your username and password every time you push.

Check the remote warehouse on Code Cloud and find that the push was successful.

6. Pull from remote warehouse

In the actual development process, multiple developers often collaborate to develop. If a developer submits new code to the remote warehouse, then the content on his local warehouse will be different from the content on the remote warehouse. , so you need to pull it again from the remote warehouse.

6.1 Modify the contents of the remote warehouse

At this point, you can file.txtsimulate other developers pushing new code to the remote warehouse by modifying the contents of the file on the remote warehouse:


At this time, the remote warehouse is one version ahead of the local warehouse. In order to keep the local warehouse with the latest version, we need to pull the remote code and merge it locally.

6.2 Pull from remote warehouse

Git provides git pullthe command, which is used to fetch code from a remote location and merge the local version. The format is as follows:

git pull <远程主机名> <远程分⽀名>:<本地分⽀名>

# 如果远程分⽀是与当前分⽀合并,则冒号后⾯的部分可以省略。
git pull <远程主机名> <远程分⽀名>

For example, pull the code from the remote warehouse:

check the file again file.txtand find that the content is the same as the remote warehouse.

7. gitignore file

In daily development, we have some files that we do not want or should not submit to the remote end, such as the configuration file that saves the database password. So how do we let Git know which files to ignore? Create a special .gitignorefile in the root directory of the Git workspace, then fill in the file names to be ignored, and Git will automatically ignore these files.

7.1 Configure gitignore file

Generally, we do not need to create .gitignorethe file ourselves, because when creating a remote warehouse on Code Cloud, if we check the Add .gitignoreoption, it will be automatically generated by us:

if this option is not selected at the time, it is also possible to create one in the workspace. Either way, you can end up with a complete .gitignorefile. For example, if we want to ignore all files ending with .soand , the content is as follows:.ini.gitignore

# 省略选择模本的内容
...
# My configurations:
*.ini
*.so

In addition, .gitignoreyou can also specify a certain file or folder in the file to ignore all the contents of this file or folder.

The last step is to .gitignoresubmit it to the remote end, which completes .gitignorethe configuration of the file:

For example, create a file on the workspace at this time test.soand see if Git tracks and manages it.


Use git statusthe command to find that the workspace is still clean, indicating that test.sothe file has been successfully ignored.

7.2 Push ignored files

  1. Sometimes, we may want to add a file to Git, but because the file is .gitignoreignored and cannot be added at all, we can use -fthe option to force the addition:
git add -f [filename]
  1. Or we find that there may be .gitignorea problem with the writing, and we need to find out which rule is written wrong, for example, test.soa file is to be added. In this case, you can use the following command to check:
 git check-ignore -v [filename]

For example:

At this point, you can find test.sothe reason for being ignored.

  1. There are also times when we write rules that exclude .*all files of type, for example:
# 排除所有.开头的隐藏⽂件:
.*

But we found that .*this rule .gitignorealso excludes . Although it can be git add -fforcibly added, it always seems inelegant and breaks .gitignorethe rules. At this time, you can add an exception rule:

# 排除所有.开头的隐藏⽂件:
.*

# 不排除.gitignore
!.gitignore

.gitignoreThis is how to exclude specified files from the rules ! + 文件名. So, just add the exception file.

8. Tag management

8.1 What is a label

In Git, a tag is commita meaningful identification for a certain event, which can be regarded as commitan alias for a specific event. The main function of labels is to identify important versions, milestones or releases in the project, making it easier for people to understand and remember.

The meaning of the label:

Why use tags? Compared with that long list that is difficult to remember commit id, tags provide the following important benefits:

  1. Easy to remember and use: Tags usually use meaningful names to represent versions, such as "v1.0", "Release-2.1", or "Beta". This makes it easier for developers and teams to remember and use tags, rather than having to remember a long list of hashes.

  2. Version management: Tags are a powerful tool for version management. When the project needs to release a new version or an important milestone, you can create a label for the relevant commit so that you can find and access this specific version of the code at any time.

  3. Easy to roll back: When you need to roll back to a specific version, you can directly use the label to locate it without having to remember the commit id. This greatly simplifies the version switching process.

  4. Readability and clarity: The name of the label can convey information about the version, such as whether it is an official version, what problems have been fixed, what features have been added, etc. This helps team members better understand the meaning of the release.

Tags are a powerful tool in Git for identifying important releases and milestones. They provide an easier-to-remember and use way to target specific ones commit, making version management and collaboration more efficient and clear.

8.2 Creation of labels

Tagging in Git is very simple. First switch to the branch that needs to be tagged:

Then, use the command git tag [name]to create a new label:

You can use the command git tagto view all tags:

The default tag is the latest commit commit. commitSo how to label the specified one? The method is to find the historical submissions commit idand then use the following command to tag them:

git tag [name] [commit id]

For example the following example:

8.3 View label information

Use git tagto view the tag information. You can find that it is not listed in chronological order, but in alphabetical order.

In addition, you can use to git show [tagname]view tag information:


commitAt this time, all information corresponding to is listed .

Not only that, Git also provides the ability to create tags with descriptions. Use to -aspecify the tag name and -mdescription text. The format is:

git tag -a [name] -m "XXX" [commit_id] 

After tagging, use tree .gitthe command to view the changes in the local library:

you can find tagsthat the tags just added are stored in the directory.

If you look at the content of a certain tag, you can find that the so-called tag is actually saved commit id:

8.3 Deletion of local tags

If the label is wrongly typed, you can also delete the label. Use the command to delete the label:

git tag -d [tagname]

For example, to delete v1.1a v1.2tag:


The reason why tags can be deleted is that the created tags are only stored locally and will not be automatically pushed to the remote. Therefore, mistyped tags can be safely deleted locally.

8.4 Pushing tags

If you want to push a label to the remote, the command you need to use is as follows:

 git push origin [tagname]

For example, push v1.0and v0.9to the remote repository:

When the label is pushed successfully, the updated label can be seen in the remote warehouse.

Of course, if there are many local tags, you can also push them all to the remote end at once:

git push origin --tags

8.5 Deletion of remote tags

If the label has been pushed to the remote, it is a little more troublesome to delete the remote label. Delete it locally first:

Then delete it remotely. The same is true for the delete command push, but the format of the command is as follows:

git push origin :refs/tags/[tagname]

For example:

Check the remote warehouse again and you can find that the tag has been successfully deleted.

Guess you like

Origin blog.csdn.net/qq_61635026/article/details/133320507