Summary of the Git | ① What is a version management system | ② Differences between Git and SVN |
③ Four components of Git | ④ Several states of files in Git | |
⑤ Four classes of objects in Git | ||
Git download installation configuration | ||
Git local basic operations | (1) configuration”git config“ | ② Get help”git help“ |
Create Git repositorygit init“ | ||
④ Add file to temporary storagegit add“ | ||
⑤ Let Git not track specific files”. Gitignore file“ | ||
⑥ Submit the contents of temporary storage area to local warehouse”git commit“ | ||
⑦ Check the status of working area and temporary storage areagit status“ | ||
⑧ Content change, difference comparison”git diff“ | ||
⑨ Viewing Historical Submission Recordsgit log“ | ||
⑩ Check the change records of a file.git blame“ | ||
Alias Git commandgit config –global alias“ | ||
Follow-up labelling of important submissionsgit tag“ | ||
Git file recovery and version rollback | ① File restoration without adding”git checkout“ | |
② File restore, add but not commitgit reset HEAD“ | ||
③ Version rollback, commit”git reset –hard“ | ||
④ Check the input command record”git reflog“ | ||
⑤ Withdraw a submission”git revert“ | ||
⑥ Viewing the submitted changesgit show“ | ||
⑦ Check the Hash value of the latest branch commit.git rev-parse“ | ||
The last hope of retrieving the lost objectgit fsck“ | ||
Git local branch | ① The concept of branches | ② The reason for creating other branches |
③ A simple branch management strategy | ||
④ Branch is created in switch”git branch“ | ||
⑤ Branch mergergit merge“V”git rebase“ | ||
⑥ Resolve merge conflicts | ⑦ Delete branch | |
Restore the branch deleted by mistake.git log –branches“ | ⑨ Branch was renamed | |
⑩ Store uncommitted changes temporarily when switching branches.git stash“ | ||
“Change the commit from one branch to another”git cherry-pick“ | ||
Git remote repository | ① Overview of remote warehouse | |
② Association between local warehouse and remote warehousegit remote“ | ||
③ Push local warehouse to remote warehousegit push“ | ||
④ Clone remote warehousegit clone“ | ||
⑤ Synchronize remote warehouse updategit fetch“V”git pull“ | ||
Where are the suggestions for git push | ||
⑦ SSH Key Avoid repeatedly entering the account password for each push | ||
Git workflow | Centralized workflow | ② Functional branch workflow |
③ Gitflow workflow | ④ Forking workflow | |
⑤ Pull Request workflow | ||
Other miscellaneous | ① Contribute code to open source projects | ② SourceTree usage details |
Overview of Git — Distributed version control Systems
Understanding Git related concepts helps you master the following commands
1. What is a version management system
Version Control System (VCS) : a System that records the history of changes in one or more files so that historical records of a specific Version can be viewed, modified, and backed up. Can be a simple analogy for “game save”, before the Boss save file, not pass, re-read file; Branch story, want to experience different choices trigger different story, can save multiple files, want to play which read which.
VCS fall into the following three categories:
- 1. The local VCS
Use a simple database to record historical update differences of files, such as RCS.
- 2. Centralized VCS
A server is used to hold revisions of all files, and people working with it connect to this server to retrieve or submit updates to files, such as SVN.
This collaborative approach has two obvious disadvantages: 1. “Networking” : synchronization and update push speed is limited by bandwidth, the internal network is fine, but the external network may be a little slow (large files); 2. 2. “Dependent on central server” : everyone only has the previously synchronized version locally. If the server goes down (dang), no one can get or submit updates.
- 3. Distributed VCS
Each user has a complete commit history, support offline commit changes, view historical commit records, etc. The central server is more of a tool for change merging and synchronization, such as Git.
Git is basically a memory-addressed file system that locates files based on their Hash value. This 40-bit Hash value is generated using the SHA1 algorithm and is concatenated with two parts: header = ”
” + content.length + “\0”. Object type, length of data bytes, null bytes (used to separate header and content) Hash = sha1(header+ Content), where the concatenation is binary level concatenation, not string concatenation.
2. Differences between Git and SVN
Git and SVN have different storage requirements:
The SVN is concerned about: specific differences in file contents; Git cares if the file as a whole has changed. The SVN submits a record of which files are modified and which lines and contents are modified.
As shown, Version 2 records changes to files A and C, while Version 3 records changes to file C, and so on. And Git, don’t keep these differences in data before and after the transformation, but to save the entire all the files in the cache area, also called a snapshot, “haven’t change a change file, file without saving, but the last saved a snapshot of a link”, because this kind of preserved in different ways, making a lot quicker than the SVN switch Git branch.
Of course, SVN also has its advantages, such as “permission control”, you can set the read and write permissions for each account, while Git has no responsive permission control. As for which, or to see the company requirements ~
3. Four components of Git
Git has four components:
- Workspace: The entire project directory does not include the.git folder. All changes are made in the workspace.
- Temporary area: also known as index area. After a local file is modified, the add operation will add the changes of the workspace to the cache.
- Local repository: When a COMMIT operation is performed, the staging data is logged to the local repository.
- Remote repository: a server that hosts project code and merges and synchronizes code through a remote repository when multiple people collaborate.
Here’s how these parts work together:
Workspace vs. staging: Workspace changes can be committed to staging with git add; You can also use the Git checkout command to overwrite the contents of the current workspace with the contents of the staging area.
Staging versus local repository: You can commit the contents of staging to a local repository by using git commit. Each commit generates a snapshot, numbered with a Hash value. You can restore a snapshot to the staging area using git reset Hash.
Workspace and local repository: Restore a snapshot directly to your workspace by git Checkout snapshot number.
Local and remote repositories: Git push commands can be used to push a commit to a remote repository. In addition, pull the project of a remote repository to the local through Git Clone, or pull the latest content of the remote repository through Git Fetch, and decide whether to merge it into the local repository after checking.
Workspace and remote repository: The collaboration here is typically git pull, where the latest content of the remote host is pulled down and merged directly.
4. States of files in Git
Tracked or Untracked, based on: “Is the file version controlled?”
Flow chart of file status change cycle:
Process brief:
Assume that a project has been added to Git version control
- 1. Create a file. The file is Untracked.
- 2. Run the git add command to add the file to the cache
Tracked
Status or the time when the file has been tracked by version control and it is inStaged
**(temporary) status; - 3. Run the git commit command to commit the file in the staging area to the local repository and the file is in the Unmodified state.
- 4. If you edit the file, the file will change to **
Modified
**(modify) state;
5. Four classes of objects in Git
There are four types of objects in a Git system. Almost all Git operations are performed on these four objects: Blob, Tree, Commit, and Tag. The relationship of the first three is shown in the figure:
Then we will explain these four types of objects in detail:
① Block Object (Blob)
A block of binary data, “only stores file contents”, excluding file names and permissions. Git computes a Hash value based on the contents of the file and stores the Hash value as the file index. This means that only one file with the same file content will be saved, that is, sharing the same Blob object. Git hash-object file name to compute the hash value of the file contents. Git cat-file hash if you know the hash value of a file that has been added to Git, you can also use Git cat-file hash to read the data object. The options are -p (to view the Git object content), -t (to view the Git object type), as shown in the following example:
② Tree Object
Git ls-tree Hash = git ls-tree Hash = git ls-tree Hash
Git cat-file -p hash git cat-file -p
In addition to holding references to block objects, tree objects can also refer to “other tree objects,” thus forming a “directory hierarchy.” Create a test directory, copy a 1.txt file to this directory, commit a commit, and view the contents of the tree object:
Can point to another tree object, this tree object points to another 1.txt file, the tree object solved the filename problem. We also need to know about the person, time and description of the submission by the submission object.
③ Commit object (Commit)
Save the Hash value of the tree object, the Hash value of the parent Commit, and the Commit author, time, and description. Git cat-file**
④ Tag Object (Tag)
An important commit is tagged to indicate that it is important.
- Lightweight tags: Instead of creating a real TAG object, they refer directly to the Hash value of the COMMIT object.
- Attached tags: TAG objects are created, which contain a reference to the commit object, and a.git/refs/tags/ TAG name file is created, which holds the reference to the TAG object.
Here we label our two commits one at a time, and see what happens:
Git download installation configuration
- For Windows, go to Git For Windows or git-for-windows.github.
- Sudo apt-get install git for Ubuntu
- Mac system: go to Installing on Mac to download, but it seems that the new system already has Git by default, in addition, if you have Homebrew installed, you can directly command line type: brew install Git to install.
Git local Basic Operations
1. Configure git config.
After installing Git, you need to configure the environment. The configuration information is stored in the gitConfig file. There are three levels:
- system(System) :All users in the systemConfiguration file:
C:\Program Files\Git\mingw64\etc\gitconfig
, different systems may be different, you can use:git config -e --system
The path to the configuration file can be found at the bottom:
- global(Overall) :It takes effect for the current system user, configuration file:
C:/Users/ current user /.gitconfig
, the above can also be used:git config -e --global
View the location of the configuration file. - local(Local) :The configuration takes effect only for the current project, configuration file:
Project path /.git/config
Run the following command to configure the effective priority: local > global > system
# configuration
git config --global user.name "Username" Configure the user name
git config --global user.email "User email" # configure mailboxGit config --global core.editorConfigure the editor using vi or VIm
# check configuration
git config --global user.name # check the configured user name
git config --global user.email Check the configured mailbox
See the list of configurations
git config --global --list View the global Settings parameter list
git config --local --list View the list of local Settings
git config --system --list View the system configuration parameter list
git config --list Git configuration (global + local + system)
Copy the code
In addition to the command line, you can also directly edit the corresponding configuration file.
2. Get help “git help”
git helpThe commandGit command: git command: git commandThe git command -- help# another way to write it
Copy the code
Create a local repository “git init”
Git init repository nameCreate a new project with a Git repository
git init Create a Git repository for existing projects
Copy the code
4. Add files to the staging area “git add”
Git add file nameAdd a file from the workspace to the staging area.
git add -u Adds information about all files that were modified or deleted from the tracked file to the staging area, does not handle untracked files
git add -A Adds information about all files that were modified or deleted from the tracked file to the staging area, including the untracked file
git add . Add all files from the current workspace to the staging area
git add -i Enter interactive interface mode and add files to cache as needed
Copy the code
For those of you who haven’t used interactive interface mode, here’s how to use it:
Process brief:
- Create two new files in the GitTest folder.
- Type git add -i to go interactive mode, type 4, and select add untracked file;
- To add a file according to the sequence number of the unmarked file, type? Relevant prompts will pop up, directly enter, end the selection;
- Type 4 and you can see that there is no more untracked file.
5. Let Git not Tracked for a particular file “.gitignore file configuration”
When you add an unmarked file to the cache using the git add command, Git starts tracking the file. Git does not need to trace files or folders that are automatically generated, log files, temporary compilations, or application signature files. The. Gitignore file is in the same directory as the. Git folder **.
If you don’t want to write the file yourself, you can go to github.com/github/giti… Select a template and copy and paste it. You can also write your own, support the simplified true expression (specification and sample template from Git king super God path)
*
: Matches zero or more arbitrary characters[abc]
: Matches only any character in parentheses[0-9]
: indicates the range. Matches any character between 0 and 9?
: Matches any character**
: Matches any intermediate directory. For example, A /*/z can match a/z, A/B /z, and A /b/c/ Z
Example template:
# ignore all files ending in.c
*.c
# But stream.c will be tracked by Git! stream.cTODO files in the current folder are ignored. TODO files in other folders are not included
/TODO
Ignore all files in the build folder
build/
# ignore doc/notes.txt, but not include.txt for example: doc/server/arch.txt
doc/*.txt
Ignore all.pdf files in the doc directory
doc/**/*.pdf
Copy the code
One thing to note in particular is !!!!
Configuration. Gitignore only works for files that are not added to version control (files not Tracked)!
Here’s a simple example:
There are two files, A and B, you add them first, and then you configure the.gitignore file not to track these two files, but you will find that it does not take effect at all.
git add A
git add B
Configure not to track A and B
git add .gitignore
Copy the code
Therefore, it is best to add the.gitignore file at the beginning of the project. Of course, even if this happens, there is a workaround. You can clear the marking state by typing the following command, then adding.gitignore and then adding the file:
git rm -r --cached . Clear the version control flag, with. Representing all files or specifying specific files
Copy the code
In addition, if you use the IDEA series code editor, you can install a plugin “.ignore “, manually check the files that do not need to trace, directly generate.gitignore files.
6. Commit the contents of the staging area to the local repository “Git commit”
git commit -m "Submit instructions" Commit staging area contents to the local repository
git commit -a -m "Submit instructions" Skip the cache operation and commit workspace content directly to the local repository
Copy the code
If you don’t add the -m “commit notes”, Git will use your default editor (vi or vim) to write the commit notes. In addition, sometimes you may want to modify the last submission: submit instructions, modify files, etc. :
# merge the staging area with the last COMMIT, generate a new COMMIT and replace the old one. If there is no content in the cache,
Amend to modify the commit description of the last commit.
#
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
# commit use amend! Remember!!
git commit --amend
git commit --amend --no-edit Commit the same as the last commit
Copy the code
7. Check the status of the workspace and cache.
git status View the current state of workspaces and staging areas
git status -s Make the output shorter
Copy the code
8. “Git diff”
git diff # Workspace vs. cache differencesGit diff branch nameRemotes /origin/ branch name
git diff HEAD Difference between workspace and HEAD pointerGit diff Commit ID File pathThe difference between the current and historical versions of a file in the workspace
git diff --stage # Difference between workspace file and last commit (pre-1.6 --cached)Git diff version TAG# View all changes from a versionGit diff A git diff B# compare the difference between branch A and branch B (also supports comparing two tags)Git diff branch A... Branch BCompare the changes made by the two branches after they split
If you only want to count which files were changed and how many rows were changed, you can add the --stat parameter
Copy the code
9. View historical commit records “Git log”
git log Check all commit records (sha-a checksum, author name, email, commit time, commit description)
git log- p - number of timesCheck the number of recent commits
git log --stat A brief display of each committed content change
git log --name-only Display only the list of files that have been modified
git log --name-status Display the list of new, modified, and deleted files
git log --oneline Let the record be submitted as a single line of output
git log- graph - all - online# Graph shows the merge history of branches
git log- the author = author# grep --all--match (grep --all--match)
git log--grep= Filter information# list all submissions that contain filtering information
git log-s Indicates the query content# is similar to --grep, with no Spaces between S and the query content
git log fileName # Check the modification record of a file
Copy the code
In addition, you can customize the submission information with — pretty, for example:
More rules and customizations are listed below (for more, see Viewing the Commit History). Common placeholders for format: (Note: the author is the person who last modified the file, and the committer is the person who submitted the file)
A placeholder | instructions | A placeholder | instructions |
---|---|---|---|
%H |
The full hash string of the commit object | %h |
A short hash string of the submitted object |
%T |
The full hash string of a tree object | %t |
A short hash string for a tree object |
%P |
The full hash string of the parent object | %p |
A short hash string of the parent object |
%an |
Name of the author | %ae |
Email address of the author |
%ad |
Author revision date (can be customized with the -date = option) | %ar |
Display by how long ago |
%cn |
The name of the committer | %ce |
Email address of the submitter |
%cd |
Submission date | %cr |
Submission date, as in how long ago |
%s |
Submit instructions |
Some other operations:
options | instructions |
---|---|
-p |
Shows the differences between each update in patch format |
- the stat |
Display file change statistics for each update (lines) |
- shortstat |
Only the last row number modification in -stat is displayed |
- the name - only |
A list of modified files is displayed only after the information has been submitted |
- the name - the status |
Displays the list of new, modified, and deleted files |
- abbrev - commit |
Only the first few characters of SHA-1 are displayed, not all 40 characters |
- relative to the date |
Use short relative time displays (e.g., “2 weeks ago”) |
- graph |
Displays branch merge history for ASCII graphical representation |
- pretty |
Format customization, options are: oneline, short, Full, Fullerton and format(followed by the specified format) |
There are also options to limit log output:
options | instructions |
---|---|
-(n) |
Only the last n commits are displayed |
- since, - after |
Only commits after the specified time are displayed. |
- until, - before |
Displays only commits prior to the specified time. |
- the author |
Only submissions related to the specified author are displayed. |
- 4-8 |
Displays only the commits associated with the specified submitter. |
- the grep |
Only submissions with the specified keyword are displayed |
-S |
Only submissions that add or remove a keyword are displayed |
10. Check who changed the “Git Blame” file
Git BlameView the author of each line of a file, the latest commit, and the commit time
Copy the code
For example, modify the author username and email address first, then add the contents to 1.txt:
If you’re using an IDEA compiler, right-click the line number and select Annotate to achieve the same effect. Such as:
Git config — global alias
When the Git command is used in the terminal, it can be automatically completed by pressing TAB twice. Create a simple alias for each of these commands, such as status (st) and checkout (co). Commit to ci; Branch is br. The following is an example:
git config --global alias.st status
Copy the code
The Settings for aliases are stored in git configuration files:
12. Tag important commits with “Git Tag”
For some commits, we can Tag them to indicate that the commit is important. For example, we can Tag a commit with a Tag to indicate that the commit is important. When a commit has a problem, we can use the Tag to quickly find the Hash value of the commit and directly switch to the code of this version to find the problem. It’s a lot easier than committing one by one.
There are two types of tags in Git: lightweight tags and additional tags.
Git tag marks the content# Lightweight tags
git tag -aTag content -m"Additional Information" # Attach tag
Copy the code
If you want to TAG a previous commit, you can find the Hash value of the commit and add the -a option, as shown in the following example:
git tag -aMark the content version IDGit tag -a v1.1 bcfed96
Copy the code
Git push does not push tabs to remote repositories by default. If you want to push tabs to remote repositories, you can:
Git push Origin tag contentPush a tag to a remote repository
git push origin --tags Delete all tags that do not exist in the local repository
Copy the code
In addition, there are the following general operations:
Git checkout -b branch name marks the contentCreate a new branch with a TAGGit show tags content# View the information corresponding to the tag
git tag -dMark content# delete the local TAGGit push origin --delete tag# delete remote TAG
Copy the code
Git file recovery and version rollback
1. File restore (not commit)
If you delete a file that has been Tracked with Git directly in your workspace, the file will still be in the staging area:
Git tells you that files in your workspace have been deleted. You have two options: delete cache files or restore deleted files:
Delete files from temporary storage:Git rm File name git commit -m"Submit instructions"
Delete and restore files by mistake (overwrite files in workspace with files in staging area)Git checkout -- file nameGit rm is equivalent to git rm --cached file + rm file
Git Checkout throws out changes to the current workspace!! Unrecoverable!! Be careful!!
Copy the code
“Git reset HEAD”
If the changes have been added to the staging area and you want to restore them, you can run the following command:
Git checkout file nameCopy the code
3. Version rollback (commit)
The file has been committed. If you want to restore the version of the file that was not committed last time, you can:
git reset HEAD^ Restore to the last committed version
git reset HEAD^^ # revert to the last version submitted, that is, multiple ^, and so on
git reset HEAD~3 # can also be directly ~ timesGit reset -- Hard version number# git log check the Hash value, select the first seven digits and roll back the Hash value based on the version
Copy the code
The reset command resets the HEAD pointer to point to another COMMIT. This action may affect the cache, for example:
Git git: -a-b (HEAD, master) Git reset C: git reset C: git reset C: git reset C: Git reset C
Reset provides three optional parameters:
- Soft: just change the HEAD pointer, cache and workspace remain unchanged;
- Mixed: Modify the HEAD pointer, temporary storage content lost, workspace unchanged;
- Hard: The HEAD pointer is changed, the contents of the temporary storage area are lost, and the workspace is restored to its previous state.
4. Check the command record “git reflog”
Git reflog will remember the Hash value of the new commit. For example, Git reset will change to an old commit, and Git log will find that the new commit is missing. Then git reset.
git reflog
Copy the code
Note: Instruction records are not saved forever! Git periodically cleans up objects that are not needed!!
5. Undo a commit “Git Revert”
Sometimes you want to undo a change you made in a commit, using the revert command
git revert HEAD Undo the most recent commitGit revert The Hash value submittedRevoke a commit
Copy the code
Attention!!
Instead of actually undoing the commit, a new commit is generated to overwrite the old commit. Both the revoked commit and the new commit record are saved!! If you don’t believe me, you can type Git Revert HEAD again and see that the changed item has changed back. To put it simply: “Undo is a file change, commit record still exists.”
6. Check the submitted modification “git show”.
Git show Commits the Hash value# check the changes made during a commit
Copy the code
7. Check the Hash value of the latest commit of the branch. Git rev-parse
Git rev-parse branch name# check the Hash value of the branch's latest commit
Copy the code
8. Last hope of retrieving lost object “git FSCK”
If git reflog is not found, you can use git FSCK to find the Hash version of the lost object and restore it.
git fsck --lost-found
Copy the code
Git local branch
1. The concept of branching
Branches are not Git objects, like lightweight TAG objects, and only contain indexes to commit objects. After the branch is updated, the index is replaced with the latest COMMIT, and the index does not change after the TAG object is created. Branch files are saved in the following two paths:
- The local branch:
Current project /.git/refs/heads/
- Remote branch:
Current project /.git/refs/remotes/
When it comes to branches, you’ll inevitably mention HEAD, which points to the “local branch you’re working on” file: current project /.git/HEAD
Here are some examples and diagrams to help you understand the branches:
Do the same, submit twice:
You can see the pattern in the diagram above: Each commit, the master moves forward to the latest commit. At this point, some kids might ask: Where did the arrow between commit come from? Or how does a commit string a line?
A: Remember the commit object you introduced in the beginning? There is a parent value that points to the Hash value of the parent commit.
2. Reasons for creating other branches
Two common scenarios illustrate the need to create additional branches:
- Scene 1:
The project is generally upgraded step by step iteratively, with big and small version updates: the big version is generally a face-change update, such as UI overhaul, architecture overhaul, version is: V2.0.0; Small version of the update is generally UI minor changes, Bug fixes and optimization, version is: V2.0.11 so; There is only one master branch, which means that your branch line is very, very long. If you have released the second major version and users report that the first major version has a serious BUG, then you want to go back to the first version to fix the BUG, and then after fixing the BUG, you want to go back to the second major version. I can tag an important commit and then find the tag and cut it back.
- Scene 2:
If there is only one master branch, if a commit conflict occurs and the conflict is difficult to resolve or cannot be resolved, the development is stuck and cannot move forward.
3. A simple branch management strategy
To solve the problem of having only one master branch, we can introduce branch management. The simplest strategy is as follows:
Create a new Develop branch on the Master branch, and then create another branch on the Develop branch, depending on its functionality or business, and merge that branch into the Develop branch! You can delete the develop branch and TAG it with the Master branch once the release is complete.
Both the Master and Develop branches are treated as permanent branches, while other created branches are treated as temporary branches! Briefly describe the division of branches:
- Master branch: Code that can be used directly for a product release
- Develop branch: a branch of daily development where people on the team work on development
- Temporary branches: A branch created for a specific purpose, such as a feature branch, a pre-release branch, or a fixbug branch. When the purpose is complete, merge the branch into the Develop branch and remove the branch so that the common branches in the repository are always only: Master and Develop two long branches!
4. Branch creation and switch “Git Branch”
Git branch Specifies the branch nameCreate a branch
git branch # View local branches
Copy the code
We create a Develop branch on the Master branch and the version line looks like this:
Now that the Develop branch has been created, HEAD still points to master, so let’s switch branches:
Git Checkout branch name# Switch branchesGit checkout -bCreate a branch and switch to this branch
Copy the code
After switching to Develop and committing once, the version line will look like this:
Commit again, then switch to the master branch with the version line:
After switching back to master, commit once, now version line:
All right, now that I’m done, I believe you have some knowledge of the branches in Git.
Git merge vs. Git rebase
Git merge you can use Git merge and Git rebase to merge branches.
Git merge Merges branches
There are two ways of merging: quick merging and ordinary merging. The difference between the two is that “the former cannot be seen to have been merged before, and the history of the latter will have branch records”, as shown in the figure:
Git does not create any new commits, but simply points the current branch to the merged branch. To demonstrate a quick merge, execute git reset to switch to the fourth commit, and then execute Git Merge Develop to merge the master branch.
For common merge, add ** — no-ff** to disable quick merge.
In other cases, there are many commit records in the merged branch that do not need to be represented in the branch, and a single COMMIT is sufficient. Commits can be compressed using the **–squash** parameter as shown in the following example:
Git merge
git merge -ff # Fast merge, default parameter
git merge -ff-only # Merge only in case of quick merge
git merge --no-ff # Do not use fast mergeGit merge -n branch name# merge branches do not display different states after the mergeGit merge -stat branch name# merge branches, display the different states before and after the merge
git merge -eBranch name# merge branches, call the editor before merge, write your own COMMIT
Copy the code
Git fetch + git merge
Git reabse merge branches
Rebase, which many tutorials on the web write inscrutable, is not really that complicated, but this combination makes the tree neat and easy to track. Using the result in 4 above as an example, first reset the Master and Develop branches to the latest COMMIT.
Merge: merge
Then try the rebase merge:
Git cancels each commit and temporarily saves it as a patch. For example, after some conflict resolution, new commits are generated, and the old ones are discarded and collected by Git’s GC, resulting in a straight tree.
6. Resolve merge conflicts
When merging branches, it is not always possible to merge directly, and sometimes merge conflicts occur, especially when multiple people are working together. After a merge conflict occurs, the conflict must be resolved before the merge can continue.
For A simple example, A and B create two branches on the master branch to perform related functions. When A is done, the master branch merges its branch into the master branch. The master branch then moves forward A few times to commit. If the file changed is the same as the file changed by A, the merge will fail, and then the conflict needs to be resolved before the merge can continue!
Let’s do a simple merge simulation. Merge:
Merge branch post-processing conflicts
Git status = git status = git status = git status
You can see two unmerged files, 1.txt and 2.txt, open one of them:
<<< and >>> are wrapped with conflicting content, keep what you want, delete <<< and >>> after processing, modify:
2. TXT file also do the same, then add, then commit, end merge.
Rebase branch post-handling conflicts
As shown in the figure, A is merged successfully, while B is merged, there is A merge conflict, there are three optional operations:
git rebase --continue Move on to the next patch after handling the conflict
git rebase --abort Discard all conflict handling and restore the pre-Rebase situation
git rebase --skip # Skip the current patch and process the next patch. This is not recommended.
Copy the code
Type git status to view conflicting files:
After resolving the conflict in the 1.txt file, type git add and git rebase –continue to handle the next conflict:
Handle subsequent conflicts until there are no more:
You can see that with the Rebase merge, the final branch line is a straight line. Git rebase –abort can be used to restore the state before rebase.
7. Delete the branch
The merged branch, which is basically useless, can be deleted using the following command:
git branch -dBranch nameUncommitted changes on a branch cannot be deletedGit branch -d Specifies the branch nameForcibly drop the branch, even though there are uncommitted changes on the branch
Copy the code
8. Restore the mistakenly deleted branch
Two steps: find the Hash value of the latest commit of the deleted branch and restore the branch:
git log --branches="Deleted branch name" Find the latest commit version of the deleted branchGit branch branch name# restore the deleted branch
Copy the code
9. Temporarily store uncommitted changes to “git Stash” when switching branches
Sometimes we may be on a branch is to write the code, and then there are some sudden situation, we need to temporarily switch to the other branches, such as emergency bug fixes, branch or switch to a colleague review code, at this time if the switch directly branch will be prompted to switch failure, because the branch changes has not yet been submitted, You can just add and commit, and then switch, but we’re used to writing something before committing, and we thought:
Save the changes on this branch, cut off the others, and then come back and continue writing the code on the previous changes.
Then you can use:
git stash Save the current changes
Copy the code
Then switch to the branch without worrying about it, then switch back again, and use:
git stash apply Restore save changes
Copy the code
Another point must be paid attention to!! Can stash multiple changes!! If you switch to another stash branch and then switch back stash apply is a stash that reverts to another stash branch!! If you have this stash multiple times, I recommend you type:
git stash list # Look at the Stash list
Copy the code
Find the one you want to restore
For example, you can restore the stash on the master using the following command:
git stash apply stash@{1}
Copy the code
10. Rename branches
Git branch -m Old branch name New branch name# Branch rename
Copy the code
11. Put a commit from one branch to another “git cherry-pick”
Git cherry-pick: Git cherry-pick: git cherry-pick: git cherry-pick: git cherry-pick
Master branch: A -> B -> C Feature branch: A -> B
Now if you want to add b on the feature branch to the master branch, you can do as follows:
- Step 1: Switch to the feature branch and git log to get the version number (SHA1) of B commit.
- Go to the master branch and type git cherry-pick.
Git remote repository
1. Overview of the remote warehouse
In the actual development process, it is basically in the form of team collaboration, that is, many people are responsible for the same project, so how to share the same code and manage it? You can use Git remote repository. You can build your own, or choose a professional CODE hosting platform, such as: Github, Git@OSC, GitCafe, GitLab, Coding.net, GITC, BitBucket, Geakit, Douban CODE, etc. Of course, if there are conditions, certainly is their own build some cool, controllable, but also can do some custom (integrated compilation, robot remind, etc.), simple point can try “Gogs”, playability can try “GitLab”.
2. Associate local repository with remote repository “Git remote”
Create a new project repository on Github, which will generate the corresponding repository link, such as:
Type the following command to associate:
Git remote add Origin Specifies the remote repository addressCopy the code
You can then type the following command to view the association:
git remote # list remote branches that already exist
git remote -v Check the address of the remote repository
Copy the code
3. Push local repository to remote repository “Git push”
Once the association is established, you can use git push to push local changes to a remote repository
git push -u origin master
Copy the code
The -u parameter is used for the first commit to associate the local master branch with the remote master branch (setting the default remote host). This parameter is not required for subsequent commits.
In addition, if you want to change the remote warehouse address, you can run the following command:
Alter remote warehouse address directly
git remote set-url origin Specifies the url of the remote warehouseYou can also delete Origin and add it later
git remote rm origin Delete the warehouse associationGit remote add Origin Specifies the remote repository addressAdd a warehouse association
Copy the code
You can also directly modify the config file in the.git folder to replace the circled location:
One more thing: “Origin” is not a fixed thing, just an alias for the warehouse address!! It can be written as something else, and then you can also set up multiple warehouse associations with different alias flags, such as:
git remote add github https://github.com/coder-pig/SimpleTea.git
git remote add osc [email protected]:coder-pig/SimpleTea.git
Copy the code
4. Clone “git clone”
After pushing the project to a remote repository, other developers can clone the project locally using the git clone command
git cloneThe warehouse addressClone the project to the current folder
git cloneWarehouse address Directory nameClone the project to a specific directory
Git clone creates the master branch with the git clone command.
git checkout -t origin/dev
# This command is equivalent to
git checkout -b dev origin/dev
In addition, you can also:Git fetch Origin Remote branch: local branch# new branch will be created locally, but will not automatically switchGit branch --set-upstream Remote branchCreate a link between the local branch and the remote branch
Copy the code
5. “Git Fetch” vs. “Git pull”
There are two methods for retrieving remote repository updates: fetch and pull. Briefly explain the differences between the two methods:
- git fetch
Just get the latest version locally from a remote server. If you don’t merge, the local workspace doesn’t change! For example, create a readme. md file on Github and call Git Fetch to get updates to the remote repository.
- git pull
Git pull = merge readme. md on Github
Git fetch is safer. After all, when you merge, you can check the update status and decide whether to merge or not.
6. Where are the suggestions for git push
After creating a new project on Github, create a readme. md or other file in the repo and associate it with the local repository. Push to origin/master was rejected Push to origin/master was rejected refusing to merge suggested histories, where the two warehouses are different, can be resolved using the following command:
git pull origin master --allow-unrelated-histories
Copy the code
Alternatively, you can be rude and use the local repository to “force overwrite the remote repository”, but with caution!! If something goes wrong, you can only see if someone else’s computer has the original local repository to restore!!
git push -f origin # Caution!!
Copy the code
7.SSH Key Avoid reentering the password for each push
Private projects using Https pull or push require authentication of the account and password, which is a bit cumbersome. If you want to avoid repeated input, you can use SSH. Secureshell(SSH) is used to secure remote login sessions and other network services. Data transmitted through SSH can be compressed to speed up transmission. SSH is preferred for security and speed. SSH security authentication rules are classified into two types: password – based and key – based. Pub and private key (ID_RSA), and then paste the public key content to the SSH keys in the remote repository Settings, thus establishing the local and remote authentication relationship. The procedure for configuring an SSH Key is as follows:
- The SSH key has not yet been created.
If you have entered a password, you will still need to enter a password for push. The SSH key has been created successfully. The SSH key has been created successfully. You can then open the id_rsa.pub file with an editor or copy the contents by typing:
clip <id_rsa.pub
Copy the code
Open Github, click your profile picture, select: Settings, then click left SSH Keys, and then New SSH Key
Github will then send you an email asking you to create a new SSH key. Ignore it and type:
**ssh -T [email protected]**
Copy the code
Then enter a password if it has been set, otherwise just type Yes and keep pressing Enter! SSH key configuration is successful.
If you want to manage multiple SSH-keys on one computer, you can go to:
Git Gleanings: Multi-SSH-Key Management on one Machine
0x6 Git Workflow
Git Workflows and Tutorials there is a great article on Github about Git Workflows and Tutorials that I won’t go into.
1. Centralized workflow
Similar to SVN, but with A master branch and A bunch of people on that branch, like little A and little B:
- 1. The project manager initializes the repository and then pushes it to the remote repository
- 2. Clone the remote warehouse project to the local PC
- 3. Little A and Little B finish their respective work
- Git push origin master will push the code to the remote repository
- 5. After little B finished, the code was pushed to the remote warehouse, and there was a file modification conflict
- 6. B needs to resolve the conflict first, git pull — rebase origin master, then rebase slowly
- 7. Git push Origin master will push the code to the remote repository after B resolves the conflict
2. Functional branch workflow
Compared with centralized partial flow, only branches are not only master, but new branches are created according to the function, as shown in the following example:
- Git branch -b new-feature git branch -b new-feature
- 2. Xiao A wrote related new functions in new-feature, and he could push this branch to the remote warehouse
- 3. After the function is complete, launch a pull request to merge the new-feature into the master branch
- 4. The warehouse administrator can view the changes made by User A, make some comments, and ask user A to make some changes. Then, user A can initiate A pull request or pull the pull request to the local computer for modification.
- 5. Add the new feature branch to the master and delete the new feature branch
Note: The warehouse manager here is the person who has the warehouse management authority
3. Gitflow workflow
In fact, the functional branch workflow provides some specifications. See “A Simple Branch Management Strategy” above for a general process.
4. The Forking workflow
Distributed workflow, where each developer has his or her own repository, contributes code frequently to open source projects, forks the project to his or her own remote repository, makes changes, and then pulls the request to the source repository, where the repository manager can decide whether to merge.
5.Pull Request workflow
Similar to the Forking workflow, Pull Requests is a feature on Bitbucket that facilitates collaboration between developers
0x7 Miscellaneous Items
1. Contribute code to open source projects
You can Clone someone else’s open source project. When you look at someone else’s code, you think the author wrote something wrong or wrong, or you have a better idea. After local changes, you want to push the changes to the open source project, but you cannot push the changes directly. There are two ways to participate in open source projects:
-
Method 1: Allow the author to add you as the author and add Collaborators by clicking Settings of the repository → Properties then enter the user name or email address of the person you want to add, and click Add.
-
Method 2: Click the Fork button, Fork the project to your own account, Clone it to local, make the changes you want to make, commit, and push it to your own repository, open the open source project, click, create a new “Pull Request”, and set your repository as the source repository. Set the source branch, target repository, and target branch, and then the title and description of the pull request. The author of the open source project will receive a pullRequest and review it. If the author thinks the code is ok after the review, he can click the Merge button to merge the pull Request into his project. If the author finds some bugs in your code, He can explain to you through the Pull Request that the merger is allowed only after the xxBUG is fixed. Then you can modify the BUG and submit it. After the change, the reference will enter into the Pull Request, and then the author will review it.
If the author doesn’t close or merge your Pull Request, you can always commit harassment to the main project…
2.SourceTree
Git Git Git Git Git Git Git Git Git Git Git Git Git www.sourcetreeapp.com/, online tutorials are flying everywhere, I also do not paste copy, find a write also good, interested can move to: “with SourceTree easy Git project diagram”.
There will be new updates, to be continued…
Git Git
- Pro Git Chinese version
- Object behind Git