1 the Git configuration

1.1 File Type

  • System-wide profiles, including common configurations for each user and his repository on the system, are locatedGitInstallation directoryC:/Program Files/Git/etc/gitconfig.
  • The user-level configuration file is only applicable to the current user and is located in the user directoryC:/Users/{username}/.gitconfig.
  • A project-level configuration file that applies only to oneGitWarehouse, located under the warehouse directory.git/config.

Git reads configuration files in the sequence of system-level, user-level, and project-level. The configuration at the above three levels overwrites the configuration at the previous level.

1.2 File Operations

1.2.1 view

Git will read the same configuration from different files. In this case, Git will use the last configuration of each variable it finds.

git config -l
Copy the code

View the configurations of different levels. [] indicates different levels.

git config [--system|--global|--local] -l
Copy the code

In the command, user.name indicates a configuration. If no command output is displayed, the configuration does not exist and garbled characters may be displayed in Chinese. Git reads configuration items in the configuration file based on the command path.

git config [--system|--global|--local] user.name
Copy the code

1.2.2 new

Add a configuration item, where section is the configuration node, key is the key under the node, and section.key is added to true.

git config [--system|--global|--local] --add section.key true
Copy the code

1.2.3 editor

Edit different level configuration files, where -e is short for –edit. Git default editor is Vim, enter the editor (default normal mode), enter I to enter insert mode, you can edit configuration information, keyboard arrow keys to control cursor movement, the left mouse button does not take effect. After editing, press ESC or Ctrl + C to enter normal mode and type :w (save), :q (exit), :q! (Forced exit), :wq (Save the configuration and exit.) –local is used by default. You can edit the project level configuration file.

git config [--system|--global|--local] -e
Copy the code

Edit the value of a configuration item. The section node key is set to false.

git config [--system|--global|--local] section.key false
Copy the code

1. Remove

When a configuration item is deleted, the key key of the section node is deleted.

git config [--system|--global|--local] --unset section.key
Copy the code

1.3 User Information

After installing Git, initialize the user name and email address. This information will be used in every Git commit and will be written to every commit without change. Using the –global option means that Git uses this information whenever it does anything on the system (commit, push, etc.). When different user names and email addresses are used for a particular project, they can be configured using the –local option in that project directory.

git config --global user.name username
git config --global user.email [email protected]
Copy the code

1.4 Text editor

Git uses Vim, the default text editor for the operating system, to configure a different text editor, such as VS Code.

git config --global core.editor code
Copy the code

2 the Git command

2.1 Creating a Version library

2.1.1 Directory Initialization

To create an empty directory on Windows, ensure that the directory name (including the parent directory) does not contain Chinese characters. The PWD command is used to display the current directory path.

mkdir gitdir
cd gitdir
pwd
Copy the code

Git init creates a.git subdirectory, which is used by Git to keep track of repositories. Implied file at the beginning.

git init
Initialized empty Git repository in. ls -a ./ .. / .git/Copy the code

You can also initialize the Git repository and track the files in a folder where they already exist (not an empty folder). Track the specified file with the git add command, and then execute the Git commit.

git add --all
git commit -m 'message'
Copy the code

2.1.2 Cloning the Warehouse

Clone an existing Git repository. Using the Git clone command, Git clones almost all the data on the Git repository server. By default, every version of every file in the remote Git repository is pulled down.

git clone https://github.com/username/repo.git
Copy the code

Create a directory called repo in the current directory, initialize a.git folder in the directory, pull all the data from the remote repository into the.git folder, and read a copy of the latest version of the file from there. When cloning a remote repository, run the following command to customize the name of the local repository.

git clone https://github.com/username/repo.git repos
Copy the code

Clone a specific branch of the remote repository, where -b is short for –branch and dev is the branch of the remote repository repo.

git clone -b dev https://github.com/username/repo.git
Copy the code

2.2 the Git operation

2.2.1 staging

Add a single file to the staging area, or mark a file in the unmerged unmerged state as resolved.

git add readme.md
Copy the code

Add multiple files to the staging area.

git add readme.md file.txt
Copy the code

Adds all files in the workspace that are not tracked or modified to the staging area. Git add –all temporarily stores all untracked, modified, or deleted files in any directory. Git add. can only temporarily save all untraced and modified files in the current directory, excluding deleted files.

git add --all 
git add .
Copy the code

2.2.2 Revoke temporary storage

Remove a single file from the staging area.

git reset HEAD readme.md
Copy the code

Remove all files from the staging area.

git reset HEAD
Copy the code

2.2.3 Canceling the Modification

Undo changes to individual files, including files modified or deleted in the workspace.

git checkout -- readme.md
Copy the code

Undo all changes to files in your workspace. Temporary changes will not be undone, that is, they will be back to where they were when the last repository or Git add was made.

git checkout .
Copy the code

2.2.4 delete

To delete a file and add it to the staging area, use git rm readme.md instead of the following command.

rm readme.md
git add readme.md
Copy the code

Git rm will return an error if you run the -for –force option to forcibly delete files that have been modified and have been placed in the staging area. Error reporting is used to prevent accidental deletion of data that has not been added to the repository and that Git cannot recover.

git rm -f readme.md
Copy the code

2.2.5 Abandonment of tracing

Delete files from your Git repository but keep them in your current working directory. Keep files on disk, but don’t want Git to keep track of them.

git rm --cached readme.md
git commit -m 'message'
Copy the code

2.2.6 rename

To change the name of a file, run git mv readme.md file.md instead of the following command.

mv readme.md file.md
git rm readme.md
git add file.md
Copy the code

2.2.7 submitted

If you do not add the -m parameter, the Vim editor will be called to prompt you to enter the submission description.

git commit -m 'message'
Copy the code

The -a option will automatically save and commit all files that have been traced (excluding new ones), bypassing the Git add step.

git commit -a -m 'message'
Copy the code

2.2.8 Version Rollback (Undoable Commit)

Git uncommit can be implemented by rolling back to the previous version of the current repository and running the following command. Where HEAD indicates the current version library, the previous version library is HEAD^^, and the next 100 versions are HEAD~100.

git reset --hard HEAD^
Copy the code

Which version of the library is to be rolled back? –hard indicates the checksum. You don’t have to write the whole checksum, just the first few bits. After you go back to a past version, the Git log can only view all previous commits. To go back to a future version, use Git reflog to view the commit history to get a checksum.

git reset --hard 8b9b5aa
Copy the code

2.2.9 Adding A Submission (Modifying the Submission Information)

If a commit fails to commit some of the unstored changes, some of the changes are committed without being provisioned. You don’t want to generate another commit record, but append it to the previous commit. First, save that part of the change and run the following command to re-edit the commit information. To modify the submission information, run the following command. Note that corrections change the checksum submitted.

git commit --amend
Copy the code

2.3 the Git status

2.3.1 overview

  • Untracked: Not tracked, that is, not trackedGitFiles that are included in version control. Class in a folder where files already exist (not an empty folder)GitWarehouse, this warehouse under all files are not tracked.GitNew files created in the repository are also not tracked.
  • Unmodified: Unmodified, one of the traced states. After cloning a repository, all files in the working directory remain unmodified. The files in the staging area are also committed unmodified.
  • Modified: Modified, one of the traced states. Unmodified Status A file is edited or deleted and is in modified state.
  • Staged: A temporary, traced state. Files that have been modified to be staged are in staged storage.

2.3.2 git status

To see which files are in which state, use the git status command. After cloning the repository, run the following command to prompt that there are no committed files in the master branch and the workspace is clean, that is, all traced files have not changed since the last commit.

git status
On branch master
nothing to commit, working tree clean
Copy the code

Git status prints new files that are not tracked in the workspace. Notice If the. Gitignore file ignores the specified file, git status will not be printed.

git status
On branch master
Untracked files:
  ...
     readme.md
  ...
Copy the code

If the traced file is unmodified, run git status after editing and the file will be marked red modified. If you delete traced files, they will be marked red deleted. Rename or move files, the original name or location file is marked red deleted, and the new name or location file is untracked. Files that collide when different branches make different changes to the same file are marked both modified in red.

git status
On branch master
Changes not staged for commit:
  ...
         deleted:    file.txt
        modified:   index.js
Unmerged paths:
  ...
        both modified:   readme.md
Copy the code

Files that are not traced, deleted, modified or conflicted, renamed or moved after running Git Add are marked green as new file, deleted, Modified, and renamed, respectively.

On branch master
Changes to be committed:
  ...
        new file:   readme.md
        deleted:    file.txt
        modified:   readme.md
        renamed: o.txt -> n.txt
        renamed: location.txt -> file/location.txt
Copy the code

Git status command output is very detailed. Run the following command to view the simplified information, where -s is short for –short. The newly added untraced file is preceded by?? Tags, new files added to the staging area are preceded by an A mark, modified files are preceded by an M mark, and deleted files are preceded by A D mark. M on the right means that the file has been modified but not yet put into the staging area, M on the left means that the file has been modified and put into the staging area, and D is the same. The presence of MM indicates that the file was modified in the workspace after being submitted to the staging area, so there is a record of the file being modified in both the staging area and the workspace.

git status -s ?? . A ... M ... M ... MM ... D ... D...Copy the code

2.3.3 git diff

You can use git diff to modify the output of the git status command. When a workspace changes a file and the change is not pending, diff compares the workspace to the files in the most recent repository. Git diff compares files in a workspace with files in a staging area. Git diff itself only shows changes that have not yet been staging. If the workspace file is modified and provisionally saved for the first time, after the second change, you can run git diff to view the changes that have not been provisionally saved.

git diff
Copy the code

Look for file differences between staging and the last version library, where –staged and –cached are equivalent.

git diff --cached
Copy the code

To view the differences between a workspace and the latest repository, HEAD can be followed by the checksum of a repository, that is, to view the differences between a workspace and a repository.

git diff HEAD
Copy the code

To view the differences between files that were last committed by different branches, –static to view brief differences.

git diff master dev
Copy the code

2.4 the Git log

2.4.1 Common Options

Git log lists all updates by commit time, with the most recent update at the top. Include a checksum for each submission, the author’s name and E-mail address, the submission date, and the submission instructions.

git log
Copy the code

If there are many logs, Git will display them in pagination mode by default. Space can turn the page, Ctrl + B to turn the page, q exit. If not, run the following command to display all logs.

git --no-pager log
Copy the code

Git logs have a number of options to help you find specific commits.

  • -p: Displays between each update in patch formatdiffDifferences can be used for code review
  • --stat: Displays the statistics of line addition and change for each file modification and the statistics of file modification submitted this time
  • --shortstat: Displays the submitted file modification statistics
  • --name-only: Displays each modified file
  • --name-status: Displays each modified file with a modification flag (A,M,DEtc.)
  • --abbrev-commit: Displays a partial checksum
  • --relative-date: Submission time Displays the relative time
  • --graph: Graphically displays branch merge history
  • --pretty: Formats output information, including available optionsoneline(Checksum and submission instructions),short(not including submission time),full(name and email address of author and submitter),fuller(Log appending submitter information),format(Customize the record format to display), the rest can refer toThe official documentation.

2.4.2 Custom Format

If only the submission instructions are displayed, run the following command.

git log --pretty=format:"%s"
Copy the code

Git log –pretty=format git log –pretty=format Author refers to the person who actually makes the changes, and committer refers to the person who finally delivers the work product to the warehouse. When A releases A patch for A project, and then A core member B incorporates A’s patch into the project, A is the author, and that core member B is the committer.

  • %H: Full checksum, submit object hash string
  • %h: Partial checksum
  • %anAuthor:
  • %ae: The author’s E-mail address
  • %ad: Author revision date,--dateOption to customize the time format
  • %ar: Author revision date (relative time)
  • %cn: the submitter
  • %ce: email address of the submitter
  • %cd: Submission date
  • %cr: Submission date (relative time)
  • %s: Submission instructions

2.4.3 Time Format

The current example time is Wednesday 2020/12/15 18:23:13. If only the year is displayed, run the following command:

git log --pretty=format:"%ad" --date=format:'%Y'
Copy the code

The following are common time format placeholders.

  • %c: Formats the output date and timeTue Dec 15 18:23:13 2020
  • %x: Formats a short date12/15/20
  • %X: Formats output for a short time18:23:13
  • %YYear:2020
  • %yYear:20
  • %BIn:December
  • %bIn:Dec
  • %dDate:15
  • %H:24hourly18
  • %I:12hourly06
  • %M: the minute23
  • %S: s13
  • %AWeek:Tuesday
  • %aWeek:Tue
  • %wWeek: (0 ~ 6)3
  • %p: First and afternoon (AM/PM)PM
  • %j: The day of the year350
  • %U: Week of the year (Sunday being the first day of the week)50
  • %W: Week of the year (Monday as the first day of the week)50
  • %: time zone+ 0800

2.4.4 screening

The following command filters author is DonG, time is 2020-12-15 22:20:20, commit information including update, delete or add string cname last 5 commits.

git log --author=DonG --after="The 2020-12-15 22:20:20" --grep="update" -Scname -5
Copy the code

Git filter restrictors are as follows.

  • -n: the most recentnArticle submitted
  • --author: Specifies the author’s submission
  • --committer: Specifies submitter-related commits
  • --after.--since: Commits after the specified time
  • --before.--until: Commits before the specified time
  • --grep: Commits information containing the specified keyword
  • -S: Deleted or added a keyword to the modification

2.4.5 Customizing commands

To configure a custom Git log, run git lg.

git config --global alias.lg "log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset'"
Copy the code

2.5 .gitignore

Some files in your workspace do not need to be managed by Git and do not want to appear in the list of untracked files. You can create a file named.gitignore that lists the file modes to ignore. The format of the.gitignore file is as follows. Note that gitignore can only ignore files that have not been traced before, and does not work if some files have been versioned.

  • All blank lines or#All the leading rows will beGitignore
  • You can use standard onesglobPattern matching
  • /Start by ignoring files in the root directory
  • /End Ignores the specified directory and files in the directory
  • To ignore files or directories outside the specified schema, prefix the schema!The not
*.log # Ignore only TODO files in the root directory of the project, except dir/TODO /TODO # lib.c! Lib. C # ignore doc/ c.mod doc/? Dist / # ignore /foo, a/foo, a/b/foo, etc. **/fooCopy the code

The Glob pattern refers to a simplified regular expression used by the shell.

  • *Matches zero or more arbitrary characters
  • ?Matches only one arbitrary character
  • [abc](aorborcMatches any character in square brackets
  • [0-9](Matches all0to9In square brackets, use an underscore to separate two characters, indicating that anything within these two characters can match
  • use支那Matches any intermediate directory, for examplea/**/zCan matcha/z,a/b/zora/b/c/zEtc.

2.6 Remote Warehouse

2.6.1 view

Look at the remote repositories that have been configured and run Git Remote to print the shorthand for each remote repository. If you have cloned the remote repository, you can at least see the default name Git gave the clone to origin.

git remote
origin
Copy the code

View the associated remote repository shorthand and its URL.

git remote -v
Copy the code

View more details about a remote repository.

git remote show origin
Copy the code

2.6.2 add

Associate a new Git remote repository, where github is short for associated remote repository. Caution The directory where you run the following command must be a Git repository. Otherwise, you cannot associate the directory with the Git repository. Run Git init to initialize the directory and associate the directory with the Git repository.

git remote add github https://github.com/username/repo.git
Copy the code

2.6.3 to remove

Remove a remote repository.

git remote rm origin
Copy the code

2.6.4 rename

To change the shorthand for remote repository, run the following command to rename Origin to Github.

git remote rename origin github
Copy the code

2.7 the label

2.7.1 view

Git lists tags alphabetically by default.

git tag
Copy the code

Use a specific pattern to find labels.

git tag -l 'v1.8.5 *'
Copy the code

View label information and submission information.

git show v18.. 5
Copy the code

2.7.2 create

Git uses two main types of tags, lightweight tags and annotation tags. The lightweight label is just a reference to a single submission. An annotation tag includes the date and time the tag was created, the name of the creator, and E-mail and tag information. The annotation tag is a complete object stored in a Git repository. Run the following command to create a lightweight label.

git tag v18.. 5
Copy the code

When creating an annotation tag, -m specifies the tag information to be stored in the tag. If it is not specified, Git will run an editor asking for the information.

git tag -a v18.. 5 -m 'version 1.8.5'
Copy the code

To create a label for the historical commit record, use the following command with the checksum or partial checksum specified at the end for a commit.

git tag -a v18.. 0 9fceb02
Copy the code

2.7.3 push

Git push does not push the tag to the remote repository. Once the tag is created, it must be explicitly pushed to the remote repository.

git push origin v18.. 5
Copy the code

Push multiple tags at once, using the –tags option.

git push origin --tags
Copy the code

2.7.4 delete

Delete a local label.

git tag -d v18.. 5
Copy the code

If the label has been pushed to the remote repository, delete the local label and run the following command. Git /refs/tags stores all tags information in the.git/refs/tags directory. Git push Origin –delete v1.8.5 can delete tags from remote repositories. If the remote repository branch has the same name as the tag, an error will be reported at runtime.

git push origin :refs/tags/v18.. 5
Copy the code

2.7.5 Creating a Branch

To create a branch that is identical to a tag version in the repository, use the following command.

git checkout -b dev18.. 5 v18.. 5
Copy the code

2.8 the Git alias

If you don’t want to enter the entire Git command every time, you can use Git config to set an alias for each command. Git last is configured to display the last commit information.

git config --global alias.last 'log -1'
Copy the code

3 the Git branch

3.1 an overview of the

Staging the Git will be calculated for each file checksum (SHA – 1 hash, 40 hexadecimal character string, according to the content of the Git file or directory structure calculated), then the current version of the file snapshot (blob object) save to Git repository, will check and added to the staging area for submission.

Git computes the checksum for each subdirectory at commit time, and then saves the checksum as a tree object. Create a submission object that contains author information, submission information, and a pointer to the parent submission object.

The final repository includes several BLOB objects that hold file snapshots, a tree object that records the directory structure and bloB object index, and a commit object that contains Pointers to the tree object and commit information.

Each commit produces a commit object that contains a pointer to the last committed object (the parent object).

A branch is essentially just a mutable pointer to a submitted object. The default Git branch name is master, and Git init init does not have a commit object, so there is no branch. Git automatically creates the master branch after the first commit, and it automatically moves forward with each commit.

Git has a special pointer called HEAD to determine which branch is currently in.

3.2 Local Branch

3.2.1 view

View all branches, where * highlighted in green is the current branch, the branch to which HEAD points.

git branch
Copy the code

View the latest submission information and partial checksum of all branches, where -v is short for –verbose.

git branch -v
Copy the code

Run the following command to view the branches in the list that have not been merged to the current branch. To see which branches are merged to the current branch, run Git branch –merged.

git branch --no-merged
Copy the code

3.2.2 switch

Git switch dev can also switch branches using git switch dev.

git checkout dev
Copy the code

3.2.3 create

Run the following command to create a local branch, where dev is the name of the local branch.

git branch dev
Copy the code

To create and switch branches, run the following command, or run git switch -c dev.

git checkout -b dev
Copy the code

In commit history, specify a commit to create a new branch.

git branch dev 375ea5e
Copy the code

The remote warehouse branch creates the local branch. Note that the local branch created in this way is the trace branch.

git branch dev origin/master
Copy the code

3.2.4 merger

Merges changes from other branches to the current branch, where dev is the branch to be merged into the current branch. If the commit to which the current branch points is directly upstream of Dev, Git simply moves the pointer forward. When trying to merge two branches, Git will simply move the pointer forward (move the pointer right) when merging the two branches, because there is no divergence to resolve in this case, i.e. fast-forward fast-forward.

If the commit of the dev branch is not directly related to the commit of the dev branch, Git will do a simple three-way merge, including the parent commit and the last commit of both branches. A new snapshot is taken of the result of the three-way merge and a new commit is automatically created. This is called a merge commit, and the resulting commit object has two parents.

git merge dev
...
Fast-forward
...
Copy the code

In two different branches, different changes are made to the same part of the same file, resulting in merge conflicts. Git does merge at this point, but does not automatically create merge commit. Git will pause and wait for merge conflicts to be resolved. After a merge conflict occurs, you can run the git status command to view the files that contain merge conflicts and are in the unmerged state.

git merge dev 
...
Automatic merge failed; fix conflicts and then commit the result.

git status
...
Unmerged paths:
  ...
        both modified:   readme.md
Copy the code

Git adds a standard resolution flag to a file that has a conflict. You can open a file that contains a conflict and resolve it manually. Conflicting files may contain special sections, with HEAD, where the current branch’s changes are in the upper part of =======, and dev’s changes in the lower part of =======. To resolve the conflict, you must choose to use one of the two parts divided by =======, or you can merge the contents yourself.

<<<<<<< HEAD
hello world
=======
hi world
>>>>>>> dev
Copy the code

And no < < < < < < <, = = = = = = =, and > > > > > > > tag is removed completely, as long as the conflict between files git add, then mark it as the conflict is solved. Make sure that all the conflicting files have been temporarily saved, you can enter git commit to complete the commit.

Fast forward merging is disallowed and a new commit is generated. Because fast-forward merges mix fragmentary commit histories of dev and mess up the commit histories of the current branch, to generate only one merge record, execute the following command.

git merge --no-ff dev
Copy the code

If the current branch merges a branch dev, but there are too many trivial commits on dev, just one commit record will do. Run the following command to accept all changes on the dev branch, compress them into a single change, apply them to the current branch, and finally temporarily store and commit the changes.

git merge --squash dev
Copy the code

3.2.5 delete

Deleting a branch Run the following command. If a branch contains unmerged changes, the branch cannot be deleted. Run the git branch -d dev command to forcibly delete the branch.

git branch -d dev
Copy the code

3.3 Remote Branch

3.3.1 briefly

A remote branch is a normal branch of a remote repository.

Remote tracking branch (remote-tracking branch) is obtained from the server and named as remote/branch. It is used to tell the user the status of the remote branch that it is tracking (i.e. which submission object it points to). Therefore, the user can only read and cannot move the branch. Automatically moves when communicating with remote warehouses (FETCH, push, etc.).

Tracking branch is a local branch that tracks remote branches. The trace branch is directly related to the remote branch. If you type Git pull on a trace branch, Git automatically identifies which server to fetch and which branch to merge into.

When a repository is cloned, a remote trace branch origin/ Master and a trace branch Master are automatically created.

The trace branch master generates multiple commits and pushes them to the master branch of the remote repository Origin. The remote trace branch Origin/Master automatically moves to the commit.

The remote branch master generates multiple commits. Run git fetch to get the latest commit from the remote branch. The remote trace branch automatically points to the latest commit obtained. Then run Git Merge to merge the latest commit into the trace branch master. Git pull is the same as fetch and merge.

3.3.2 rainfall distribution on 10-12 view

View the list of remote references, which are references to remote repositories, including branches, labels, and so on, where Origin is shorthand for the associated remote repository.

git ls-remote origin
Copy the code

View more information about remote repositories.

git remote show origin
Copy the code

View all remote trace branches.

git branch -r
Copy the code

View all branches. -A is short for –all.

git branch -a
Copy the code

View local and remote branch association information, last commit information and partial checksum, and show each branch tracking which remote branch and local branch are ahead, behind, or both.

git branch -vv
Copy the code

3.3.3 push

To track branch push changes, run the following command and Git automatically identifies which branch to push to the remote repository.

git push
Copy the code

The version of the local repository is earlier than that of the remote repository. Generally, the version is pulled and then pushed. Run the following command to forcibly push the version to overwrite the history of the remote repository. Do not use multiplayer collaboration mode, otherwise it may overwrite other people’s changes. -f is short for force.

git push -f
Copy the code

Push the local branch to the remote repository. HEAD is the current branch, Origin is the abbreviation of the remote repository, and master is the branch of the remote repository. That is, push the current branch to the master branch of origin. If there is no master branch, the system automatically creates the master branch.

git push origin HEAD:master
Copy the code

If the current branch is dev, you can run the following command to push it to the remote dev branch.

git push origin dev
Copy the code

Push the local branch to a remote branch with a different name, as follows: push the local dev branch to the remote Develop branch.

git push origin dev:develop
Copy the code

Push the local branch to trace the remote branch at the same time, where Origin is short for remote repository and master is the local branch.

git push -u origin master
Copy the code

3.3.4 Tracing branches

Create a dev branch to track the dev branch of remote repository Origin.

git checkout --track origin/dev
Copy the code

Customize the local branch name. Dev indicates the local branch name and origin/dev indicates the remote dev branch name.

git checkout -b dev origin/dev
Copy the code

An existing local branch traces a remote branch or modifs a traced remote branch. -u is equivalent to — set-upupstream -to.

git branch -u origin/dev
Copy the code

3.3.5 Canceling Tracing

To cancel tracing a remote branch, run the following command.

git branch --unset-upstream
Copy the code

3.3.6 access

Git automatically retrieves the latest commit from the branch of the remote repository by executing the following command.

git fetch
Copy the code

Gets all updates to the remote repository and has references to all branches in that remote repository that can be merged or viewed at any time.

git fetch origin
Copy the code

Gets updates to a branch of the remote repository.

git fetch origin master
Copy the code

3.3.7 merger

Trace branches Run the following command to automatically merge the latest commit of which remote trace branch Git has.

git merge
Copy the code

The current branch merges the remote trace branch, which pulls the latest data in git fetch.

git merge origin/master
Copy the code

Merge branches that have no common ancestor.

git merge origin/master --allow-unrelated-histories
Copy the code

3.3.8 pull

Git automatically retrieves and merges the latest changes by running the following command to trace the branch.

git pull
Copy the code

Pull and merge updates from a branch of the remote repository.

git pull origin master
Copy the code

Radu has no branches of common ancestry, i.e. merges the history of two separate branches.

git pull origin master --allow-unrelated-histories
Copy the code

3.3.9 delete

To delete the remote branch, run the following command:

git push origin --delete dev
Copy the code

3.4 rebase

3.4.1 track overview

Another way to consolidate changes from different branches is to move all changes committed to one branch to the other, making the commit history a straight line without forks.

The principle is to first find C2, the most recent common ancestor of the two branches (experiment, target master), and then compare the previous submissions of the current branch with ancestor C2 to extract the corresponding modifications and save them as temporary files. Finally, the modifications of temporary files are applied to C3 in sequence to form C4′.

3.4.2 command

To base changes from the current branch to the target branch master, run the following command.

git rebase master
Copy the code

Base changes from the specified branch to the target branch, where dev is the specified branch and master is the target branch.

git rebase master dev
Copy the code

Take the dev branch, find the changes that follow the common ancestor of dev and Develop, and replay them on the Master branch.

git rebase --onto master develop dev
Copy the code

The rebasing process can also cause conflicts, and Git suspends rebasing and tells the user which file is causing the conflict.

Git rebase — Abort cancels the base change and restores the branch state to before calling Git rebase.

Git rebase — Skip the conflicting files. If you use git reflog, you can use git reflog to check some verification and rollback versions.

You can also modify the conflicting files manually by running git add to temporarily store the changes and running git rebase –continue to work on the rest of the base change.

Rule 3.4.3 risk

If you run the base change command on a commit that has been pushed to a public repository, you may get into serious trouble, cause confusion in the commit history, and even discard some changes. Others who previously pulled a common repository commit can either execute the git pull –rebase command or execute the following decomposition command.

Generally, the base-changing command is regarded as a tool to clean up the submission before pushing, and only performs base-changing operation to clear the history of the modification that has not been pushed, and never performs base-changing operation to the submission that has been pushed elsewhere, so as to avoid the trouble caused by base-changing.

git fetch
git rebase origin/master
Copy the code

4 Git multi-repository

4.1 protocol

Git supports multiple transfer protocols, such as https://, Git ://, and SSH.

The local Protocol remote repository is a directory on the hard disk. The advantage is to use the existing file permissions and network access permissions, put the copy of the bare version library in a path accessible to others, and set the read and write permissions. The disadvantage is that it is not convenient to access multiple locations from multiple locations.

The HTTP protocol runs on standard HTTP/S ports and can use various HTTP authentication mechanisms. The advantage is that different access methods need only one URL and the server only prompts for authorization information when authorization is required. The disadvantage is that in some servers to set up HTTP/S protocol server side may be more difficult and more troublesome to manage user credentials, can use credential storage tools.

SSH Is a network protocol that supports read and write operations. It has high security and requires authorization and encryption for data transmission. The disadvantages are that you can’t access the data anonymously and you have to authorize it to read it, which is not good for open source projects.

Git protocol is an inherent network protocol of Git. It has the advantage of no authorization mechanism and saves the cost of encryption and authorization. The downside is that the authorization mechanism is inflexible, so either you can push them all or you can’t push them all.

4.2 Local Version library

A bare repository is initialized in the root directory of drive D. A bare repository is a remote central repository that does not have a workspace and cannot be used to execute Git commands. Git suffix can be added or not. However, most git version libraries add the. Git suffix.

git init --bare repo.git
Copy the code

Clone a local raw warehouse. The cloned warehouse can perform push and pull operations.

git clone D:/repo.git
Copy the code

The first clone of the warehouse in the pull error, push a commit, after the clone of the warehouse pull will not fail.

git pull
Your configuration specifies to merge with the ref 'refs/heads/master'
from the remote, but no such ref was fetched.
Copy the code

Clone a repository as a bare repository, where D:/respos is the local repository path, and repos.git is the bare repository generated after cloning, including historical commit records and file snapshots.

git clone --bare D:/repos repos.git
Copy the code

4.3 HTTP Login Exemption

When you run the following command to verify the user name and password, Git first looks up the credentials from the specified credential manager. If the credentials don’t exist, Git prompts you for the username and password. Then the credential manager records the credentials.

git config --global credential.helper manager
Copy the code

When you run the following command, the username and password are saved in C:/Users/{username}/. Git-credentials in plain text. After the authentication succeeds, the username and password are saved.

git config --global credential.helper store
Copy the code

4.4 the SSH public key

Run the CD ~/. SSH command to switch to the C:/Users/{username}/. SSH folder in the user home directory. If the switch succeeds, run ls to view the files in the folder. After the SSH Key is created, two files id_rsa and id_rsa.pub are displayed.

cd ~/.ssh
ls
id_rsa  id_rsa.pub
Copy the code

If the. SSH folder does not exist or the public key and private key do not exist, run the following command to create one: [email protected] is the personal email address. Press Enter to use the default value.

ssh-keygen -t rsa -C "[email protected]"
Copy the code

Run cat ~/.ssh/id_rsa.pub to view the generated public key.

cat ~/.ssh/id_rsa.pub
ssh-rsa ...
Copy the code

On the remote end, paste the public key content with the title to distinguish the SSH public key. If the “known_hosts” file is not found in the. SSH folder, enter yes to automatically generate the “known_hosts” file. After cloning, the warehouse can be pulled and pushed normally.

git clone [email protected]:username/repo.git
Cloning into 'repo'. . Are you sure you want tocontinue connecting (yes/no/[fingerprint])? yes
Copy the code

5 Distributed Git

5.1 Workflow

5.1.1 Centralized workflow

A central repository with which several developers act as nodes to synchronize.

Use only the Master branch for development.

The general development process is for the developer to clone the master branch to the local, obtain the remote warehouse after the local development is submitted, and then push to the remote warehouse after the local merge occurs in case of conflicts.

Advantage is suitable for small team, simple working mode. The disadvantage is that logs submitted by different developers are mixed, making it difficult to locate problems.

5.1.2 Functional branch workflow

On the basis of centralized workflow, separate functional branches are assigned for different functional development.

The branches are the master branch and several feature function branches.

In the development process, several feature function branches are checked out from the main branch. The developer pushes a function branch to the function branch of the central warehouse after completing a function branch, and then sends a full request request from the function branch of the central warehouse to merge the function branch into the master branch. The code can be reviewed and discussed upon request.

The advantages are more detailed, more flexible and more stable code than centralized workflow function development. The downside is that for large projects, different branches are assigned more specific roles.

5.1.3 Gitflow workflow

There is still a central repository and several developers as nodes, the only difference being the branching structure of the project, with different roles assigned to each branch.

The main branches are Master and Develop, which help branch feature, release and hotfix.

  • masterIs the external release branch. Read-only unique branch, can only fromreleaseandhotfixMerge and cannot be modified. All inmasterThe push of the branch should be marked with the version label
  • developMain development branch. Read-only unique branch, can only be merged from other branches
  • featureFor the function development branch, there can be multiple functions and parallel development at the same timedevelopbranch
  • releaseFor pre-published branches, only fromdevelopBranch check out, check out branch repairbugAfter the merger tomasteranddevelop
  • hotfixBranch for hot update, onlinebugFix branches only frommasterCheck out, check out branch repairbugAfter the merger todevelopandmaster

The main workflow is as follows.

  • Initialize the project, created by defaultmasterBranch,masterBranch detectiondevelopbranch
  • developBranch detectionfeatureBranch, multiple developers check out multiplefeatureParallel development
  • featureBranch development completed, merged todevelopBranch, deletablefeatureBranches that cannot be changed without deletion
  • developBranch detectionreleaseBranch to carry out the test, test outbuginreleaseRepair, repair complete merge todevelopBranches andmasterBranch, merge tomasterBranch, then hit the version label, can be deletedreleaseBranches that cannot be changed without deletion
  • Discover online after onlinebug.masterBranch detectionhotfixbranch
  • hotfixBranch fix test after merge todevelopBranches andmasterBranch, merge tomasterBranch with a repair label, can be deletedhotfixBranches that cannot be changed without deletion

The advantages are clear branch role, clear submission log, easy to locate problems, project stability is very high. The disadvantage is that it is not suitable for small teams, and too many branches make the structure complex.

5.1.4 Forking workflow

Distributed workflow, which takes advantage of Git’s ability to branch and clone. Developers who manage large teams safely and reliably can accept submissions from untrusted contributors.

The main branches are master branch and feature function branch of remote warehouse.

The main workflow is as follows.

  • Derivative (fork) a server’s formal repositoryA, the derived repositoryBAt the remote server.
  • Clone derived remote repositoryBFor local warehouseC(git clone B)
  • For local warehouseCAssociation (git remote add upstream A) Remote formal warehouseAIn order to maintain local warehouses in a timely mannerCAnd formal warehouseASynchronous update of
  • Local repositoryC masterBranch detectionfeaturebranch
  • Local repositoryfeatureBranch to do development work
  • Local repositoryfeatureThe branch completes the development task and gets updates to the formal repository (git fetch upstream master), merge update (git merge upstream/master)
  • Merge complete push locallyfeatureBranch to the remote repositoryB featureBranch (git push origin feature)
  • Remote warehouseBinitiatepull requestThe request will befeatureBranches are merged into a formal repositoryA
  • Formal warehouseAThe maintainer decides whether to merge into a formal code base, one way is directly inpull requestTo view code, compare changes, make comments, and perform merges. If a merge conflict occurs, perform the following two methods, maintaining the local repository to obtain the derived repositoryB featureBranches are modified and merged, and then pushed to the formal repositoryA
git fetch https://github.com/username/B.git feature
git checkout master
git merge FETCH_HEAD
Copy the code

5.2 the picking

5.2.1 command

Pick a commit and then try to reapply it to the current branch. Cherry -pick indicates the checksum submitted for a certain time.

git cherry-pick 9fceb0
Copy the code

Pick multiple commits.

git cherry-pick 9fceb0 1359a9 ceb036
Copy the code

5.2.2 Merge Conflicts

If pick commits D and applies it to F, pick D’s C based patch. I’m going to replay the change in D with respect to C on F.

C -- D <-- dev/A -- B -- E -- F <-- masterCopy the code

Because the pick is the change to the parent object from a single commit, conflicts can occur. If C adds the readme.md file, D modifies the readme.md file, and F does not have the readme.md file, the selection will cause a conflict, because the modification of readme.md cannot be applied to the readme.md file in F. At this point, cherry-pick stops and the user decides what to do.

  • --continue: After the conflict is resolved,git addMark the file as resolved, rungit cherry-pick --continueContinue to perform
  • --abort: Abandoned the merge and resumedcherry-pickBefore the state, namely undocherry-pick
  • --quit: The merge is interrupted. Conflicting files need to be manually resolved. Files that do not conflict are temporarily saved

5.2.3 requires configuration items

Git cherry-pick Common configuration items are as follows:

  • -e: If you want to elect merge the submitted information again after editing it-efor--editshorthand
  • -n: If only the changes of the pick submission are obtained and stored temporarily, no submission record is generated, where-nfor--no-commitshorthand
  • -x: Append a line to the end of the submission information (cherry picked from commit ...), how is query submission generated
  • -s: Appends operator information to the end of the submission (Signed-off-by: ...), which-sfor--signoffshorthand

5.3 Submission Specifications

5.3.1 Writing specifications

The submitted information includes header, body, and footer. Header is required, body and footer can be omitted.

<type>(<scope>): <subject>

<body>

<footer>
Copy the code

Type indicates the submission type, including the following types.

  • featNew features:
  • fixRepair:bug
  • docs: Document modification
  • style: format, modify space indent comma, etc
  • refactor: Code refactoring
  • perf: Performance improvement
  • test: Add missing tests or correct existing tests
  • chore: Changes to the build process or ancillary tools
  • revert: Rollback the version

Scope Indicates the scope of the file or module to be modified. If the scope is large, replace it with *.

A short description submitted by the subject, no more than 50 characters. Start with a verb, use the first person present tense (such as “change” rather than “changed” or “changing”), start with a lowercase letter, and end without a full stop (.) .

Body adds object, generally do not write, modify the cause, purpose and other related factors. Multiple small commits rather than one overcommit.

The footer is not compatible with breaking change, starting with breaking change, followed by a description of the change. Watches #123, #245 can also be turned off in the footer section (watches #123, #245)

feat(doc,core): a short description of the commit

Add object, generally do not write, modify the 
reason, purpose and other related factors.

Closes #123#,245

BREAKING CHANGE: description of changes.
Copy the code

5.3.2 Submitting a Template

Create the gitMessage template file in user directory C:/Users/username.

type(scope): subject
Copy the code

Configure the commit information template under the repository. When git commit, the editor will display the information placeholder in the template.

git config --local commit.template ~/.gitmessage
Copy the code

5.3.3 Specification submission tool

Initialize the NPM and install commitizen and CZ-Conventional – Changelog.

cnpm install commitizen cz-conventional-changelog --save-dev
Copy the code

Initialize the configuration to support Angular’s commit format, where –save-exact locks the version number.

npx commitizen init cz-conventional-changelog --save-dev --save-exact
Copy the code

Package. json Adds the script command.

{..."scripts": {
        	"commit": "npx git-cz"}}Copy the code

Run the script command.

git add --all
npm run commit
Copy the code

5.3.4 Test submission

Git commit is not restricted by the commit specification, installation checks rely on ghook and validate-commit-msg, and references that do not meet the format are blocked.

cnpm install ghooks  validate-commit-msg --save-dev
Copy the code

Configuration package. Json.

{..."config": {
        "ghooks": {
              "commit-msg": "validate-commit-msg"}}}Copy the code

The next article