How to merge branch to master

How to merge branch to master

Basic Branching and Merging

Let’s go through a simple example of branching and merging with a workflow that you might use in the real world. You’ll follow these steps:

Do some work on a website.

Create a branch for a new user story you’re working on.

Do some work in that branch.

At this stage, you’ll receive a call that another issue is critical and you need a hotfix. You’ll do the following:

Switch to your production branch.

Create a branch to add the hotfix.

After it’s tested, merge the hotfix branch, and push to production.

Switch back to your original user story and continue working.

Basic Branching

First, let’s say you’re working on your project and have a couple of commits already on the master branch.

How to merge branch to master. Смотреть фото How to merge branch to master. Смотреть картинку How to merge branch to master. Картинка про How to merge branch to master. Фото How to merge branch to master

This is shorthand for:

How to merge branch to master. Смотреть фото How to merge branch to master. Смотреть картинку How to merge branch to master. Картинка про How to merge branch to master. Фото How to merge branch to master

You work on your website and do some commits. Doing so moves the iss53 branch forward, because you have it checked out (that is, your HEAD is pointing to it):

How to merge branch to master. Смотреть фото How to merge branch to master. Смотреть картинку How to merge branch to master. Картинка про How to merge branch to master. Фото How to merge branch to master

Now you get the call that there is an issue with the website, and you need to fix it immediately. With Git, you don’t have to deploy your fix along with the iss53 changes you’ve made, and you don’t have to put a lot of effort into reverting those changes before you can work on applying your fix to what is in production. All you have to do is switch back to your master branch.

However, before you do that, note that if your working directory or staging area has uncommitted changes that conflict with the branch you’re checking out, Git won’t let you switch branches. It’s best to have a clean working state when you switch branches. There are ways to get around this (namely, stashing and commit amending) that we’ll cover later on, in Stashing and Cleaning. For now, let’s assume you’ve committed all your changes, so you can switch back to your master branch:

At this point, your project working directory is exactly the way it was before you started working on issue #53, and you can concentrate on your hotfix. This is an important point to remember: when you switch branches, Git resets your working directory to look like it did the last time you committed on that branch. It adds, removes, and modifies files automatically to make sure your working copy is what the branch looked like on your last commit to it.

Next, you have a hotfix to make. Let’s create a hotfix branch on which to work until it’s completed:

How to merge branch to master. Смотреть фото How to merge branch to master. Смотреть картинку How to merge branch to master. Картинка про How to merge branch to master. Фото How to merge branch to master

You can run your tests, make sure the hotfix is what you want, and finally merge the hotfix branch back into your master branch to deploy to production. You do this with the git merge command:

You’ll notice the phrase “fast-forward” in that merge. Because the commit C4 pointed to by the branch hotfix you merged in was directly ahead of the commit C2 you’re on, Git simply moves the pointer forward. To phrase that another way, when you try to merge one commit with a commit that can be reached by following the first commit’s history, Git simplifies things by moving the pointer forward because there is no divergent work to merge together — this is called a “fast-forward.”

Your change is now in the snapshot of the commit pointed to by the master branch, and you can deploy the fix.

How to merge branch to master. Смотреть фото How to merge branch to master. Смотреть картинку How to merge branch to master. Картинка про How to merge branch to master. Фото How to merge branch to master

Now you can switch back to your work-in-progress branch on issue #53 and continue working on it.

How to merge branch to master. Смотреть фото How to merge branch to master. Смотреть картинку How to merge branch to master. Картинка про How to merge branch to master. Фото How to merge branch to master

Basic Merging

This looks a bit different than the hotfix merge you did earlier. In this case, your development history has diverged from some older point. Because the commit on the branch you’re on isn’t a direct ancestor of the branch you’re merging in, Git has to do some work. In this case, Git does a simple three-way merge, using the two snapshots pointed to by the branch tips and the common ancestor of the two.

How to merge branch to master. Смотреть фото How to merge branch to master. Смотреть картинку How to merge branch to master. Картинка про How to merge branch to master. Фото How to merge branch to master

Instead of just moving the branch pointer forward, Git creates a new snapshot that results from this three-way merge and automatically creates a new commit that points to it. This is referred to as a merge commit, and is special in that it has more than one parent.

How to merge branch to master. Смотреть фото How to merge branch to master. Смотреть картинку How to merge branch to master. Картинка про How to merge branch to master. Фото How to merge branch to master

Now that your work is merged in, you have no further need for the iss53 branch. You can close the issue in your issue-tracking system, and delete the branch:

Basic Merge Conflicts

Occasionally, this process doesn’t go smoothly. If you changed the same part of the same file differently in the two branches you’re merging, Git won’t be able to merge them cleanly. If your fix for issue #53 modified the same part of a file as the hotfix branch, you’ll get a merge conflict that looks something like this:

Git hasn’t automatically created a new merge commit. It has paused the process while you resolve the conflict. If you want to see which files are unmerged at any point after a merge conflict, you can run git status :

Anything that has merge conflicts and hasn’t been resolved is listed as unmerged. Git adds standard conflict-resolution markers to the files that have conflicts, so you can open them manually and resolve those conflicts. Your file contains a section that looks something like this:

This means the version in HEAD (your master branch, because that was what you had checked out when you ran your merge command) is the top part of that block (everything above the ======= ), while the version in your iss53 branch looks like everything in the bottom part. In order to resolve the conflict, you have to either choose one side or the other or merge the contents yourself. For instance, you might resolve this conflict by replacing the entire block with this:

If you want to use a merge tool other than the default (Git chose opendiff in this case because the command was run on a Mac), you can see all the supported tools listed at the top after “one of the following tools.” Just type the name of the tool you’d rather use.

If you need more advanced tools for resolving tricky merge conflicts, we cover more on merging in Advanced Merging.

After you exit the merge tool, Git asks you if the merge was successful. If you tell the script that it was, it stages the file to mark it as resolved for you. You can run git status again to verify that all conflicts have been resolved:

If you’re happy with that, and you verify that everything that had conflicts has been staged, you can type git commit to finalize the merge commit. The commit message by default looks something like this:

If you think it would be helpful to others looking at this merge in the future, you can modify this commit message with details about how you resolved the merge and explain why you did the changes you made if these are not obvious.

Git: Merge Branch into Master

How to merge branch to master. Смотреть фото How to merge branch to master. Смотреть картинку How to merge branch to master. Картинка про How to merge branch to master. Фото How to merge branch to master

One of Git’s most powerful features is the ability to easily create and merge branches. Git’s distributed nature encourages users to create new branches often and to merge them regularly as a part of the development process. This fundamentally improves the development workflow for most projects by encouraging smaller, more focused, granular commits.

In legacy Version Control Systems (like CVS) the difficulty of merging restricted it to advanced users. Other modern but centralized version control systems like Subversion require commits to be made to a central repository, so a nimble workflow with local branching and merging is atypical.

A commonly used branching workflow in Git is to create a new code branch for each new feature, bug fix, or enhancement. These are called Feature Branches. Each branch compartmentalizes the commits related to a particular feature. Once the new feature is complete – i.e. a set of changes has been committed on the feature branch – it is ready to be merged back into the master branch (or other main code line branch depending on the workflow in use).

Note: Feature branching isn’t the only branching workflow you can go with, but it’s a widely adopted one.

The git branch command is used to list all existing branches in a repository. An asterisk will appear next to the currently active branch.

To create a new branch, we can use the git branch new-branch command. This will create a new branch mirroring the commits on the currently active branch:

As a brief aside, keep in mind that behind the scenes Git does not actually create a new set of commits to represent the new branch. In Git, a branch is really just a tag. It is a label that we can use to reference a particular string of commits. It would be inefficient to duplicate a set of commits behind the scenes, so Git allows us to create multiple diverging sets of commits from a single base.

At this point, commits can be made on the new branch to implement the new feature. Once the feature is complete, the branch can be merged back into the main code branch.

First we run git checkout master to change the active branch back to the master branch. Then we run the command git merge new-branch to merge the new feature into the master branch.

Note: git merge merges the specified branch into the currently active branch. So we need to be on the branch that we are merging into.

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

If you’re merging a new feature into the main branch, you first want to switch to the main branch and then merge into it:

If all goes well then our job is done. The new feature commits now appear in the main branch. However, it is possible that Git won’t be able to complete the merge due to a conflict change in the source branch. This is called a merge conflict.

To summarize, here are the commands to create a new branch, make some commits, and merge it back into master:

About the Author

How to merge branch to master?

Part of GitLab Collective

I do have a local branch with some changes, and I want to merge it to remote master. When I run: git merge master I get:

but I still can see that the master doesn’t contain the new changes.

I checked the following issue Git merge reports “Already up-to-date” though there is a difference Ask, but it seems in one hand to be outdated, and on the other hand, none of the hints there were helpful.

Any idea or hint?

How to merge branch to master. Смотреть фото How to merge branch to master. Смотреть картинку How to merge branch to master. Картинка про How to merge branch to master. Фото How to merge branch to master

4 Answers 4

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

If you want to merge your branch to master on remote, follow the below steps:

How to merge branch to master. Смотреть фото How to merge branch to master. Смотреть картинку How to merge branch to master. Картинка про How to merge branch to master. Фото How to merge branch to master

How to merge branch to master. Смотреть фото How to merge branch to master. Смотреть картинку How to merge branch to master. Картинка про How to merge branch to master. Фото How to merge branch to master

To merge branch with master,there are two ways you can proceed

Git Commands

Here also you can go with two different commands,first is

Second way

Actually this is the more suggested way you can proceed.

Merge branch using GitHub Dashboard

This is most easiest way to merge. Create new pull request, select the branch you want to merge and resolve the conflicts.

How do I safely merge a Git branch into master?

Question 1: Is this the right approach? Other developers could have easily worked on same files as I have worked btw.

A:

B:

Question 2: Which one of these two methods is right? What is the difference there?

The goal in all of this is to keep my test branch updated with the things happening in master and later I could merge them back into master hoping to keep the timeline as linear as possible.

How to merge branch to master. Смотреть фото How to merge branch to master. Смотреть картинку How to merge branch to master. Картинка про How to merge branch to master. Фото How to merge branch to master

15 Answers 15

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

How I would do this

If I have a local branch from a remote one, I don’t feel comfortable with merging other branches than this one with the remote. Also I would not push my changes, until I’m happy with what I want to push and also I wouldn’t push things at all, that are only for me and my local repository. In your description it seems, that test is only for you? So no reason to publish it.

How to merge branch to master. Смотреть фото How to merge branch to master. Смотреть картинку How to merge branch to master. Картинка про How to merge branch to master. Фото How to merge branch to master

This is a very practical question, but all the answers above are not practical.

This approach has two issues:

It’s unsafe, because we don’t know if there are any conflicts between test branch and master branch.

It would «squeeze» all test commits into one merge commit on master; that is to say on master branch, we can’t see the all change logs of test branch.

So, when we suspect there would some conflicts, we can have following git operations:

If conflict is encountered, we can run git status to check details about the conflicts and try to solve

Once we solve the conflicts, or if there is no conflict, we commit and push them

But this way will lose the changes history logged in test branch, and it would make master branch to be hard for other developers to understand the history of the project.

So the best method is we have to use rebase instead of merge (suppose, when in this time, we have solved the branch conflicts).

Following is one simple sample, for advanced operations, please refer to http://git-scm.com/book/en/v2/Git-Branching-Rebasing

Yep, when you have uppers done, all the Test branch’s commits will be moved onto the head of Master branch. The major benefit of rebasing is that you get a linear and much cleaner project history.

The only thing you need to avoid is: never use rebase on public branch, like master branch.

Never do operations like the following:

Основы ветвления и слияния

Давайте рассмотрим простой пример рабочего процесса, который может быть полезен в вашем проекте. Ваша работа построена так:

Вы работаете над сайтом.

Вы создаете ветку для новой статьи, которую вы пишете.

Вы работаете в этой ветке.

В этот момент вы получаете сообщение, что обнаружена критическая ошибка, требующая скорейшего исправления. Ваши действия:

Переключиться на основную ветку.

Создать ветку для добавления исправления.

После тестирования слить ветку содержащую исправление с основной веткой.

Переключиться назад в ту ветку, где вы пишете статью и продолжить работать.

Основы ветвления

Предположим, вы работаете над проектом и уже имеете несколько коммитов.

How to merge branch to master. Смотреть фото How to merge branch to master. Смотреть картинку How to merge branch to master. Картинка про How to merge branch to master. Фото How to merge branch to master

Это то же самое что и:

How to merge branch to master. Смотреть фото How to merge branch to master. Смотреть картинку How to merge branch to master. Картинка про How to merge branch to master. Фото How to merge branch to master

Вы работаете над своим сайтом и делаете коммиты. Это приводит к тому, что ветка iss53 движется вперед, так как вы переключились на нее ранее ( HEAD указывает на нее).

How to merge branch to master. Смотреть фото How to merge branch to master. Смотреть картинку How to merge branch to master. Картинка про How to merge branch to master. Фото How to merge branch to master

Но перед тем как сделать это — имейте в виду, что если рабочий каталог либо индекс содержат незафиксированные изменения, конфликтующие с веткой, на которую вы хотите переключиться, то Git не позволит переключить ветки. Лучше всего переключаться из чистого рабочего состояния проекта. Есть способы обойти это (припрятать изменения (stash) или добавить их в последний коммит (amend)), но об этом мы поговорим позже в разделе Припрятывание и очистка главы 7. Теперь предположим, что вы зафиксировали все свои изменения и можете переключиться на ветку master :

С этого момента ваш рабочий каталог имеет точно такой же вид, какой был перед началом работы над проблемой #53, и вы можете сосредоточиться на работе над исправлением. Важно запомнить: когда вы переключаете ветки, Git возвращает состояние рабочего каталога к тому виду, какой он имел в момент последнего коммита в эту ветку. Он добавляет, удаляет и изменяет файлы автоматически, чтобы состояние рабочего каталога соответствовало тому, когда был сделан последний коммит.

Теперь вы можете перейти к написанию исправления. Давайте создадим новую ветку для исправления, в которой будем работать, пока не закончим исправление.

How to merge branch to master. Смотреть фото How to merge branch to master. Смотреть картинку How to merge branch to master. Картинка про How to merge branch to master. Фото How to merge branch to master

Вы можете прогнать тесты, чтобы убедиться, что ваше исправление делает именно то, что нужно. И если это так — выполнить слияние ветки hotfix с веткой master для включения изменений в продукт. Это делается командой git merge :

How to merge branch to master. Смотреть фото How to merge branch to master. Смотреть картинку How to merge branch to master. Картинка про How to merge branch to master. Фото How to merge branch to master

Теперь вы можете переключиться обратно на ветку iss53 и продолжить работу над проблемой #53:

How to merge branch to master. Смотреть фото How to merge branch to master. Смотреть картинку How to merge branch to master. Картинка про How to merge branch to master. Фото How to merge branch to master

Основы слияния

How to merge branch to master. Смотреть фото How to merge branch to master. Смотреть картинку How to merge branch to master. Картинка про How to merge branch to master. Фото How to merge branch to master

Вместо того, чтобы просто передвинуть указатель ветки вперёд, Git создаёт новый результирующий снимок трёхстороннего слияния, а затем автоматически делает коммит. Этот особый коммит называют коммитом слияния, так как у него более одного предка.

How to merge branch to master. Смотреть фото How to merge branch to master. Смотреть картинку How to merge branch to master. Картинка про How to merge branch to master. Фото How to merge branch to master

Теперь, когда изменения слиты, ветка iss53 больше не нужна. Вы можете закрыть задачу в системе отслеживания ошибок и удалить ветку:

Основные конфликты слияния

Git не создал коммит слияния автоматически. Он остановил процесс до тех пор, пока вы не разрешите конфликт. Чтобы в любой момент после появления конфликта увидеть, какие файлы не объединены, вы можете запустить git status :

Всё, где есть неразрешённые конфликты слияния, перечисляется как неслитое. В конфликтующие файлы Git добавляет специальные маркеры конфликтов, чтобы вы могли исправить их вручную. В вашем файле появился раздел, выглядящий примерно так:

Мы рассмотрим более продвинутые инструменты для разрешения сложных конфликтов слияния в разделе Продвинутое слияние главы 7.

Если это вас устраивает и вы убедились, что все файлы, где были конфликты, добавлены в индекс — выполните команду git commit для создания коммита слияния. Комментарий к коммиту слияния по умолчанию выглядит примерно так:

Если вы считаете, что коммит слияния требует дополнительных пояснений — опишите как были разрешены конфликты и почему были применены именно такие изменения, если это не очевидно.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *