Git usage explained (8)--New and merged branches

Source: Internet
Author: User
Tags version control system git mergetool

New and merged branches

Now let's take a look at a simple example of branching and merging, in which the work flow is generally used in the actual work:

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

Suppose at this point that you suddenly receive a call saying that there is a serious problem that needs urgent repair, you can do it in the following way:

1. Return to the branch that was previously published on the production server. 2. Establish a new branch for this emergency repair and fix the problem in it. 3. After passing the test, go back to the branch where the production server is located, merge the patch branches in, and then push to the production server. 4. Switch to the branch that previously implemented the new requirement and continue working.

New and switching of branches

First, we assume that you are working happily in the project and have submitted several updates (see Figure 3-10).


Figure 3-10. A Brief history of submissions

Now, you decide to fix #53 problem on the problem tracking system. Incidentally, Git works with any particular problem tracking system. In order to explain the problem to be solved, the new branch is named Iss53. To create a new and switch to the branch, run git checkout and add the -b parameters:

git checkout -b iss53Switched to a new branch "iss53"

This is equivalent to executing the following two commands:

$ git branch iss53$ git checkout iss53

Figure 3-11 shows the execution result of the command.


Figure 3-11. A pointer to a new branch was created

Then you begin to try to fix the problem, after several updates have been submitted, the iss53 branch pointer will move forward as it is the current branch (in other words, the current HEAD pointer is pointing forward, as shown in iss53 figure 3-12):

$ vim index.html$ git commit -a -m ‘added a new footer [issue 53]‘

Figure 3-12. ISS53 branches move forward with work

Now you've got an emergency call for the site and need to fix it right away. With Git, we don't need to publish both the patch and the iss53 changes made, and we don't need to take the time to restore those changes before creating and releasing the patch to the server. The only thing you need is to switch back to the master branch.

But before you do, keep an eye out for your staging area or working directory of changes that have not yet been committed and will conflict with the branch you are about to check out to prevent Git from switching branches for you. It 's best to keep a clean working area when switching branches. a couple of ways to get around this problem are described later (called stashing and Commit amending, respectively). All of the changes have been submitted so you can then switch to the master branch normally:

$ git checkout masterSwitched to branch "master"

The content in your working directory is exactly the same as you did before you solved the problem #53, and you can focus on emergency patching. This is worth remembering: Git restores the contents of the working directory to a snapshot of the Commit object it points to when it checks out a branch. It automatically adds, deletes, and modifies files to ensure that the contents of the catalog are exactly the same as when you submitted them.

Next, you need to make an emergency fix. We created an emergency patch branch hotfix to work until it was done (see Figure 3-13):

$ git checkout -b ‘hotfix‘Switched to a new branch "hotfix"$ vim index.html$ git commit -a -m ‘fixed the broken email address‘[hotfix]: created 3a0874c: "fixed the broken email address" 1 files changed, 0 insertions(+), 1 deletions(-)

Figure 3-13. The hotfix branch is differentiated from the point where the master branch is located.

It is necessary to do some testing to make sure that the patching is successful, then go back to the master branch and merge it in, then publish it to the production server. To git merge Merge with a command:

$ git checkout master$ git merge hotfixUpdating f42c576..3a0874cFast forward README |    1 - 1 files changed, 0 insertions(+), 1 deletions(-)

Note that a "Fast forward" prompt appears when merging. Since master the Commit object where the current branch resides is directly upstream of the branch to be merged hotfix , Git simply master shifts the branch pointer right. In other words, if you go down one branch and you reach another, Git will simply move the pointer to the right as it merges the two, because there's no such thing as a single branch of history that needs to be resolved. So this merging process can be called Fast Forward (fast forward).

Now that the latest modification is in the master commit object pointed to by the current branch, it can be deployed to the production server (see Figure 3-14).


Figure 3-14. after merging, the master branch and the hotfix branch point to the same location

After that super-important patch release, you want to go back to the job that was interrupted. Since the current hotfix branch and master both point to the same commit object, the hotfix historical mission has been completed and can be erased. Use git branch the -d options to perform the delete operation:

$ git branch -d hotfixDeleted branch hotfix (3a0874c).

Now go back to work on the #53 repair branch that was not completed previously (Figure 3-15):

$ git checkout iss53Switched to branch "iss53"$ vim index.html$ git commit -a -m ‘finished the new footer [issue 53]‘[iss53]: created ad82d7a: "finished the new footer [issue 53]" 1 files changed, 1 insertions(+), 0 deletions(-)

Figure 3-15. ISS53 branches can continue to advance without being affected.

Don't worry about hotfix the changes to the previous branch that have not been included iss53 in the section. If you do need to include this patch, you can either git merge master merge the Master branch into it, iss53 or wait for it to complete before merging iss53 iss53 the updates in the branch master .

Merging of branches

After the problem #53 related work is complete, you can merge back to the master branch. The actual operation is similar to the previous merge hotfix branch, just go back to the master branch and run git merge the command to specify the branch to merge in:

$ git checkout master$ git merge iss53Merge made by recursive. README |    1 + 1 files changed, 1 insertions(+), 0 deletions(-)

Note that the underlying implementation of this merge operation differs from hotfix the previous incorporation method. Because this time your development history is branching out from earlier places. Because master the Commit object (C4) that the current branch points to is not iss53 a direct ancestor of the branch, Git has to do some extra processing. In this case, Git uses the end of the two branches (C4 and C5) and their common ancestor (C2) to perform a simple three-party merge calculation. Figure 3-16 shows the three commit objects that Git uses to merge with a red box:


Figure 3-16. Git automatically recognizes the best homologous merge points for branch merging.

this time, Git does not simply move the branch pointer right, but instead makes a new snapshot of the three-party merge and automatically creates a Commit object (C6) that points to it(see Figure 3-17). This commit object is very special, it has two ancestors (C4 and C5).

It is worth mentioning that Git can decide for itself which common ancestor is the best consolidation base; This differs from CVS or Subversion (1.5 later), which requires the developer to manually specify the consolidation basis. So this feature makes Git a lot easier to merge than any other system.


Figure 3-17. Git automatically creates a commit object C6 that contains the results of the merge.

Since the results of the previous work have been merged, it is master iss53 useless. You can delete it and close the issue in the problem tracking system.

$ git branch -d iss53
Branch merge when encountering a conflict

Sometimes merging does not work so well. If you modify the same part of the same file in a different branch , Git cannot cleanly bring the two together (logically speaking, this problem can only be ruled by people.) )。 If you modify the part of the modification in the process of solving the problem #53 hotfix , you will get a result similar to the following:

git merge iss53Auto-merging index.htmlCONFLICT (content): Merge conflict in index.htmlAutomatic merge failed; fix conflicts and then commit the result.

Git makes a merge, but does not commit , it will stop waiting for you to resolve the conflict. To see which files conflict when merging, you can use the git status lookup:

$ git statusindex.html: needs merge# On branch master# Changed but not updated:#   (use "git add <file>..." to update what will be committed)#   (use "git checkout -- <file>..." to discard changes in working directory)##unmerged:   index.html#

any files that contain unresolved conflicts are listed in the non-consolidated (unmerged) state . Git will include standard conflict resolution tags in conflicting files, which can be used to manually locate and resolve these conflicts. You can see that this file contains a section similar to the following:

<<<<<<< HEAD:index.html<div id="footer">contact : [email protected]</div>=======<div id="footer">  please contact us at [email protected]</div>>>>>>>> iss53:index.html

You can see the ======= top HEAD half of the partition, which is the content in the branch, the master branch that you merge switch to when you run the command, and the lower part is the content in the iss53 branch. The way to resolve conflicts is to either choose one or you can integrate it yourself. For example, you can solve this by replacing the content with the following:

<div id="footer">please contact us at [email protected]</div>

This solution incorporates a subset of the two branches, and I've also deleted <<<<<<< , ======= and >>>>>>> these lines . after all the conflicts in all the files have been resolved, the run git add will mark them as resolved (in effect, a snapshot is saved to the staging area.) )。 because once staged, the conflict is resolved . If you want to use a graphical interface tool to solve these problems, run git mergetool it, it will call a visual Merge tool and guide you to resolve all conflicts:

$ git mergetoolmerge tool candidates: kdiff3 tkdiff xxdiff meld gvimdiff opendiff emerge vimdiffMerging the files: index.htmlNormal merge conflict for ‘index.html‘:  {local}: modified  {remote}: modifiedHit return to start merge resolution tool (opendiff):

If you don't want to use the default merge tool (Git gives me opendiff the default choice, because I ran the command on my Mac), you can find a list of available merge tools in the "merge tool candidates" above and enter the name of the tool you want to use. We'll discuss how to change the default values in the environment in the seventh chapter.

After exiting the merge tool, Git will ask you if the merge was successful. If the answer is yes, it will save the relevant files for you to indicate that the status has been resolved.

Run again git status to confirm that all conflicts have been resolved:

$ git status# On branch master# Changes to be committed:#   (use "git reset HEAD <file>..." to unstage)##modified:   index.html#

If you feel satisfied, and confirm that all conflicts have been resolved, that is, enter the staging area, you can use git commit to complete the merger submission. The submitted record is almost like this:

Merge branch ‘iss53‘Conflicts:  index.html## It looks like you may be committing a MERGE.# If this is not correct, please remove the file# .git/MERGE_HEAD# and try again.#

If you want to give some convenience to the person who will be looking at this merger, you can modify the information to provide more consolidation details. For example, what changes you have made and why you have done so. Sometimes the justification for the conflict is not straightforward or obvious, and it is necessary to comment slightly.


Management of Branches

So far, you've learned how to create, merge, and delete branches. In addition to this, we also need to learn how to manage the branches, and in future routine work will often use the following management commands.

The git branch command can not only create and delete branches , but if you do not add any arguments, it will give you a list of all the branches that are currently present :

$ git branch  iss53* master  testing

Note master The character of the Zhiqian * : it represents the branch that is currently located. That is, if you commit the update now, the master branch will move forward as the development progresses . To view information about the last commit object for each branch, run git branch -v :

$ git branch -v  iss53   93b412c fix javascript issue* master  7a98805 Merge branch ‘iss53‘  testing 782fd34 add scott to the author list in the readmes

To filter out the list of branches that you have (or haven't) merged with the current branch, you can use the --merged and --no-merged options (Git 1.5.6 or later). For example, git branch --merged see which branches have been merged into the current branch (i.e., which branches are directly upstream of the current branch). ):

$ git branch --merged  iss53* master

We've already merged iss53 , so we'll see it here. In general, branches that are not in * the list can usually be git branch -d deleted . The reason is simple, since the work they contain has been integrated into other branches, and the deletion will not be lost.

You can also git branch --no-merged view work that has not been merged:

$ git branch --no-merged  testing

It shows the branches that have not been merged in. Because these branches also contain work that has not yet been merged , simply git branch -d Deleting the branch will prompt an error because doing so will result in loss of data:

$ git branch -d testingerror: The branch ‘testing‘ is not an ancestor of your current HEAD.If you are sure you want to delete it, run ‘git branch -D testing‘.

However, if you do want to delete the changes on that branch, you can enforce them with the uppercase delete option, as -D indicated in the message above.

Workflow for development with branching

Now that we've learned to create new branches and merge branches, what can (or should) be done with it? In this section, we will describe some of the workflows that are developed using branching. And it is because of the convenience of branch management, it is derived from this kind of typical work mode, you can choose a use to see according to the actual situation of the project.

Long-term Branch

Since Git uses a simple three-party merge, it is not difficult to merge a branch to another branch over a long period of time. That is, you can have multiple open branches at the same time, each of which is used to accomplish a specific task, and as the development progresses, you can move the results of a feature branch to other branches at any time.

Many developers who use Git like to work in this way, such as master keeping completely stable code in a branch , i.e. code that has been published or is about to be released. At the same time, they also have develop a next parallel branch called or, dedicated to subsequent development, or only for stability testing-certainly not necessarily absolute stability, but once in a stable state, it can be merged into master . This allows you to ensure that these completed feature branches (short-term branches, such as previous iss53 branches) pass all tests and that no more errors are introduced, and that you can go to the trunk branch and wait for the next release.

Essentially what we're talking about is a pointer that keeps moving right along with the commit object. The pointer to the stable branch always lags behind in the commit history, while the frontier branch is always relatively front (see figure 3-18).


Figure 3-18. Stable branches are always older.

Or think of them as work lines, perhaps a better understanding of the set of tested submissions to be selected to a more stable pipeline (see figure 3-19).


Figure 3-19. It might be easier to imagine a pipeline.

You can use this to maintain different levels of stability. Some major projects will also have a proposed (recommended) or pu (proposed updates, recommended update) branch, which contains content that may not yet be ripe to next enter master . The goal is to have different levels of stability: when these branches enter a more stable level, merge them into higher-level branches. Again, it is not necessary to use multiple long-term branches, but in general, this is easier to manage for very large projects or for very complex projects.

Feature Branch

Attribute (Topic) branching can be used in projects of any size. An attribute branch refers to a short-term branch that is used to implement a single feature or its associated work. Maybe you've never done anything like this in a previous version control system, because it's often too expensive to create and merge branches. In Git, however, it's common to build, use, merge, and delete multiple branches within a day.

We have seen this usage in the example in the last section. We created a iss53 hotfix branch with these two features, and after submitting several updates, we merged them into the trunk branch and then deleted them. This technology allows you to quickly and completely switch context-because your work is scattered across the pipeline, and the changes in each branch are related to its target characteristics, and things like browsing the code become easier. You can keep the changes you make in the feature branch for a few minutes, a few days or even months, and then merge them when they mature, without caring about the order or the progress they set up.

Now let's look at a practical example. Take a look at Figure 3-20, from the bottom up, at master first we are working to C1, and then start a new branch to iss91 try to repair the 91st defect, submitted to C6, there is a new way to solve the problem, so from the place before C4 branch iss91v2 , to C8, Back in the trunk to master submit the C9 and C10, and then go back iss91v2 to work, submit C11, then, and then came up with a less certain idea, from master the latest submission C10 opened a new branch to dumbidea do some experiments.


Figure 3-20. Has a commit history for multiple attribute branches.

now, let's assume two things: we finally decided to use the second solution, the one iss91v2 in which we showed the branch to our dumbidea colleagues and found it to be a genius. So next, we're going to discard the original iss91 branch (which would actually discard C5 and C6) and merge the other two branches directly into the trunk. The final commit history will turn into figure 3-21 :


Figure 3-21. Merge the branching histories of Dumbidea and Iss91v2.

It is important to keep in mind that these branches are all local branches. When you use branching and merging, everything is done in your own Git repository-it doesn't involve interacting with the server at all.

Git usage explained (8)--New and merged branches

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.