Rebase current onto selected в idea что значит

Git rebase vs merge¶

Conceptual Overview¶

The first thing to understand about git rebase is that it solves the same problem as git merge. Both of these commands are designed to integrate changes from one branch into another branch—they just do it in very different ways.

Consider what happens when you start working on a new feature in a dedicated branch, then another team member updates the master branch with new commits. This results in a forked history, which should be familiar to anyone who has used Git as a collaboration tool.

Rebase current onto selected в idea что значит. 01. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-01. картинка Rebase current onto selected в idea что значит. картинка 01

The Merge Option¶

The easiest option is to merge the master branch into the feature branch using something like the following:

Or, you can condense this to a one-liner:

This creates a new “merge commit” in the feature branch that ties together the histories of both branches, giving you a branch structure that looks like this:

Rebase current onto selected в idea что значит. 02. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-02. картинка Rebase current onto selected в idea что значит. картинка 02

Merging is nice because it’s a non-destructive operation. The existing branches are not changed in any way. This avoids all of the potential pitfalls of rebasing (discussed below).

On the other hand, this also means that the feature branch will have an extraneous merge commit every time you need to incorporate upstream changes. If master is very active, this can pollute your feature branch’s history quite a bit. While it’s possible to mitigate this issue with advanced git log options, it can make it hard for other developers to understand the history of the project or branch you are working on.

The Rebase Option¶

We prefer this option over merging

As an alternative to merging, you can rebase the feature branch onto master branch using the following commands:

Rebase current onto selected в idea что значит. 03. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-03. картинка Rebase current onto selected в idea что значит. картинка 03

The major benefit of rebasing is that you get a much cleaner project history:

The Golden rule of Rebasing¶

Force-Pushing¶

However, before executing this command, please be sure nobody else is working on this branch.

But how do I rebase?¶

Syncing your fork first¶

Add upstream remote which points to https://github.com/strongbox/strongbox

Rebasing¶

In most modern IDEs you will have an option to rebase from the IDE. That would be your best option as you will be able to more easily resolve any conflicts which might occur during the rebase.

If you are using Intellij Idea, you need to be at your feature branch and then just Rebase current onto Selected (master) :

Rebase current onto selected в idea что значит. rebase 1. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-rebase 1. картинка Rebase current onto selected в idea что значит. картинка rebase 1

Should there be any conflicts, Idea will give you a pop-up window with a list of the conflicting files/changes

Explanation for the options above:

You can also check Idea’s manual for Resolving Conflicts

Command line¶

If you are command line lover, you can execute the commands manually:

However, when conflicts arise, it could be a bit challenging to fix them from your console.

Finally¶

Once you are done rebasing and you have ensured that the code builds as well as the tests are passing, then you will need to force push your branch (remember the Force Pushing section?)

I need help¶

License¶

Источник

Apply changes from one Git branch to another

In Git, there are several ways to integrate changes from one branch into another:

Merge branches

Suppose you have created a feature branch to work on a specific task, and want to integrate the results of your work into the main code base after you have completed and tested your feature: Rebase current onto selected в idea что значит. feature branch diagram. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-feature branch diagram. картинка Rebase current onto selected в idea что значит. картинка feature branch diagram

Merging your branch into master is the most common way to do this.

It is very common that while you are working in your feature branch, your teammates continue to commit their work to master: Rebase current onto selected в idea что значит. feature branch diverge from master diagram. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-feature branch diverge from master diagram. картинка Rebase current onto selected в idea что значит. картинка feature branch diverge from master diagram

Rebase current onto selected в idea что значит. merge result diagram. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-merge result diagram. картинка Rebase current onto selected в idea что значит. картинка merge result diagram

Git creates a new commit (M) that is referred to as a merge commit that results from combining the changes from your feature branch and master from the point where the two branches diverged.

Merge branches

In the Branches popup or in the Branches pane of the Git tool window, select the target branch that you want to integrate the changes to, and choose Checkout from the context menu to switch to that branch.

Do one of the following:

If you do not need to specify options for the merge, select the branch that you want to merge into the current branch and choose Merge into Current from the submenu.

If you need to specify merge options, from the main menu choose VCS Git | Merge Changes to open the Merge dialog:

Rebase current onto selected в idea что значит. merge dialog. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-merge dialog. картинка Rebase current onto selected в idea что значит. картинка merge dialog

Select the branch that you want to merge into the current branch, click Modify Options and choose from the following:

—no-ff : a merge commit will be created in all cases, even if the merge could be resolved as a fast-forward.

—ff-only : the merge will be resolved only if it is possible to fast-forward.

—squash : a single commit with all pulled changes will be created on top of the current branch.

-m : you will be able to edit the message for the merge commit.

—no-commit : a merge will be performed, but a merge commit will not be created so that you can inspect the result of the merge before committing.

If your working tree is clean (which means you have no uncommitted changes), and no conflicts occur between your feature branch and the target branch, Git will merge the two branches, and the merge commit will appear in the Log tab of the Git tool window Alt+9 :

Rebase current onto selected в idea что значит. merge commit. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-merge commit. картинка Rebase current onto selected в idea что значит. картинка merge commit

If conflicts occur between your branch and the target branch, you will be prompted to resolve them (see Resolve conflicts). If there are unresolved conflicts left after a merge, the Merge Conflicts node will appear in the corresponding changelist in the Local Changes view with a link to resolve them.

You can cancel an unfinished merge operation by selecting the Abort action from the Git Branches popup.

Rebase branches (git-rebase)

When you rebase a branch onto another branch, you apply the commits from the first branch on top of the HEAD commit in the second branch.

Suppose you have created a feature branch to work on a specific task and make several commits to that branch: Rebase current onto selected в idea что значит. feature branch diagram. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-feature branch diagram. картинка Rebase current onto selected в idea что значит. картинка feature branch diagram

While you develop in your branch, your teammates continue to commit their work to master: Rebase current onto selected в idea что значит. feature branch diverge from master diagram. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-feature branch diverge from master diagram. картинка Rebase current onto selected в idea что значит. картинка feature branch diverge from master diagram

When you perform the rebase operation you integrate changes you have done in your feature branch to the master branch by applying your commits on top of the current HEAD commit in master : Rebase current onto selected в idea что значит. rebase result diagram. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-rebase result diagram. картинка Rebase current onto selected в idea что значит. картинка rebase result diagram

Rebase a branch on top of another branch

From the main menu select Git | Rebase :

Rebase current onto selected в idea что значит. git rebase dialog. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-git rebase dialog. картинка Rebase current onto selected в idea что значит. картинка git rebase dialog

From the list, select the target branch onto which you want to rebase the current branch: Rebase current onto selected в idea что значит. git rebase choose target branch no interactive. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-git rebase choose target branch no interactive. картинка Rebase current onto selected в idea что значит. картинка git rebase choose target branch no interactive

Rebase current onto selected в idea что значит. git rebase specify commit no interactive. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-git rebase specify commit no interactive. картинка Rebase current onto selected в idea что значит. картинка git rebase specify commit no interactive

Rebase current onto selected в idea что значит. git rebase choose source branch no interactive. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-git rebase choose source branch no interactive. картинка Rebase current onto selected в idea что значит. картинка git rebase choose source branch no interactive

IntelliJ IDEA will check out this branch before starting the rebase operation.

You can cancel an unfinished rebase operation or resume an interrupted rebase by selecting the Abort or Continue actions respectively from the top of the Git Branches popup.

If you do not need to specify options for the rebase, you can initiate a rebase without invoking the rebase dialog. In the Branches popup or in the Branches pane of the Git tool window select a branch and choose one of the following actions:

    Pull into Current Using Rebase (for remote branches) to fetch changes from the selected branch and rebase the current branch on top of these changes.

    Checkout and Rebase onto Current (for local branches) to check out the selected branch and rebase it on top of the branch that is currently checked out.

    For details on how to skip or squash commit during a rebase, refer to Edit project history by performing interactive rebase.

    Watch this video to see how a merge or a rebase operation are reflected in the Log tab of the Git tool window Alt+9 :

    Cherry-pick separate commits

    Sometimes you only need to apply a single commit to a different branch instead of rebasing or merging an entire branch. This may be useful, for example, if you are working in a feature branch and want to integrate a hotfix from master that was committed after the two branches have diverged. Or you may want to backport a fix to a previous release branch. You can do so by using the Cherry-pick action.

    The status of a cherry pick operation is displayed in the status bar. You can always abort an ongoing cherry-pick by selecting Abort Cherry-Pick in the Git Branches popup. Rebase current onto selected в idea что значит. cherry pick status. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-cherry pick status. картинка Rebase current onto selected в idea что значит. картинка cherry pick status

    Apply a commit to another branch

    In the Branches popup select the target branch that you want to integrate the changes to and choose Checkout from the popup menu to switch to that branch.

    Open the Git tool window Alt+9 and switch to the Log tab.

    Locate the commit containing the changes you want to cherry pick.

    Select the required commit. Use the information in the Commit Details area to make sure these are the changes you want to transfer to another branch.

    When done, click Commit to cherry-pick the selected changes.

    Push the changes to the target branch.

    Apply separate changes

    Imagine you’ve made some changes to a file that you want to apply to a different branch, but these changes were committed together with other modified files. IntelliJ IDEA lets you apply separate changes instead of cherry-picking an entire commit.

    In the Branches popup select the target branch that you want to integrate the changes to and choose Checkout from the popup menu to switch to that branch.

    Open the Git tool window Alt+9 and switch to the Log tab.

    Locate the commit that contains the changes that you want to apply.

    In the Commit Details pane on the right, select the files containing the changes you want to apply to the target branch and select Cherry-Pick Selected Changes from the context menu.

    Commit the changes and then push them to the target branch.

    Apply separate files

    In addition to applying separate changes to a single file, you can copy an entire file’s contents to a different branch. This may be useful, for example, if the file you want to apply doesn’t exist in the target branch, or if changes to it were made within several commits.

    Switch to the branch to which the changes will be applied.

    In the Branches popup or in the Branches pane of the Git tool window, select the branch that contains the file you want to apply and choose Show Diff with Working Tree from the context menu.

    The dialog that opens shows a list of all files that are different in the selected branch compared with the branch that is currently checked out:

    Rebase current onto selected в idea что значит. ij git branches diff. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-ij git branches diff. картинка Rebase current onto selected в idea что значит. картинка ij git branches diff

      Files that exist in the selected branch and are missing in the current branch are marked with grey.

      Files that exist in the current branch but are missing in the selected branch are marked with green.

      Files that contain differences between the selected and the current branch are marked with blue.

      You can click the Swap Branches link to change which branch is considered as a base against which you are comparing the other branch.

      Commit and push the changes. IntelliJ IDEA will copy the entire contents of the file to the current branch.

      Источник

      Edit Git project history

      Git allows you to edit your project history. This is useful when you’re working on a feature branch and want to clean it up and make it look the way you want before you share it with others. For example, you can edit commit messages, squash together smaller commits related to the same functionality, or split a commit that contains unrelated changes into separate commits, add changes to a previous commit, and so on.

      Avoid modifying the history for a remote branch with multiple contributors unless absolutely necessary, for example, if you accidentally pushed some sensitive data.

      Pushing modifications that rewrite a branch history to the remote repository will be rejected to prevent data loss, so you will have to force push your changes.

      Also, you cannot perform actions that modify a branch history for commits that are not contained in the branch currently checked out.

      Edit a commit message

      If the only thing you need to change is a commit message, you can edit it before you push this commit.

      Amend the previous commit

      Sometimes you may commit too early and forget to add some files, or notice an error in the last commit that you want to fix without creating a separate commit.

      You can do this by using the Amend commit option that appends staged changes to the previous commit. As a result, you end up with a single commit instead of two different ones.

      Select the Amend checkbox so that the Commit button changes to Amend Commit and click it.

      Amend any earlier commit

      If you need to add changes to any earlier commit instead of committing them separately, you can do this by using the fixup or the squash action. Both commands append staged changes to the selected commit, but handle commit messages differently:

      squash adds the new commit message to the original commit

      fixup discards the new commit message, leaving only the message from the original commit

      Both commands require a rebase because they change the commit hashes.

      Modify the commit message if necessary if you’ve chosen to squash changes.

      Squash commits

      If you need to meld any two commits related to the same functionality, you can squash them into one for the sake of cleaner branch history.

      In the Log tab of the Git tool window Alt+9 select the commits that you want to combine into one and choose Squash Commits from the context menu.

      Push Ctrl+Shift+K the changes to the remote branch.

      Drop a commit

      You can discard a pushed commit in the current branch without creating an additional commit that reverts the changes.

      Select a commit you want to discard in the Log view and choose Drop Commit from the context menu.

      Edit project history by performing interactive rebase

      Edit the history of the current branch

      IntelliJ IDEA allows you to edit the commits history in the current branch before you apply the changes to a different branch.

      Open the Git tool window Alt+9 and switch to the Log tab.

      Filter the log so that it only displays commits from the current branch:

      Rebase current onto selected в idea что значит. VCS log branch filter. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-VCS log branch filter. картинка Rebase current onto selected в idea что значит. картинка VCS log branch filter

      The Interactive Rebase dialog will be displayed containing the list of all commits in the current branch that were made after the selected commit:

      Rebase current onto selected в idea что значит. VCS interactive rebase dialog. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-VCS interactive rebase dialog. картинка Rebase current onto selected в idea что значит. картинка VCS interactive rebase dialog

      If the Interactively Rebase from Here option is disabled, this may be due to one of the following reasons:

      the selected commit has several parents

      the selected commit is not in the current branch

      the selected commit is pushed to a protected branch

      To identify the reason, hover the action in the context menu and look for the message in the status bar:

      Rebase current onto selected в idea что значит. VCS interactive rebase disabled. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-VCS interactive rebase disabled. картинка Rebase current onto selected в idea что значит. картинка VCS interactive rebase disabled

      You can perform the following changes to the branch history:

      When rebase is stopped at a commit, a notification pops up in the bottom-right corner of the IntelliJ IDEA window letting you continue or abort the rebase:

      Rebase current onto selected в idea что значит. continue rebase notification. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-continue rebase notification. картинка Rebase current onto selected в idea что значит. картинка continue rebase notification

      If you’ve closed the notification, from the main menu choose Git | Continue rebase to resume it.

      Reword the commit message : click Reword or double-click a commit and edit the text in the mini-editor that opens.

      In both cases, you will be able to edit the commit message in the mini editor that opens when you apply one of these actions.

      Ignore a commit : click Drop so that the changes from the selected commit are not applied.

      Undo all changes : click Reset to discard all actions you’ve applied to the commits.

      As a result, the Rebasing Commits dialog shows a graph illustrating all actions you’ve applied to commits in your branch, so that you can review them before starting the rebase:

      Rebase current onto selected в idea что значит. VCS interactive rebase graph. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-VCS interactive rebase graph. картинка Rebase current onto selected в idea что значит. картинка VCS interactive rebase graph

      Edit a branch history and integrate it into another branch

      IntelliJ IDEA allows you to rebase a branch on top of another branch and edit the source branch history before you apply the changes.

      From the main menu select Git | Rebase :

      Rebase current onto selected в idea что значит. git rebase dialog. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-git rebase dialog. картинка Rebase current onto selected в idea что значит. картинка git rebase dialog

      From the list, select the target branch onto which you want to rebase the current branch: Rebase current onto selected в idea что значит. git rebase choose branch. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-git rebase choose branch. картинка Rebase current onto selected в idea что значит. картинка git rebase choose branch

      Rebase current onto selected в idea что значит. git rebase specify commit. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-git rebase specify commit. картинка Rebase current onto selected в idea что значит. картинка git rebase specify commit

      Rebase current onto selected в idea что значит. git rebase choose source branch. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-git rebase choose source branch. картинка Rebase current onto selected в idea что значит. картинка git rebase choose source branch

      IntelliJ IDEA will check out this branch before starting the rebase operation.

      The Interactive Rebase dialog will be displayed containing the list of all commits in the current branch that were made after the selected commit.

      Rebase current onto selected в idea что значит. VCS interactive rebase dialog. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-VCS interactive rebase dialog. картинка Rebase current onto selected в idea что значит. картинка VCS interactive rebase dialog

      You can perform the following changes to the branch history:

      When rebase is stopped at a commit, a notification pops up in the bottom-right corner of the IntelliJ IDEA window letting you continue or abort the rebase:

      Rebase current onto selected в idea что значит. continue rebase notification. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-continue rebase notification. картинка Rebase current onto selected в idea что значит. картинка continue rebase notification

      If you’ve closed the notification, from the main menu choose Git | Continue rebase to resume it.

      Reword the commit message : click Reword or double-click a commit and edit the text in the mini-editor that opens.

      In both cases, you will be able to edit the commit message in the mini editor that opens when you apply one of these actions.

      Ignore a commit : click Drop so that the changes from the selected commit are not applied.

      Undo all changes : click Reset to discard all actions you’ve applied to the commits.

      As a result, the Rebasing Commits dialog shows a graph illustrating all actions you’ve applied to commits in your branch, so that you can review them before starting the rebase:

      Источник

      Простое объяснение Git Rebase

      Перевод статьи «Git Rebase Explained Simply».

      Rebase current onto selected в idea что значит. coast light lighthouse sunset night atmosphere 836494 pxhere.com min. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-coast light lighthouse sunset night atmosphere 836494 pxhere.com min. картинка Rebase current onto selected в idea что значит. картинка coast light lighthouse sunset night atmosphere 836494 pxhere.com min

      Rebase, пожалуй, самая недопонятая команда git. Практически каждый разработчик-джуниор, с которым мне довелось работать в паре, боялся применять git rebase.

      Забавно, но rebase это одна из нескольких команд git, которыми я лично пользуюсь практически ежедневно. По большому счету, я делаю rebase по крайней мере единожды для каждого пул-реквеста на GitHub.

      Применение rebase помогает мне удостовериться, что мои сообщения коммитов имеют смысл и что мои ветки не вызовут каких-то серьезных и неожиданных конфликтов слияния.

      Использование команды git rebase перестанет быть чем-то сложным или пугающим, как только вы поймете, как она работает и чем полезна.

      Итак, представьте, что у вас есть две ветки.

      Первая выглядит так:

      Если присмотреться, можно заметить, что вплоть до 13363dd3 основа веток (base) одинакова, а дальше они расходятся.

      Первая ветка, которую мы будем считать нашей рабочей веткой, содержит три коммита, которых нет во второй ветке.

      Вторая ветка (в нашем примере — master) содержит восемь коммитов, не имеющихся в нашей рабочей ветке.

      В реальной жизни подобные ситуации происходят постоянно. Вы можете это прочувствовать, поработав над проектом в составе большого коллектива разработчиков.

      Допустим, вы занимаетесь разработкой какой-нибудь отдельной фичи и делаете это в отдельной ветке. Если эта ваша ветка просуществует хотя бы несколько дней, скорее всего за это время ветка master успеет измениться (т. е., еще до того, как вы вольете свою ветку обратно в master).

      В таком случае очень пригодилась бы возможность сначала привести свою ветку в соответствие с master, а уж затем добавить свои изменения на верхушку git history.

      Если мы «уравняем» нашу рабочую ветку с веткой master в ее теперешнем состоянии, а затем поместим три своих коммита сверху, мы получим следующую историю:

      Таким образом пул-реквест в master будет куда чище, кроме того, это поможет избежать конфликтов слияния.

      К счастью, все это возможно благодаря перебазированию ветки!

      Давайте обратим внимание на само название команды: Rebase. Что оно означает?

      Применяя эту команду, мы заменяем основу (базу) нашей рабочей ветки на на ветку master. Т.е., мы «перебазируем» («re-base») рабочую ветку, меняем ее основу.

      Использование git rebase

      Rebase current onto selected в idea что значит. parkour 730407 1280 min. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-parkour 730407 1280 min. картинка Rebase current onto selected в idea что значит. картинка parkour 730407 1280 min

      Давайте теперь познакомимся поближе с самой командой.

      Предположим, у нас есть working-branch (рабочая ветка), проверенная на нашей локальной машине. В таком случае rebase выглядит просто:

      Вы увидите в консоли некий output:

      Как мы видим, git заново «проигрывает» нашу работу, как своего рода музыкальную запись, сверху ветки master.

      Если вывести лог истории git, вы увидите, что наши изменения записаны поверх ветки master.

      То есть, мы «перебазировали» нашу ветку, заменив ее основу на ветку master.

      Если использование rebase все еще пугает вас, попробуйте делать копию своей рабочей ветки, прежде чем запускать команду rebase — просто на всякий случай!

      Источник

      Git Rebase: руководство по использованию

      Rebase — один из двух способов объединить изменения, сделанные в одной ветке, с другой веткой. Начинающие и даже опытные пользователи git иногда испытывают нежелание пользоваться ей, так как не видят смысла осваивать еще один способ объединять изменения, когда уже и так прекрасно владеют операцией merge. В этой статье я бы хотел подробно разобрать теорию и практику использования rebase.

      Теория

      Итак, освежим теоретические знания о том, что же такое rebase. Для начала вкратце — у вас есть две ветки — master и feature, обе локальные, feature была создана от master в состоянии A и содержит в себе коммиты C, D и E. В ветку master после отделения от нее ветки feature был сделан 1 коммит B.

      Rebase current onto selected в idea что значит. image loader. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-image loader. картинка Rebase current onto selected в idea что значит. картинка image loader

      После применения операции rebase master в ветке feature, дерево коммитов будет иметь вид:

      Rebase current onto selected в idea что значит. image loader. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-image loader. картинка Rebase current onto selected в idea что значит. картинка image loader

      Обратите внимание, что коммиты C’, D’ и E’ — не равны C, D и E, они имеют другие хеши, но изменения (дельты), которые они в себе несут, в идеале точно такие же. Отличие в коммитах обусловлено тем, что они имеют другую базу (в первом случае — A, во втором — B), отличия в дельтах, если они есть, обусловлены разрешением конфликтных ситуаций, возникших при rebase. Об этом чуть подробнее далее.

      Такое состояние имеет одно важное преимущество перед первым, при слиянии ветки feature в master ветка может быть объединена по fast-forward, что исключает возникновение конфликтов при выполнении этой операции, кроме того, код в ветке feature более актуален, так как учитывает изменения сделанные в ветке master в коммите B.

      Процесс rebase-а детально

      Давайте теперь разберемся с механикой этого процесса, как именно дерево 1 превратилось в дерево 2?

      Напомню, перед rebase вы находтесь в ветке feature, то есть ваш HEAD смотрит на указатель feature, который в свою очередь смотрит на коммит E. Идентификатор ветки master вы передаете в команду как аргумент:

      Для начала git находит базовый коммит — общий родитель этих двух состояний. В данном случае это коммит A. Далее двигаясь в направлении вашего текущего HEAD git вычисляет разницу для каждой пары коммитов, на первом шаге между A и С, назовем ее ΔAC. Эта дельта применяется к текущему состоянию ветки master. Если при этом не возникает конфликтное состояние, создается коммит C’, таким образом C’ = B + ΔAC. Ветки master и feature при этом не смещаются, однако, HEAD перемещается на новый коммит (C’), приводя ваш репозитарий состояние «отделеной головы» (detached HEAD).

      Rebase current onto selected в idea что значит. image loader. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-image loader. картинка Rebase current onto selected в idea что значит. картинка image loader

      Успешно создав коммит C’, git переходит к переносу следующих изменений — ΔCD. Предположим, что при наложении этих изменний на коммит C’ возник конфликт. Процесс rebase останавливается (именно в этот момент, набрав git status вы можете обнаружить, что находитесь в состоянии detached HEAD). Изменения, внесенные ΔCD находятся в вашей рабочей копии и (кроме конфликтных) подготовлены к коммиту (пунктиром обозначена stage-зона):

      Rebase current onto selected в idea что значит. image loader. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-image loader. картинка Rebase current onto selected в idea что значит. картинка image loader

      Далее вы можете предпринять следующие шаги:

      1. Отменить процесс rebase набрав в консоли

      При этом маркер HEAD, будет перенесен обратно на ветку feature, а уже добавленные коммиты повиснут в воздухе (на них не будет указывать ни один указатель) и будут вскоре удалены.

      При этом, если все конфликты действительно разрешены, будет создан коммит D’ и rebase перейдет к следующему, в данном примере последнему шагу.

      После применения изменений ΔDE будет создан последний коммит E’, указатель ветки feature будет установлен на коммит E’, а HEAD станет показывать на ветку feature — теперь, вы находитесь в состоянии на втором рисунке, rebase окончен. Старые коммиты C, D и E вам больше не нужны.

      Rebase current onto selected в idea что значит. image loader. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-image loader. картинка Rebase current onto selected в idea что значит. картинка image loader

      При этом коммиты, созданные в процессе rebase-а, будут содержать данные как об оригинальном авторе и дате изменений (Author), так и о пользователе, сделавшем rebase (Commiter):

      С небес на землю — rebase в реальных условиях

      На самом деле обычно вы работаете не с двумя ветками, а с четырьмя в самом простом случае: master, origin/master, feature и origin/feature. При этом rebase возможен как между веткой и ее origin-ом, например feature и origin/feature, так и между локальными ветками feature и master.

      Rebase ветки с origin-ом

      Если вы хотите начать работать с rebase, то лучше всего начать с ребейза своих изменений в ветке относительно ее копии в удаленном репозитарии. Дело в том, что когда вы добавляете коммит, и в удаленном репозитарии добавляется коммит, для объединения изменений по-умолчанию используется merge. Выглядит это примерно так:

      Rebase current onto selected в idea что значит. image loader. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-image loader. картинка Rebase current onto selected в idea что значит. картинка image loader

      Rebase current onto selected в idea что значит. image loader. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-image loader. картинка Rebase current onto selected в idea что значит. картинка image loader

      Три коммита превратились в 6 (базовый коммит не считаем), история изменений неоправдано запутана, информация об объединении локальных веток с удаленными, на мой взгляд, лишняя. Если масштабировать эту ситуацию на несколько тематических веток и большее количество разработчиков, граф может выглядеть, например, так:

      Rebase current onto selected в idea что значит. image loader. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-image loader. картинка Rebase current onto selected в idea что значит. картинка image loader

      Rebase current onto selected в idea что значит. image loader. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-image loader. картинка Rebase current onto selected в idea что значит. картинка image loader

      Как поделиться веткой, к которой применен rebase, с коллегой

      Rebase current onto selected в idea что значит. image loader. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-image loader. картинка Rebase current onto selected в idea что значит. картинка image loader

      Тут все просто, наберите в консоли команду:

      Force-режим просто копирует отсутствующие родительские коммиты ветки feature на origin и насильно устанавливает указатель ветки на тот же коммит, что и ваш локальный.

      Будьте внимательны! Если вы забудете указать идентификатор ветки, то force-push будет выполнен для всех локальных веток, имеющих удаленный оригинал. При этом нужно понимать, что некоторые локальные ветки могут быть в неактуальном состоянии. То есть измененения, которые вы не успели затянуть будут удалены в origin-е. Конечно, сами коммиты не будут удалены — сбросятся только указатели ветки. Эта ситуация поправима — достаточно для каждой ветки найти человека, который последним пушил изменения в нее или уже успел их забрать. Он может сделать обычный push, вновь передав их на origin. Но вся эта морока вам ни к чему, так что лучше просто будьте внимательны.

      Реинтеграция тематической ветки в master

      Мы рассмотрели все необходимые операции для работы с ветками в стиле rebase. Осталось только переключиться в ветку master и сделать git merge feature. Ветка, подготовленная rebase-ом вольется в master по fast-forward, то есть указатель будет просто перемещен вперед.

      Rebase current onto selected в idea что значит. image loader. Rebase current onto selected в idea что значит фото. Rebase current onto selected в idea что значит-image loader. картинка Rebase current onto selected в idea что значит. картинка image loader

      В данном случае, на мой взгляд, merge-коммиты полезны и несут в себе информацию о моменте объединения веток. Этот граф выглядит как учебный пример, но такая структура вполне реальна при соблюдении некоторых простых правил всеми членами команды.

      Заключение

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

      В данной статье сделано одно допущение. Все это верно при простой модели ветвления — есть одна главная ветка master и несколько тематических, которые создаются от нее. Когда от тематической ветки создается другая тематическая ветка, есть свои нюансы при rebase-е первичной и вторичной ветки. О них можно прочитать в том самом официальном руководстве.

      Иногда споры, что же лучше merge или rebase доходят до холивара. От себя могу сказать, что в конечном счете выбор за вами, однако этот выбор не может быть продиктован уровнем владения тем или иным инструментом. Обоснованный выбор можно сделать, только когда для вас не составит труда работать и в том и в другом стиле. Я не агитирую за повсеместное использование rebase-а, а просто объясняю как им пользоваться. Надеюсь, это статья поможет вам снять вопросы, связанные с механизмом работы rebase и его применением в ежедневной работе.

      PS. Хочу поблагодарить своих коллег, продуктивные беседы с которыми позволили мне лучше разобраться в материале, положенном в основу этой статьи.

      Источник

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

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