Note source: Silicon Valley Git tutorial complete version (12h in-depth master Git)

[TOC]

Deep into the Git

1. Version control

What is version control? Why should we care?

Version control is a system that records changes to the contents of one or more files for future reference of revisions to a particular version

Why use version control?

Using a version control system in software development is a wise choice. It allows you to trace a file back to its previous state, or even an entire project back to a point in time. Even if you arbitrarily change and delete files throughout the project, you can easily restore the original status. But the extra work was minimal. You can compare the details of the changes, find out who made what changes last, find out what caused the weird problems, who reported a bug when, and so on.

1.1. Centralized version control system

Centralized version control systems such as CVS, Subversion, and Perforce have a single, centrally managed server that holds revisions of all files, and people who work together connect to this server through a client to retrieve the latest files or submit updates. This has been standard practice for version control systems over the years

There are many benefits to this approach, and now everyone can see to some extent what others on the project are doing. Administrators can easily control the rights of each developer and manage a centralized version control system; It’s much easier than maintaining a local database on each client

There are two sides to a story, good and bad. The most obvious drawback of this approach is the single point of failure of the central server

If the server is down for an hour, no one can commit an update and no one can work together during that hour

This is not to say that there is no way to write code when the server fails, but there is no way to write code when the server fails. Imagine a day when the SVN central server is down, and you’ve been working hard to write code for a day. The code before 12 o ‘clock is high quality and reliable, and has a lot of shine. The code after 12 o ‘clock is completely changed because you want to try a more daring idea. Then all the work you did before 12 o ‘clock is gone. The recorded version can only be the version saved when the SVN server fails.

If the central server’s disks fail and the backup happens not to be done, or is not done in a timely manner, there is a risk of data loss. In the worst-case scenario, all historical changes for the entire project are completely lost, and some locally stored snapshot data accidentally extracted by the client becomes the hope of recovery. But that’s still a problem. You can’t guarantee that all the data has been extracted completely beforehand. As long as the entire project’s history is kept in a single location, there is a risk that all historical updates will be lost

Centralized summary

  • Advantages: Code is kept on a single server for easy project management
  • Disadvantages: The server is down and faulty

1.2 distributed version control system

Distributed version control systems were introduced. In such systems, such as Git and BitKeeper, the client doesn’t just take a snapshot of the latest version of the file, but mirrors the entire repository. This way, a failure of any of the co-operating servers can be later recovered using any of the mirrored local repositories. Because each extraction operation is actually a complete backup of the code repository

Furthermore, many of these systems can specify interactions with several different remote code repositories. This allows you to work with people in different groups on the same project

Distributed version control systems do not manage projects with differences between versions, they manage projects with indexes (disk space is minimal, so each client can put down a history of the entire project)

The emergence of distributed version control systems addresses the shortcomings of centralized version control systems:

  • 1) Development can be done even when the network is off (because version control is done locally)
  • 2) Use Git for team collaboration, even if Github is down, each client will save the entire project (including history!!).

1.3 Comparison between SVN and Git

  • The SVN stores different data each time. Therefore, the hard disk space is smaller, but the rollback speed is slow
  • Git stores a complete snapshot of the project each time, requiring a relatively large amount of hard disk space (although the Git team has done extreme compression of the code, the actual space required is not much more than SVN), but the rollback speed is extremely fast

A brief history of Git

Git is the most advanced distributed version control system in the world. Like many of life’s great events, Git was born at a time of great strife and innovation. The Linux kernel open source project has a large number of participants. The vast majority of Linux kernel maintenance was spent on the tedious task of submitting patches and keeping archives (1991-2002). By 2002, the entire project team had started implementing a distributed version control system, BitKeeper, to manage and maintain the code

In 2005, the commercial companies that developed BitKeeper ended their partnership with the Linux kernel open source community and took back their right to use BitKeeper for free. This forced the Linux open source community (and in particular Linus Torvalds, the creator of Linux) to learn its lesson and develop its own version control system to avoid the same mistakes. They set out a number of objectives for the new system:

  • Fast branch switching speed
  • Small capacity (compression)
  • Simple design
  • Completely distributed
  • Strong support for non-linear development patterns (allowing thousands of parallel development branches)
  • Ability to efficiently manage very large scale projects like the Linux kernel (speed and data volume)

Since its inception in 2005, Git has matured to a level of ease of use while remaining true to its original goals. It is extremely fast, ideal for managing large projects, and has an incredibly non-linear branch management system that can handle complex project development requirements

3. Git initial configuration

On a new system, you need to configure your Git environment first. The configuration work only needs to be done once, and the current configuration will be used for future upgrades. Of course, you can always modify the existing configuration with the same command if necessary.

Git provides a command called Git config to configure or read the corresponding workspace variables. It is these environment variables that determine the specific working mode and behavior of Git in each link. These variables can be stored in three different places:

  • /etc/gitconfigFile: A configuration on the system that is universally applicable to all users. If usegit configWhen using--systemOption to read and write to this file
  • ~/gitconfigFile: The configuration file in the user directory applies only to the user. If usegit configWhen using--globalOption to read and write to this file
  • .git/configFiles: configuration files in the Git directory of the current project, which are valid only for the current project

Each level of configuration overrides the same configuration at the top

The first thing to configure is your personal user name and email address. These two configurations are important because they are referenced every Git commit as to who committed the update and are therefore permanently incorporated into history along with the update:

Git config --global user.email Git config --global user.emailCopy the code

To check existing configuration information, use commands

git config --list
Copy the code

4. Git

4.1. Initialize the new warehouse

  • Command:git init
  • To start Git management for an existing project, simply go to the project’s directory and run the command
  • Effect: After initialization, a directory named.gitGit, where all the data and resources you need are stored. So far, we’ve just initialized all the files and directories in the existing architecture, but we haven’t started tracking any files in the project yet

4.2. Git directory

directory role
hooks The directory contains client-side or server-side hook scripts
info Contains a global exclusion file
logs Saving Log Information
object Directories store all data content
refs Directories store Pointers to submitted objects that point to data (branches)
config The file contains project-specific configuration options
description Displays the description of the warehouse
HEAD The file indicates the branch that is currently checked out
index The file holds staging area information

4.3. Basic Linux commands

clear  # Clear screen
echo 'test content' Output information to console
echo 'test content' > test.txt Output information to a file
ll # Tiled the subfiles & subdirectories in the current directory on the consoleThe find directory name# Tiled the descendant files & descendant directories in the corresponding directory on the consoleFind Directory name -type f # Tiled the files in the corresponding directory on the consoleRm [-rf] Indicates the file name# delete fileMv Source file Renames a file# renameUrl of cat file# Check the contents of the corresponding fileUrl of vim file (in English mode)# Press I to enter insert mode: Edit the file
    # Press Esc & Press: to execute the command
		q! # force exit (not save)
		wq # save exit
		set nu # set the line number
Copy the code

4.4, objects,

  • Git objects: A Git object is a snapshot of a file
  • Tree object: A tree object is a snapshot of the project
  • Commit object: A commit object is a version of the project

4.5, regional

  • The workspace
  • The staging area
  • repository

4.6. Git Objects

At the heart of Git is a simple key-value database. You can insert any type of content into the database, and it returns a key value that can be retrieved again at any time

4.6.1 Write to the database and return the corresponding key

echo 'test content' | git hash-object -w --stdin
# d670460b4b4aece5915caf5c68d12f560a9fe3e4
Copy the code
  • -wOption instructshash-objectCommand to store data objects; If this option is not specified, only the corresponding key value is returned
  • --stdinThe standard input option indicates that the command reads from standard input

If this option is not specified, the path of the file to be stored must be specified at the end of the command

Git hash-object-w Specifies the file path# save fileGit hash-object Specifies the file pathReturn the key value of the corresponding file
Copy the code

Returns: This command outputs a 40-character checksum. This is a SHA-1 hash

4.6.2 How does Git store data

find .git/objects -type f
# .git/objects/d6/70460b4b4aece5915caf5c68d12f560a9fe3e4
Copy the code

Returns: git/objects/d6/70460 b4b4aece5915caf5c68d12f560a9fe3e4

This is how Git originally stored content: one file per content. The first two characters of the checksum are used to name subdirectories, and the remaining 38 characters are used as file names

4.6.3 Pull data according to key values

git cat-file -p d670460b4b4aece5915caf5c68d12f560a9fe3e4
Copy the code
  • -pOption instructs the command to automatically determine the type of content and display us well-formed content

Returns: the content of the corresponding file

4.6.4 Simple version control of a file

Create a new file and store its contents to the database

echo 'version 1' > test.txt
git hash-object -w test.txt
Copy the code

Write new content to the file and save it to the database again

echo 'version 2' > test.txt
git hash-object -w test.txt
# 1f7a7a472abf3dd9643fd615f6da379c4acb3e3a 
Copy the code

Viewing database Contents

find .git/objects -type f
git cat-file -p 1f7a7a472abf3dd9643fd615f6da379c4acb3e3a
git cat-file -p 83baae61804e65cc73a7201a7252750c76066a30
git cat-file -t 83baae61804e65cc73a7201a7252750c76066a30
Copy the code

With the cat-file -t command, you can tell Git to tell us what type of object it stores internally

Question:

  1. It is not practical to remember the SHA-1 value for each version of a file
  2. In Git, the file name is not saved — we only save the contents of the file

Solution: Tree objects

Note: The current operations operate on the local database and do not involve the staging area

4.7. Tree Objects

Tree objects, which solve the problem of file name preservation, also allow us to organize multiple files together. Git stores content in a manner similar to UNIX file systems. Everything is stored as tree objects, which correspond to UNIX directory entries, and data objects (Git objects), which roughly correspond to file contents. A tree object contains one or more records (each record contains a sha-1 pointer to a Git object or subtree object, along with schema, type, and file name information). A tree object can also contain another tree object

We can use update-index; The write – tree; A command such as read-tree to build a tree object and stuff it into the staging area. Suppose we do a bunch of things and we get a tree object

4.7.1 Viewing the temporary storage area

git ls-files -s
Copy the code

4.7.2 Create temporary storage area

1. Run update-index to create the first version of the test. TXT file

git update-index --add --cacheinfo 100644 e32092a83f837140c08e85a60ef16a6b2a208986 test.txt
Copy the code
  • --addOption: Needed for the first time because the file was not in the staging area before--add
  • --cacheinfoOptions: Because the files to be added are in the Git database, not in the current directory--cacheinfo
  • File mode is
    • 100644Indicates that this is a normal file
    • 100755Represents an executable file
    • 120000Represents a symbolic link

4.7.3. Spanning tree Objects

You can run the write-tree command to generate tree objects

git write-tree
Copy the code

The tree object holds a snapshot of the staging area

TXT. Insert the second version of the new. TXT and test. TXT files into the staging area. You can run the write-tree command to generate tree objects

The new new. TXT

Modify the test. TXT

Plug into the staging area

Spanning tree object

Current state of

Object correspondence

.git/objects/0c/1e7391ca4e59584f8b773ecdbbb9467eba1547    # test.txt v2 version
.git/objects/83/baae61804e65cc73a7201a7252750c76066a30    # test.txt v1 version
.git/objects/d8/329fc1cc938780ffdd9f94e0d364e0ea74f579    # V1 version of the project
.git/objects/ea/23032fd52f7aaba1b6cfd81730d709061f556d    # v2 version of the project
.git/objects/ea/e614245cc5faa121ed130b4eba7f9afbcc7cd9	  # new.txt v1 version
Copy the code

3. Add the first tree object to the second tree object to make it a new tree object

git read-tree --prefix=bak d8329fc1cc938780ffdd9f94e0d364e0ea74f579
git write-tree
Copy the code

Current state of

Object correspondence

.git/objects/0c/1e7391ca4e59584f8b773ecdbbb9467eba1547    # test.txt v2 version
.git/objects/83/baae61804e65cc73a7201a7252750c76066a30    # test.txt v1 version
.git/objects/d8/329fc1cc938780ffdd9f94e0d364e0ea74f579    # V1 version of the project
.git/objects/ea/23032fd52f7aaba1b6cfd81730d709061f556d    # v2 version of the project
.git/objects/ea/e614245cc5faa121ed130b4eba7f9afbcc7cd9	  # new.txt v1 version
.git/objects/f2/5275d3da687083ea111caf5d3a4d0f5e2ed796    # V3 version of the project
Copy the code

4.7.4. Parse tree objects

Git creates and records a tree object based on the state represented by the staging area (that is, the index area) at a given time, so that a sequence of tree objects can be recorded by repetition (at a given time)

The tree object is an abstraction of the operation in the staging area, as opposed to a snapshot. When any changes to our workspace are synchronized to the staging area. The write-tree command is invoked

Writes a tree object to the staging area contents using the write-tree command. It automatically creates a new tree object based on the current staging state. That is, each synchronization produces a tree object. And the command returns a hash to the tree object

In Git every file (data) has a hash (type blob) and every tree object has a hash (type tree)

Summary: We can think of a tree object as a snapshot of our project

Problem: There are now three tree objects (three write-trees performed) that represent the different project snapshots we want to track. However, the problem remains: to reuse these snapshots, you must remember all three SHA-1 hashes. Also, you have no idea who saved the snapshots, when they were saved, or why. This is the basic information that a Commit Object can store for you

4.8. Submit objects

We can create a commit object by calling the commit-tree command, specifying the SHA-1 value of a tree object and the commit’s parent (if any, there is no parent when the staging is first taken).

4.8.1. Create a submission object

echo 'first commit' | git commit-tree d8329fc1cc938780ffdd9f94e0d364e0ea74f579
# 7fe5a775aa47939d222518e8e2340ca093a8cf47
Copy the code

4.8.2 Viewing the Submitted Object

git cat-file -p 7fe5a775aa47939d222518e8e2340ca093a8cf47
Copy the code

4.8.3 Format of submitted object

The format of the submission object is simple:

  • Start by specifying a top-level tree object that represents the current project snapshot
  • Then author/submitter information (based on your user.name and user.email configuration, plus a timestamp)
  • A blank line
  • Finally, submit comments

Next, we will create two more commit objects that reference the previous submission (as its parent)

# 7fe5a775aa47939d222518e8e2340ca093a8cf47
echo 'second commit' | git commit-tree ea2303 -p 7fe5a7
# f1108b54c247d0f4455b3857e0ae2db482658237
echo 'second commit' | git commit-tree f25275 -p f1108b
# 665fa8610194e347f7d70ce35cca7487d131a585
Copy the code

Git commit-tree not only generates the commit object, but also commits the corresponding snapshot (tree object) to the local library

graphic

4.9,

Common commands in this section are used

Get data by key
git cat-file -p hash
Get the data type based on the key
git cat-file -t hash
# Check the staging area
git ls-files -s
Copy the code

5, Git local operation (high level command)

5.1 basis,

Git operation basic flow:

  • git initCreating a working directory
  • Modify the working directory
  • git add ./
    • Git hash-object-w Specifies the file name: This command is executed as many times as the files in the working directory are modified
    • git update-index --add --cacheinfo xxx
  • Git commit -m
    • git write-tree
    • git commit-tree

5.2. Initialize the new warehouse

git init
Copy the code

To start Git management for an existing project, simply go to the project’s directory and run the command

After initialization, a.git directory is displayed in the current directory. All data and resources required by Git are stored in this directory. So far, we’ve just initialized all the files and directories in the existing architecture, but we haven’t started tracking any files in the project yet

5.3 Record each update to the warehouse

All files under the working directory are in one of two states: traced or not traced

  • Traced fileFiles that were originally under version control, were recorded in the last snapshot, and after working for some time, their status may beHas been submitted,The modifiedOr temporarily stored
  • All other files belong toUntraced file. They do not have a snapshot from the last update, nor are they in the current staging area

When a warehouse is cloned for the first time, all files in the working directory are traced files and the status is committed. After you edit some files, Git marks them as modified. We gradually put the modified files into the staging area until we finally commit all the staging files at once. The file state change cycle with Git is shown below

5.4. Check the current file status

git status
Copy the code

Effect: Determine what state the file is currently in

5.4.1 Clone the files after the warehouse

If you execute this command immediately after cloning the repository, you will see output similar to this:

On branch master 
nothing to commit, working directory clean
Copy the code

This means your current working directory is pretty clean. In other words, none of the traced files have changed since the last commit

In addition, the above information indicates that there are no new files in the current directory that are not tracked, or Git would list them here

Finally, the command also shows that the current branch is master, which is the default branch name and can actually be changed, so don’t worry about it for now

5.4.2 Files not tracked

If you create a new file called README, save and exit and run git status to see it appear in the list of untracked files:

You can see in the status report that the new README file appears under Untracked Files

Not tracking files means that Git didn’t have them in its previous snapshot (commit)

Git doesn’t automatically track this unless you explicitly tell it, “I need to track this file,” so you don’t have to worry about versioning temporary files, too

5.5. Basic operations

5.5.1 Tracking new files (Temporary storage)

Git add file nameCopy the code

Function: Trace a new file

Run git status again to see that the README file has been traced and is in a temporary state

Changes to be committed is a transient state if it is below this line. If committed at this time, the version of the file at this point in time is retained in history

You can specify the file or directory path to track after Git add. Git Add means that you must recursively track all files in your directory (e.g., passively tracked files).

5.5.2 Temporarily save modified files

Now the README files have been temporarily saved and will be recorded in the warehouse with the next submission. Let’s say at this point, you want to add another comment to your README, re-edit it, save it, and be ready to commit. But wait, run Git status again

README file appears twice! Once calculated has modified, once calculated has temporarily saved, how is this possible?

Well, actually Git only holds the version you were in when you ran Git add. If you commit now, you will be committing the version before you added the comments, not the version in your current working directory. So, if you run git add and then make revisions, you need to run git add again to temporarily save the latest version

5.5.3 View temporary and unstored updates

Git status is a simple list of files that have been modified. You can use git diff to see what changes have been made

This command already solves two of our problems: which updates are currently being made that are not yet stored? What updates have been tabled and are ready for submission next time?

  • What updates are currently being made that have not yet been provisioned? Command:git diff(Direct input without parametersgit diff)
  • What updates have been tabled and are ready for submission next time? Command:git diff --cachedorgit diff --staged(1.6.1 above)
git diff
Copy the code

git diff --cached
git diff --staged
Copy the code

5.5.4 submit updates

When the staging area is ready to commit, make sure there are any changes or new files that haven’t been added to git before you commit

So, before preparing to commit, check with git status to see if everything is temporarily saved, and then run the commit command

git commit
Copy the code

Note: This method launches the text editor to enter a description of the commit. The default commit message contains the output of the last git status run, in the comment line; There is also an empty line at the beginning for you to enter the submission instructions. You can always get rid of these comment lines, but it’s ok to keep them, as they’ll help you remember what’s going on in this update

Alternatively, you can commit the update in a single command with the -m parameter followed by the commit instructions

Git commit -m"message xxx"
Copy the code

At commit time, snapshots are recorded that are placed in the staging area, and any that have not been staging remain in the modified state and can be versioned for the next commit

Each time you run a commit, you take a snapshot of your project that you can return to later or compare

5.5.5. Skip the temporary storage area

While using a staging area can be an elaborate way to prepare your commit details, sometimes it can be a little cumbersome, and Git provides a way to skip the staging area

If you add the -a option to git commit, Git will automatically save all files that have already been traced and commit them, skipping the Git add step

git commit -a
Copy the code

5.5.6. Remove files

To remove a file from Git, you must register deletion from the list of tracked files (specifically, in the staging area) and commit

You can do this with git rm and remove the specified files from the working directory so that they don’t show up in the untracked files list later

Git rmCopy the code

Running git rm is equivalent to running the following two commands

rm README
git add README
Copy the code

5.5.7 Rename the file

Git mv Original file Name New file nameCopy the code

Running git mv is equivalent to running the following three commands

mv test2.txt test.txt
git rm test2.txt
git add test.txt
Copy the code

5.5.8 Viewing Historical Records

After committing a few updates, or cloning a project, you might want to review your commit history. The simplest and most effective tool to do this is the git log command

By default, without any parameters, git log lists all updates by commit time, with the most recent update at the top

As you can see, this command lists the name and email address of the author of each submitted SHA-1 checksum, the submission date, and the submission instructions

The git log parameters

git log --pretty=oneline
git log --oneline
Copy the code

5.6,

Common commands in this section are used

Initialize the local repository
git init
Add temporary storage
git add file
# submit the version library
git commit file
git commit -m "comment" file
git commit -a
git commit -a -m "comment"

Remove the file and store it temporarily
git rm file
Rename the file and save it temporarily
git mv file1 file2

# check status
git status
# Check unsaved
git diff
# check temporary storage
git diff --staged
# check log
git log
git log --pretty=oneline
git log --oneline
Copy the code

6. Git branch operation (killer function)

Almost all version control systems support branching in some form. Using branches means that you can separate your work from the development mainline without affecting it

On many version control systems, this is a slightly inefficient process — it is often necessary to create a complete copy of the source directory

For large projects, this process can take a lot of time

Git’s branching model is extremely efficient and lightweight. Git is a must-have feature, and because of this feature, Git stands out from many version control systems

6.1. Create a Branch

Git branch Specifies the branch nameCopy the code

Action: Creates a new pointer for you to move

Note: Creating a new branch does not automatically switch to the new branch

For example, create a testing branch: Git branch Testing, which creates a pointer to the current submitted object

Create a new branch and point it to the corresponding commit object

git branch name commitHash
Copy the code

6.2. Switch Branches

Git Checkout branch nameCopy the code

Switch to the Testing branch, git checkout Testing

Make changes before submitting

Git checkout master

Note: Branching changes files in your working directory. When switching branches, be aware that files in your working directory will be changed. If you switch to an older branch, your working directory will revert to what it looked like when the branch was last committed. If Git can’t do this cleanly, it will forbid branch switching. Therefore, it is recommended to commit the current branch each time before switching branches

Create and switch branches

Git checkout -bCopy the code

The switch branch moves in three places:

  • HEAD
  • The staging area
  • Working directory

Best practice: Before each branch switch, the current branch must be clean (committed state)

Pit: When switching branches, if there are unpending changes (the first time) or uncommitted staging (the first time) on the current branch, the branch can be successfully switched, but the switch may contaminate other branches

6.3. View branches

  • git branchNot only can you create and delete branches. If you run it without any arguments, you get a list of all the current branches

  • git branch -vYou can view the last commit for each branch

  • git log --oneline --decorate --graph --all: View all branch histories of the project

6.4. Delete branches

  • git branch -d name: Delete branch
  • git branch -D name: Branches are not allowed to be deleted if they have not already been merged. You can use this command to forcibly delete data

conclusion

  • A branch is essentially a commit object
  • HEADIs a pointer, which by default points tomasterbranch
  • When you switch branches, you letHEADPoints to different branches
  • Every time there’s a new submission,HEADWill all move forward with the currently pointed branch

The actual case

workflow

  1. Develop a website.
  2. Create a branch to implement a new requirement.
  3. Work on this branch.

At that moment, you get a phone call saying that there is a serious problem that needs to be fixed urgently. You will handle it as follows:

  1. Switch to your production Branch.
  2. Create a new branch for this urgent task and fix it there.
  3. After the test passes, switch back to the online branch, merge the patch branch, and finally push the changes to the online branch.
  4. Switch back to the branch where you started and continue working.

Git flow

First, let’s assume that you are working on your project and already have some submissions

Now you’ve decided to fix problem #53 in the problem tracking system your company uses. You want to create a new branch and switch to that branch simultaneously

git checkout -b iss53
Copy the code

You continue to work on issue #53 and make some submissions. In this process, the ISS53 branch is constantly advancing because you have checked out the branch

!!!!!!!!! Now you get that call, and there’s an urgent problem waiting for you to solve

With Git’s help, you don’t have to mix the urgent problem with the ISS53 change, and you don’t have to work hard to undo the change about the #53 problem, then add the change about the urgent problem, and finally commit the change to the online branch. All you have to do is switch back to the Master branch

Before you do this, however, keep an eye out for changes in your working directory and staging area that have not yet been committed, which may conflict with the branch you are checking out and prevent Git from switching to that branch. The best way to do this is to keep it clean before you switch branches. (Submit all your changes)

git checkout master
Copy the code

At this point, your working directory is exactly the same as it was before you started #53, and now you can focus on fixing the urgent problem. Keep in mind that when you switch branches, Git resets your working directory to look like it was the last time you committed on that branch. Git automatically adds, removes, and modifs files to make sure that your working directory looks exactly as it did when the branch was last committed

!!!!!!!!! Next, you need to fix this urgent problem. Let’s set up a Hotfix Branch for this urgent problem and work on it until the problem is resolved

git checkout -b hotfix
# Make changes...
git commit -a -m 'fixed the broken email address'
Copy the code

!!!!!!!!! You can run your tests, make sure your changes are correct, and then merge them back into your Master branch to deploy online. You can use git merge to do this

git checkout master
git merge hotfix
Copy the code

Fast forward to merge

When merging, the term “fast-forward” is sometimes used

Since the current master branch points to a commit directly upstream of your current commit, Git simply moves the pointer forward. In other words, when you try to merge two branches, if go down a branch to another branch, so Git in together, will only simple pointer pushed forward (the pointer moves to the right), because there is no need to solve this case, the merging of differences – this is called “fast into the merger”

!!!!!!!!! After the solution to this urgent problem has been released, you are ready to return to the work you were doing before the interruption. However, you should remove the Hotfix branch first, because you don’t need it anymore — the Master branch already points to the same location. You can use the git branch command with the -d option to remove branches. Now you can switch back to the branch you were working on and continue with your work, which is the branch that addressed problem #53

git branch -d hotfix
git checkout iss53
Copy the code

The work you did on the Hotfix branch is not included in the ISS53 branch. If you need to pull hotfix changes, you can use git merge master to merge the master branch into ISS53, or you can wait until ISS53 completes its mission and merge it back into the master branch

git checkout master
git merge iss53
Copy the code

Typical merger

The current merge looks a little different than when you merged the Hotfix branch. In this case, your development history diverged from an earlier place. Git has to do some extra work because the master commit is not the direct ancestor of the ISS53 commit. When this happens, Git does a simple three-way merge using the snapshots indicated at the ends of the two branches (C4 and C5) and the working ancestors of both branches (C2)

Instead of pushing the branch pointer forward, Git takes a new snapshot of the result of the three-way merge and automatically creates a new commit pointing to it. This is called a merge commit, and it is special in that it has more than one parent commit

Git decides which commit is the best common ancestor to use as the basis for merging. This is different from older CVS systems or Subversion (prior to version 1.5), where users had to choose the best merge base. This advantage makes Git much easier to merge than other systems

Iss53 branch is finally deleted

git branch -d iss53
Copy the code

conflict

Sometimes merge operations don’t go so smoothly. If you make different changes to the same part of the same file in two different branches, Git can’t merge them cleanly. If your changes to the #53 problem and the hotfix changes both involve the same place in the same file, merge conflicts will occur when you merge them

Git does merge at this point, but does not automatically create a new merge commit. Git will pause and wait for you to resolve merge conflicts. You can use git status at any time after a merge conflict to view files that are unmerged due to the inclusion of merge conflicts

Any files that have pending resolution because they contain merge conflicts are identified as unmerged

<<<<<<< HEAD:index.html 
       ======= 
       >>>>>>> iss53:index.htmlCopy the code

After you resolve conflicts in all files, use git add for each file to mark it as resolved. Once the conflicting files are temporarily saved, Git marks them as resolved

6.5 Branch mode

Long-term branch (Master)

Many developers who use Git prefer to work this way, such as keeping only fully stable code on the Master branch — possibly only code that has been released or will be released soon. They also have parallel branches called Develop or Next that can be used for subsequent development or stability testing — these branches don’t have to be absolutely stable, but once they are, they can be merged into the Master branch and wait for the next release. The pointer that keeps moving right as you submit. The pointer to the stable branch is always a long way behind in the commit history, while the pointer to the frontier branch is always ahead

Feature Branch (Topic)

Feature branches are appropriate for projects of any size. A feature branch is a short-term branch that is used to implement a single feature or its related work. You may never do this on other version control systems (VCS), where creating and merging branches is often laborious. However, it is common to create, use, merge, and delete branches multiple times a day in Git

6.6 Branch nature

A Git branch is essentially just a mutable pointer to a submitted object. Git’s default branch name is master. After multiple commits, you actually have a master branch that points to the last committed object. It automatically moves forward on every commit

Note: The “master” branch of Git is not a special branch. It’s just like any other branch. The reason almost every repository has a master branch is because git init creates it by default and most people don’t bother to change it

6.7 The Branching principle

The git/refs

This directory holds branches and their corresponding commit objects

The HEAD reference

When you run a command like git branch (branchname), Git takes the sha-1 value of the latest commit from the current branch and adds it to any new branches you want to create. How does Git know the latest committed SHA-1 value when you execute Git Branch (branchName)? The answer is the HEAD file. The HEAD file is a symbolic reference that points to the branch you are currently in. A symbolic reference means that it does not contain a SHA-1 value like a normal reference. It is a pointer to another reference

6.8,

Common commands used in this section

Create a branch from the latest version of the current branch
git branch name
Create a branch from a version of the current branch
git branch name commithash
Create and switch branches
git checkout -b name
# delete branch
git branch -d name
git branch -D name
# View all branches
git branch
# check all branches (-v = --verbose, showing last commit)
git branch -v
View all branch histories
git log --oneline --decorate --graph --all
Copy the code

Git storage

Sometimes, when you’ve been working on one part of a project for a while, everything goes into chaos and you want to switch to another branch and do something else. The problem is, you don’t want to create a commit for a half-done job just because you come back to this point later. The answer to this problem is the git stash command

git stash  The git stash apply command will save the unfinished changes on a stack and you can reapply them at any time.
git stash list  # view storage
git stash apply stash@{2}  If you do not specify a store, Git assumes that the specified store is the nearest one
git stash pop  Apply the store and immediately drop it off the stack
git stash drop  Remove it by adding the name of the storage to be removed
Copy the code

8, alias

Git doesn’t automatically infer the command you want when you type part of it. If you don’t want to enter the full Git command every time, you can easily set an alias for each command using the Git config file

git config --global alias.co checkout git config --global alias.br branch git config --global alias.ci commit git config  --global alias.st statusCopy the code

To type Git commit, just type Git CI

In the example above, we have set up a command alias and used it

git lodga Git log --oneline --decorate --graph --all
Copy the code

Because we are using the –global command, which is defined at the user level, we can view the alias information set in the user’s home directory. Gitconfig

To type git log –oneline –decorate –graph –all, just type git lodga

Git regret medicine

9.1, cancellation

Workspace: How do I undo changes

git checkout -- <file>
Copy the code

It is important to note that git checkout —

is a dangerous command. Any changes you made to that file disappear — you just copied another file to overwrite it. Do not use this command unless you are sure that you do not want the file anymore

Temporary storage area: How to withdraw the temporary storage

git reset HEAD <file>
Copy the code

Version library: How do I withdraw a commit

git commit --amend
Copy the code

This command commits the files in the staging area. If you haven’t made any changes since your last commit (for example, if this command was executed immediately after your last commit), the snapshot remains the same and all you have changed is the commit information. Eventually you will only have one commit — the second commit will replace the result of the first

9.2, the reset

Part one: Move the HEAD

The first thing Reset does is move the HEAD point. Suppose we modify the file.txt file again and commit it a third time

History now looks like this

git reset --soft HEAD~ 
Copy the code

This is different from changing HEAD itself (which checkout does); Reset moves the branch the HEAD points to

Take a look at the image above to understand what’s happening: It essentially undoes the last Git commit command. When you run git Commit, Git creates a new commit and moves the branch that HEAD points to to point to the commit. When you reset it back to HEAD~ (the parent of HEAD), you move the branch back to its original location without changing the index or working directory. Now you can update the index and run Git Commit again to do what Amend does

Part two: Update the staging area

git reset [--mixed] HEAD~
Copy the code

Git reset HEAD~ is equivalent to git reset — -mixed HEAD~

As shown in the figure below

Understand what’s happening: It will still undo the last commit, but it will also cancel staging everything. So we roll back all git add and git commit commands

Step 3: Update your workspace

git reset --hard HEAD~
Copy the code

As shown in the figure below

You undo the last commit, git add and git commit commands, and all the work in your working directory

Note: It is important to note that the –hard flag is the only dangerous use of the reset command, and it is one of the few operations where Git actually destroys data. Any other form of reset call can be easily undone, but the –hard option cannot, because it forces the files in the working directory to be overwritten. In this particular case, the v3 version of the file remains in a commit in our Git database and can be retrieved via reflog. But if the file has not been committed, Git will still overwrite it and make it unrecoverable

9.3. Path reset

The basic behavior of reset was described earlier, but you can also give it a path to use. If a path is specified, reset skips step 1 and limits its scope to the specified file or collection of files. This makes sense, of course, because HEAD is just a pointer and you can’t make it point to both parts of the commit. However, indexes and working directories can be partially updated, so resetting continues with steps 2 and 3. Now, if we run git reset file.txt (this is the short form of git reset –mixed HEAD file.txt), it will:

  • Move the point of the HEAD branch (ignore this step because it is a file)
  • Make the index look like HEAD

So it essentially just copies file.txt from the HEAD into the index

9.4 checkout vs. Reset (no path)

Running git checkout [branch] is very similar to running Git reset –hard [branch], which updates all three to look like [branch], but there are two important differences

  1. First of all, different fromreset --hard.checkoutIt is safe for the working directory, which checks to ensure that it does not lose files that have changed. whilereset --hardThey replace everything completely without checking it
  2. The second important difference is how the HEAD is updated.resetIt moves the direction of the HEAD branch, andcheckoutIt only moves the HEAD itself to point to another branch

For example, suppose we have the Master and Develop branches, each pointing to a different commit; We are now on Develop, and if we run Git reset master, Develop itself will now point to the same commit as the master. If we run Git Checkout Master, develop doesn’t move; the HEAD itself moves. Now HEAD is going to point to master

So, although we moved the HEAD to point to commit A in both cases, the approach was very different. Reset moves the HEAD branch, while checkout moves the HEAD itself

9.5, Checkout vs. Reset (with path)

Git checkout commithash Another way to run checkout is to specify a file path, which like reset does not move the HEAD. Git reset –hard [branch] file. This is not safe for the working directory, it will not move the HEAD and will skip step 1 to update the staging and working directory. Git checkout — not git reset — hard commitHash and file name

9.6. Data Recovery

When you use Git, you may accidentally lose a commit. Usually this is because you forcibly delete a working branch, only to discover that you still need the branch. Or hard reset a branch and give up the commit you want. If these things have happened, how do you retrieve your submission?

The instance

Let’s say you’ve submitted it five times

$ git log --pretty=oneline
ab1afef80fac8e34258ff41fc1b867c702daa24b    modified repo a bit 
484a59275031909e19aadb7c92262719cfcdf19a    added repo.rb 
1a410efbd13591db07496601ebc7a059dd55cfe9    third commit
cac0cab538b970a37ea1e769cbbde608743bc96d    second commit 
fdf4fc3344e67ab068f836878b6c4951e3b15f3d    first commit
Copy the code

Now, we hard reset the master branch to the third commit

$ git reset --hard 1a410efbd13591db07496601ebc7a059dd55cfe9 
HEAD is now at 1a410ef third commit
$ git log --pretty=oneline 
1a410efbd13591db07496601ebc7a059dd55cfe9  third commit 
cac0cab538b970a37ea1e769cbbde608743bc96d  second commit 
fdf4fc3344e67ab068f836878b6c4951e3b15f3d  first commit 
Copy the code

Now the top two commits are missing – there are no branches pointing to those commits. You need to find the last committed SHA-1 and add a branch that points to it. The trick is to find the last submitted SHA-1 – but you probably can’t remember, can you?

The most convenient, and most common, way to do this is to use a tool called Git reflog. Git silently records the value of HEAD every time you change it while you’re working. The reference log is updated every time you commit or change branches

$ git reflog 
1a410ef HEAD@{0}: reset: moving to 1a410ef 
ab1afef HEAD@{1}: commit: modified repo.rb a bit 
484a592 HEAD@{2}: commit: added repo.rb
Copy the code

Git reflog does not display enough information. To make the information more useful, you can run git log -g, which outputs the reference log in a standard log format

restore

It looks like the one below is your lost commit, and you can restore it by creating a new branch pointing to it. For example, you can create a branch named Recover-branch to point to the commit (ab1afef)

git branch recover-branch ab1afef
Copy the code

There is now a branch called Recover-branch where your Master branch used to point, again making the first two commits reachable

9.7,

# undo change
git checkout -- file
Withdraw temporary storage
git reset file  <==>  git reset --mixed HEAD file
# withdraw submission
git commit --amend

# moving HEAD
git reset --soft commithash
Update the staging area
git reset --mixed commithash  <==>  git reset commithash
# Update workspace
git reset --hard commithash

# reference log
git reflog
# reference log (detail)
git log -g
Copy the code

10 and play tag

Git can tag a commit in history as important. Typically people use this feature to mark release points (V1.0, etc.)

10.1 list labels

git tag
git tag -l 'v1.8.5 *'
# v1.8.5 v1.8.5 - rc0 v1.8.5 - rc1 v1.8.5 - rc2 v1.8.5 -rc3 v1.8.5.1 v1.8.5.2 v1.8.5.3
Copy the code

10.2. Creating a Label

Git uses two main types of tags: lightweight tags and annotated tags. Much like a branch that doesn’t change, the lightweight tag is just a reference to a particular submission

Git tag v1.0 git tag v1.0 commitHashCopy the code

An annotation tag is a complete object stored in a Git database. They can be verified; This includes the name, email address, date and time of the labeler; There is also a tag information; It is usually recommended to create a footnote tag so that you have all of the above information; But if you just want to use a temporary tag, or for some reason don’t want to save that information, lightweight tags are also available

Git tag-a v1.4 git tag-a v1.4 commitHash git tag -a v1.4 commitHash -m'my version 1.4
Copy the code

10.3. View specific labels

Git show can display objects of any type

  • Git object
  • The tree object
  • Submit the object
  • Tag object

git show tagname
Copy the code

10.4. Remote Labels

By default, git push does not transfer tags to remote repository servers. After creating the tag you must explicitly push the tag to the shared server. You can run

git push origin [tagname]
Copy the code

If you want to push many tags at once, you can also use git push with the –tags option. This will transfer all labels that are not on the remote warehouse server there

git push origin --tags
Copy the code

10.5. Delete labels

Delete tags To delete tags from your local repository, use the command

git tag -d <tagname>
Copy the code

For example, you can remove a lightweight tag with the following command:

Git tag - d v1.0Copy the code

It should be noted that the above command does not remove the tag from any remote repository, you must use it

git push <remote> :refs/tags/<tagname>
Copy the code

To update your remote repository:

Git push origin: refs/tags/v1.4Copy the code

10.6. Check out labels

If you want to see what version of a file a tag is pointing to, use the Git checkout command

git checkout tagname
Copy the code

This makes your warehouse “detacthed HEAD” though. In the “split head pointer” state, if you make some changes and then commit them, the label will not change, but your new commit will not belong to any branch and will not be accessible unless the exact commit hash is accessed. So, if you need to make a change — say you’re fixing a bug in an older version — this usually requires creating a new branch:

git checkout -b version2
Copy the code

11. Git features

When you start learning Git, don’t try to compare concepts to other version control systems (Subversion, Perforce, etc.) because you can confuse the actual meaning of each operation. Git is quite different from other version control systems, although it operates in a very similar form of command to save and process information. Understanding these differences will help you make accurate use of the various tools Git offers

11.1. Record snapshots directly instead of comparing differences

The main difference between Git and other version control systems is that Git only cares about whether the file data as a whole has changed, while most other systems only care about specific differences in the file content

Such systems (CVS, Subversion, Perforce, Bazaar, etc.) keep track of which files are updated and what lines are updated each time

Other systems record the specific differences between files in each version

Git does not keep data on these differences. In practice, Git is more like taking snapshots of files that have changed and recording them in a tiny file system. Each time an update is committed, it looks through the fingerprint information of all the files and takes a snapshot of the file, then saves an index pointing to that snapshot. To improve performance, Git doesn’t save the file again if it hasn’t changed. Instead, it links only to the last snapshot saved. Git works like this (save a snapshot of the file with each update)

This is an important difference between Git and other systems. It completely overturns the traditional version control routine, and makes a new design for the implementation of each link. Git is more like a small file system, but it also provides a lot of powerful tools based on it, not just a simple VCS. We’ll look at the benefits of this design later when we discuss Git branch management

11.2. Almost all operations are performed locally

Most operations in Git require only access to local files and resources, not to the Internet. But with CVCS, almost everything requires a network connection. Because Git keeps historical updates of all current projects on your local disk, it is fast to process

11.3. Maintain data integrity at all times

All data is checksumed for content before being saved to Git, and this result is used as the unique identity and index of the data. In other words, you can’t change a file or directory and Git won’t know anything about it. This feature, as Git’s design philosophy, is built at the bottom of the overall architecture. So Git will notice immediately if the file becomes incomplete during transfer, or if the disk is corrupted and the file data is missing. Git uses the SHA-1 algorithm for data validation, which computes a SHA-1 hash of the file’s content or directory structure as a fingerprint string. The string consists of 40 hexadecimal characters (0-9 and A-f) and looks like

24b9da6552252987aa493b52f8696cd6d3b00373
Copy the code

Git’s work depends entirely on these fingerprint strings, so you’ll often see hashes like this. In fact, everything stored in a Git database is indexed by this hash value, not by filename

11.4. Most operations simply add data

Most common Git operations simply add data to the database. Because any irreversible operation, such as deleting data, makes it difficult to roll back or recreate historical versions. In other VCS, it is possible to lose or confuse changes without committing an update, but in Git you don’t have to worry about losing data once you commit a snapshot, especially if you get into the habit of regularly pushing to other repositories. This kind of high reliability makes our development work a lot of peace of mind, even if we do all kinds of experimental attempts, no matter how can we lose the data

11.5 Three states of the file

For any file, there are only three states in Git (the state outside Git is a normal file) :

  • Committed: Committed indicates that the file is safely stored in the local database
  • Modified: Modified indicates that a file has been modified but has not been committed for saving
  • Staged: Staged means to put a modified document into a list to be saved the next time you commit it

Git manages projects in three work areas for file transfers:

Git’s working directory, staging area, local repository !!!!

Git workflow

Each project has a Git directory (.git), which is where Git holds metadata and object databases. This directory is so important that every time a mirror repository is cloned, the data in this directory is actually copied

  1. Modify some files in the working directory

    A) Pull all the files and directories from a version of the project to start work on it is called the working directory. These files are actually extracted from a database of compressed objects in your Git directory and can then be edited in your working directory

  2. A) The staging area is just a simple file, usually in a Git directory. This file is sometimes referred to as an index file, but the standard term is still the staging area

  3. If you have a specific version of a file in your Git directory, you are in the committed state. If you have a specific version of a file in your Git directory, you are in the committed state. If it has been modified and put into the temporary storage area, it belongs to the temporary storage state; It is modified if it has not been placed in the staging area since it was last fetched

13. What is remote warehouse

To be able to work as a team on any Git project, you need to know how to manage your own remote repository. A remote repository is a repository of versions of your projects that are hosted on the Internet or other networks. You can have several remote repositories, some of which you can read only and some of which you can read and write. Collaborating with others involves managing remote warehouses and pushing or pulling data as needed. Managing remote repositories includes learning how to add remote repositories, remove invalid remote repositories, manage different remote branches and define whether they are tracked, and so on

13.1. Basic process of remote collaboration

GitHub is the largest repository for Git releases and a hub where thousands of developers and projects can collaborate. Most Git repositories are hosted on GitHub, and many open source projects use GitHub for Git hosting, problem tracking, code reviews, and more. So, while this is not a direct part of Git open source projects, you will inevitably have to deal with GitHub if you want to use Git professionally

Address: github.com/ After successful registration, there is a mail must be important!!

The project manager creates the remote repository

By clicking the “New Repository” button on the right side of the panel, or the + button next to your username in the top toolbar. Click and the “New Repository” form will appear:

All fields here are optional except for a project name that you must fill in. Now just click the “Create Repository” button, Duang!! — You now have a new repository on GitHub named

/

Because there is currently no code available, GitHub displays instructions for creating a new repository or associating with an existing Git repository

Now that your project is hosted on GitHub, you can share the URL with whomever you want. Projects on GitHub can be accessed via HTTP or SSH in the following format:

  • HTTP:https://github.com/<user>/<project_name>
  • SSH:[email protected]:<user>/<project_name>

Git can be fetched and pushed through the above two urls, but the user’s access rights vary depending on the certificate used to connect

Generally, http-based urls are preferred for public projects, because user clones do not need to have a GitHub account. If you share SSH urls, the user must have an account and upload an SSH key to access your project. The HTTP URL is the same address that you post to your browser to view the project

The project manager creates the local library

git init
Copy the code

The project manager configures alias & user information for the remote repository

Add a new remote Git repository and specify a shorthand that you can reference easily

git remote add <shortname> <url>
Copy the code

Displays the Git alias used by the remote repository and its corresponding URL

Git remote - vCopy the code

View more information about a remote repository

git remote show [remote-name]
Copy the code

rename

git remote rename pb paul
Copy the code

If you want to remove a remote repository for some reason – you have moved it off the server or no longer want to use a particular image, or a contributor no longer contributes

git remote rm [remote-name] 
Copy the code

Project managers push local projects to remote repositories

Initialize a local repository and then:

git push [remote-name] [branch-name]
Copy the code

Push the master branch of the local project to the Origin server

Member clone remote warehouse to local

git clone url  Git init is not required for cloning
Copy the code

The default clone alias for the remote repository is Origin. The name of the remote repository “Origin” is the same as the name of the branch “master”, which has no special meaning in Git

While “master” is the default starting branch name when you run Git init, simply because it’s widely used, “Origin” is the default remote repository name when you run Git Clone. If you run Git clone -o booyah, your default remote repository alias will be Booyah

The project manager invites members to join the team

If you want to collaborate with others and want to give them committed permissions, you need to add them as “properties”. If Ben, Jeff, and Louise are all registered on GitHub and you want to give them push privileges, you can add them to your project. This gives them “push” access, meaning they have read and write access to the project

Click the “Settings” link at the bottom of the sidebar

Then select “Properties” from the menu on the left. Then, fill in the user name in the input box and click “Add Collaborator.” If you want to delegate to more than one person, you can repeat this step multiple times. If you want to revoke permissions, click the “X” to the right of their line.

Member pushes commit to remote repository

git push [remote-name] [branch-name]
Copy the code

This command will only work if you have write permission to the clone server and no one has pushed it before. When you clone at the same time as someone else, and they push upstream and then you push upstream, your push will be rejected without question. You have to pull their work down and merge it into your work before pushing it

Project manager updates content submitted by members

git fetch [remote-name] 
Copy the code

This command accesses the remote repository and pulls any data from it that you don’t already have. Note that git fetch pulls data to your local repository – it does not automatically merge or modify your current work. You must manually incorporate it into your work when it is ready

git merge [remote-name]
Copy the code

13.2. In-depth understanding of remote libraries

13.2.1. Remotely trace branches

The remote trace branch is a reference to the state of the remote branch. They’re local branches that you can’t move. When you do any network communication, they move automatically

They are named in the form (remote)/(branch). For example, if you want to see the status of the Master branch when you last communicated with the remote repository Origin, you can look at the Origin/Master branch

When cloning a repository, it usually automatically creates a Master branch that tracks the Origin /master

Suppose you have a Git server on your network at git.ourcompany.com. If you clone from here, Git’s clone command will automatically name it Origin for you, pull all its data, create a pointer to its master branch, and name it origin/master locally. Git will also give you a local master branch that points to the same place as the Origin/Master branch, so you have something to work from

If you do some work on your local master branch, and at the same time someone else pushes a submission to git.ourcompany.com and updates its Master branch, your commit history will go in a different direction. As long as you are not connected to the Origin server, your Origin/Master pointer will not move

To synchronize your work, run git fetch Origin. This command finds which server “Origin” is (in this case, git.ourcompany.com), grabs data from it that is not available locally, and updates the local database by moving the Origin /master pointer to the new, updated location

13.2.2 Push other branches

When you want to share a branch publicly, you need to push it to a remote repository that has write permission. Local branches are not automatically synchronized with remote repositories – you must explicitly push the branch you want to share. This way, you can put content that you don’t want to share on the private branch, and push content that requires collaboration to the public branch

If you want to work with others on a branch called Serverfix, you can push it as you push the first branch

git push origin serverfix
Copy the code

Some of the work here has been simplified. Git serverfix branch name automatically will unfold as refs/heads/serverfix: refs/heads/serverfix

You can also run Git Push Origin Serverfix: Serverfix and it will do the same thing – equivalent to saying, “Push the local serverfix branch as the serverfix branch of the remote repository

git push origin serverfix:awesomebranch
Copy the code

If you do not want the branch on the remote repository to be called serverfix, you can run the command above to push the local serverfix branch to the awesomebranch on the remote repository

git fetch origin
Copy the code

The next time another collaborator grabs data from the server, they generate a remote trace branch origin/ Serverfix locally, a reference to the serverfix branch of the server

It is important to note that when a new remote trace branch is captured, an editable copy (copy) is not automatically generated locally. In other words, in this case, there will be no new Serverfix branch – just an origin/ Serverfix pointer that cannot be modified

git merge origin/serverfix 
Copy the code

You can merge this work into your current branch by running Git Merge Origin/Serverfix. If you want to work on your own Serverfix branch, you can build it on top of the remote trace branch

git checkout -b serverfix origin/serverfix  # (Other collaborators)
Copy the code

13.2.3 Trace branches

Checking out a local branch from a remote trace branch (Origin /master) automatically creates a “trace branch” (sometimes called “upstream branch” : master). Trace branches are automatically created only when the primary branch is cloned

Trace branches are local branches that are directly related to remote branches. If you type Git pull on a trace branch, Git automatically identifies which server to fetch and which branch to merge into. You can set up other trace branches if you want, or not trace the master branch

git checkout -b [branch] [remotename]/[branch] 
git checkout -b serverfix origin/serverfix
Copy the code

This is a very common operation, so Git provides the –track shortcut

git checkout --track origin/serverfix
Copy the code

If you want to set the local branch to a different name than the remote branch

git checkout -b sf origin/serverfix
Copy the code

To set up an existing local branch to track a remote branch that just pulled down, or to change a trace branch that is being traced, you can run Git Branch explicitly at any time using the -u option

git branch -u origin/serverfix  # (- set - upstream - to)
Copy the code

View all trace branches set up

git branch -vv
Copy the code

The ISS53 branch is tracking origin/ ISS53 and “ahead” is 2, meaning there are two local submissions that have not been pushed to the server. The Master branch is tracking the Origin/Master branch and is up to date. The Serverfix branch is tracking the Server-fix-good branch on the TeamOne server and is 3 ahead and 1 behind, meaning that one commit on the server has not been merged and three local commits have not been pushed. The Testing branch does not track any remote branches

It’s important to note that the values for these numbers come from the last time you fetched data from each server. This command does not connect to the server, it only tells you about locally cached server data. If you want to count the latest leading and trailing numbers, you need to grab all remote warehouses before running this command. You could do it like this

Git fetch --all Git branch -- vvCopy the code

13.2.4. Delete the remote Branch

git push origin --delete serverfix  # delete remote branch
git remote prune origin --dry-run  # list useless branches that are still being tracked remotely but have been removed remotely
git remote prune origin  Clear the remote trace listed in the command above
Copy the code

13.2.5 Pull Request process

If you want to participate in a project but don’t have push privileges, you can “Fork” that project. The derivative means that GitHub will create a copy of your project in your space that you can push. This way, project managers no longer need to be busy adding users to the contributor list and giving them push privileges. People can derive the project, push their changes to the derived copy of the project, and get their changes into the source repository by creating a Pull Request

Basic process:

  1. Create a new branch from the Master branch (own fork project)

  2. Commit some changes to improve the project (fork your own project)

  3. Push the branch to GitHub (own fork project)

  4. Create a merge request

  5. Discussion, according to the actual situation continue to modify

  6. The project owner merges or closes your merge request

Note: Every time you launch a new Pull Request, Pull the latest source repository, not the repository you fork.

13.2.6, SSH,

Ssh-keygen -t rsa -c Your email addressGenerate public and private keys
ssh -T [email protected]  Test whether the public and private keys have been paired
Copy the code

.ssh file location: C:\Users\ administrator.ssh

13.3,

  • During cloning, a master branch and the corresponding remote trace branch origin/ Master are automatically generated
  • Create another branch that can specify a trace remote branchGit checkout --track Tracks branches remotely
  • If the existing branch has not traced the remote branch, passGit branch -u Remote trace branchTo track the remote branch