Setup and Config
Getting and Creating Projects
Basic Snapshotting
Branching and Merging
Sharing and Updating Projects
Inspection and Comparison
Patching
Debugging
External Systems
Server Admin
- 2.45.1 → 2.45.2 no changes
- 2.45.0
04/29/24
- 2.44.1 → 2.44.2 no changes
- 2.44.0
02/23/24
- 2.43.3 → 2.43.5 no changes
- 2.43.2
02/13/24
- 2.43.1
02/09/24
- 2.43.0
11/20/23
- 2.42.2 → 2.42.3 no changes
- 2.42.1
11/02/23
- 2.41.1 → 2.42.0 no changes
- 2.41.0
06/01/23
- 2.40.1 → 2.40.3 no changes
- 2.40.0
03/12/23
- 2.39.4 → 2.39.5 no changes
- 2.39.3
04/17/23
- 2.39.1 → 2.39.2 no changes
- 2.39.0
12/12/22
- 2.38.1 → 2.38.5 no changes
- 2.38.0
10/02/22
- 2.37.3 → 2.37.7 no changes
- 2.37.2
08/11/22
- 2.36.3 → 2.37.1 no changes
- 2.36.2
06/23/22
- 2.35.1 → 2.36.1 no changes
- 2.35.0
01/24/22
- 2.34.1 → 2.34.8 no changes
- 2.34.0
11/15/21
- 2.33.2 → 2.33.8 no changes
- 2.33.1
10/12/21
- 2.32.1 → 2.33.0 no changes
- 2.32.0
06/06/21
- 2.31.1 → 2.31.8 no changes
- 2.31.0
03/15/21
- 2.30.1 → 2.30.9 no changes
- 2.30.0
12/27/20
- 2.29.1 → 2.29.3 no changes
- 2.29.0
10/19/20
- 2.28.1 no changes
- 2.28.0
07/27/20
- 2.27.1 no changes
- 2.27.0
06/01/20
- 2.26.1 → 2.26.3 no changes
- 2.26.0
03/22/20
- 2.25.1 → 2.25.5 no changes
- 2.25.0
01/13/20
- 2.24.1 → 2.24.4 no changes
- 2.24.0
11/04/19
- 2.23.1 → 2.23.4 no changes
- 2.23.0
08/16/19
- 2.22.1 → 2.22.5 no changes
- 2.22.0
06/07/19
- 2.21.1 → 2.21.4 no changes
- 2.21.0
02/24/19
- 2.20.1 → 2.20.5 no changes
- 2.20.0
12/09/18
- 2.19.3 → 2.19.6 no changes
- 2.19.2
11/21/18
- 2.19.1 no changes
- 2.19.0
09/10/18
- 2.18.1 → 2.18.5 no changes
- 2.18.0
06/21/18
- 2.17.1 → 2.17.6 no changes
- 2.17.0
04/02/18
- 2.16.6
12/06/19
- 2.15.4
12/06/19
- 2.14.6
12/06/19
- 2.13.7
05/22/18
- 2.12.5
09/22/17
- 2.10.5 → 2.11.4 no changes
- 2.9.5
07/30/17
- 2.8.6
07/30/17
- 2.7.6 no changes
- 2.6.7
05/05/17
- 2.5.6 no changes
- 2.4.12
05/05/17
- 2.3.10
09/28/15
- 2.2.3
09/04/15
- 2.1.4
12/17/14
- 2.0.5
12/17/14
RESUMO
git rebase [-i | --interactive] [<opções>] [--exec <cmd>] [--onto <nova-base> | --keep-base] [<upstream> [<ramo>]] git rebase [-i | --interactive] [<opções>] [--exec <cmd>] [--onto <nova-base>] --root [<ramo>] git rebase (--continue | --skip | --abort | --quit | --edit-todo | --show-current-patch)
DESCRIÇÃO
If <branch>
is specified, git rebase
will perform an automatic git switch <branch>
before doing anything else. Otherwise it remains on the current branch.
If <upstream>
is not specified, the upstream configured in branch.<name>.remote
and branch.<name>.merge
options will be used (see git-config[1] for details) and the --fork-point
option is assumed. If you are currently not on any branch or if the current branch does not have a configured upstream, the rebase will abort.
All changes made by commits in the current branch but that are not in <upstream>
are saved to a temporary area. This is the same set of commits that would be shown by git log <upstream>..HEAD
; or by git log 'fork_point'..HEAD
, if --fork-point
is active (see the description on --fork-point
below); or by git log HEAD
, if the --root
option is specified.
The current branch is reset to <upstream>
or <newbase>
if the --onto
option was supplied. This has the exact same effect as git reset --hard <upstream>
(or <newbase>
). ORIG_HEAD
is set to point at the tip of the branch before the reset.
Note | Não é garantido que ORIG_HEAD ainda aponte para o cume de uma ramificação anterior no final do "rebase" caso os outros comandos que escrevem essa pseudo-ref (git reset por exemplo) sejam usados durante o "rebase". O cume da ramificação anterior, no entanto, é acessível usando o "reflog" da ramificação atual (ou seja, @{1} , consulte gitrevisions[7]). |
Os commits que foram salvos anteriormente na área temporária são reaplicadas no ramo atual, uma por uma e em ordem. Observe que quaisquer commits no HEAD
que introduzam as mesmas alterações textuais que um commit no HEAD..<upstream>
são omitidas (ou seja, um patch já aceito na inicial com uma mensagem de commit ou carimbo de data e hora diferente, serão ignorados).
It is possible that a merge failure will prevent this process from being completely automatic. You will have to resolve any such merge failure and run git rebase --continue
. Another option is to bypass the commit that caused the merge failure with git rebase --skip
. To check out the original <branch>
and remove the .git/rebase-apply
working files, use the command git rebase --abort
instead.
Suponha que o seguinte histórico exista e que o ramo atual seja "topic":
A---B---C topic / D---E---F---G master
A partir deste ponto, o resultado de um dos seguintes comandos:
git rebase master git rebase master topic
seria:
A'--B'--C' topic / D---E---F---G master
NOTE: The latter form is just a short-hand of git checkout topic
followed by git rebase master
. When rebase exits topic
will remain the checked-out branch.
If the upstream branch already contains a change you have made (e.g., because you mailed a patch which was applied upstream), then that commit will be skipped and warnings will be issued (if the merge backend is used). For example, running git rebase master
on the following history (in which A'
and A
introduce the same set of changes, but have different committer information):
A---B---C topic / D---E---A'---F master
vai resultar em:
B'---C' topic / D---E---A'---F master
Aqui está como você transplantaria um ramo do tópico com base num ramo para outro, para fingir que você bifurcou o ramo do tópico deste último ramo, utilizando rebase --onto
.
First let’s assume your topic is based on branch next. For example, a feature developed in topic depends on some functionality which is found in next.
o---o---o---o---o master \ o---o---o---o---o next \ o---o---o topic
Queremos criar um tópico bifurcado no ramo master; porque a funcionalidade da qual o tópico depende foi mesclado na ramificação master mais estável. Queremos que a nossa árvore fique assim:
o---o---o---o---o master | \ | o'--o'--o' topic \ o---o---o---o---o next
Podemos conseguir isso utilizando o seguinte comando:
git rebase --onto master next topic
Another example of --onto option is to rebase part of a branch. If we have the following situation:
H---I---J topicB / E---F---G topicA / A---B---C---D master
então o comando
git rebase --onto master topicA topicB
resultaria em:
H'--I'--J' topicB / | E---F---G topicA |/ A---B---C---D master
É útil quando o topicB não depender do topicA.
A range of commits could also be removed with rebase. If we have the following situation:
E---F---G---H---I---J topicA
então o comando
git rebase --onto topicA~5 topicA~3 topicA
resultaria na remoção dos commits F e G:
E---H'---I'---J' topicA
This is useful if F and G were flawed in some way, or should not be part of topicA. Note that the argument to --onto
and the <upstream>
parameter can be any valid commit-ish.
In case of conflict, git rebase
will stop at the first problematic commit and leave conflict markers in the tree. You can use git diff
to locate the markers (<<<<<<) and make edits to resolve the conflict. For each file you edit, you need to tell Git that the conflict has been resolved, typically this would be done with
git add <nome-do-arquivo>
Depois de resolver o conflito manualmente e atualizar o índice com a resolução desejada, você pode continuar o processo de reconstrução com o comando
git rebase --continue
Como alternativa, você pode desfazer o git rebase com
git rebase --abort
MAIS OPÇÕES
As opções nesta seção, não podem ser usadas com nenhuma outra opção, inclusive entre si:
- --continue
Reinicie o processo de reformulação após resolver um conflito de mesclagem.
- --skip
Reinicie o processo de reconstrução da fundação ignorando o patch atual.
- --abort
Interrompa a operação de reconstrução da fundação e redefina o
HEAD
para o ramo original. Caso<ramo>
seja informado quando a operação de reconstrução da fundação seja iniciada, oHEAD
será redefinido para<ramo>
. Caso contrário, oHEAD
será redefinido para onde estava quando a operação de reconstrução foi iniciada.- --quit
Interrompa a operação de reconstrução, porém o
HEAD
não será redefinido para o ramo original. Como resultado, o índice e a árvore de trabalho também permanecem inalterados. Caso uma entrada temporária "stash" seja criada utilizando--autostash
, ela será salva na lista "stash".- --edit-todo
Edite a lista de tarefas durante uma nova reconstrução interativa.
- --show-current-patch
Exiba o patch atual numa nova recuperação interativa ou quando a nova recuperação for interrompida por causa de conflitos. É o equivalente ao
git show REBASE_HEAD
.
OPÇÕES
- --onto <nova-base>
Starting point at which to create the new commits. If the
--onto
option is not specified, the starting point is<upstream>
. May be any valid commit, and not just an existing branch name.Como um caso especial, você pode utilizar "A...B" como um atalho para a base de mesclagem A e B caso haja exatamente uma base para mesclagem. Você pode deixar de fora no máximo um de A e B; nesse caso, a predefinição retorna para
HEAD
.- --keep-base
Defina o ponto de partida para criar os novos commits para a mesclagem base do
<upstream>
e<ramo>
. Executando o comandogit rebase --keep-base <upstream> <ramo>
é o mesmo que executar o comandogit rebase --reapply-cherry-picks --no-fork-point --onto <upstream>...<ramo> <upstream> <ramo>
.Esta opção é útil no caso onde se está desenvolvendo um recurso em cima de um ramo upstream. Enquanto o recurso está sendo trabalhado, o ramo upstream pode avançar e talvez não seja a melhor ideia continuar reconstruindo no topo do upstream, porém manter a base do commit como está. Como a base do commit permanece inalterado, esta opção implica no uso da opção
--reapply-cherry-picks
para evitar a perda dos commits.Embora esta opção e o
--fork-point
encontrem a base da mesclagem entre<upstream>
e<ramo>
, esta opção utiliza a base da mesclagem como o ponto inicial onde os novos commits serão criados, enquanto--fork-point
utiliza a mesclagem da base para determinar o conjunto dos commits que serão reconstruídos.Consulte também a seção "OPÇÕES INCOMPATÍVEIS" logo abaixo.
- <upstream>
Upstream branch to compare against. May be any valid commit, not just an existing branch name. Defaults to the configured upstream for the current branch.
- <ramo>
Ramo de trabalho; A predefinição retorna para
HEAD
.- --apply
Use applying strategies to rebase (calling
git-am
internally). This option may become a no-op in the future once the merge backend handles everything the apply one does.Consulte também a seção "OPÇÕES INCOMPATÍVEIS" logo abaixo.
- --empty=(drop|keep|ask)
How to handle commits that are not empty to start and are not clean cherry-picks of any upstream commit, but which become empty after rebasing (because they contain a subset of already upstream changes). With drop (the default), commits that become empty are dropped. With keep, such commits are kept. With ask (implied by
--interactive
), the rebase will halt when an empty commit is applied allowing you to choose whether to drop it, edit files more, or just commit the empty changes. Other options, like--exec
, will use the default of drop unless-i
/--interactive
is explicitly specified.Observe que, os commits que começam vazios são mantidos (a menos que a opção
--no-keep-empty
seja utilizado) e os commits que são escolhas limpas (conforme determinado pelo comandogit log --cherry-mark ...
) são detectados e descartados como uma etapa preliminar (a menos que a opção--reapply-cherry-picks
ou--keep-base
seja utilizado).Consulte também a seção "OPÇÕES INCOMPATÍVEIS" logo abaixo.
- --no-keep-empty
- --keep-empty
Do not keep commits that start empty before the rebase (i.e. that do not change anything from its parent) in the result. The default is to keep commits which start empty, since creating such commits requires passing the
--allow-empty
override flag togit commit
, signifying that a user is very intentionally creating such a commit and thus wants to keep it.Usage of this flag will probably be rare, since you can get rid of commits that start empty by just firing up an interactive rebase and removing the lines corresponding to the commits you don’t want. This flag exists as a convenient shortcut, such as for cases where external tools generate many empty commits and you want them all removed.
Para os commits que não começam vazios, mas ficam vazios após o rebase, consulte a opção
--empty
.Consulte também a seção "OPÇÕES INCOMPATÍVEIS" logo abaixo.
- --reapply-cherry-picks
- --no-reapply-cherry-picks
Reaplique todas as escolhas seletivas que estejam limpas de qualquer commit "upstream" em vez inviabilizá-los por completo. (Então, caso estes commits se tornem vazios depois da reconstrução, por conter um subconjunto de alterações da "upstream", o comportamento em direção à eles é controlado através da opção
--empty
.)In the absence of
--keep-base
(or if--no-reapply-cherry-picks
is given), these commits will be automatically dropped. Because this necessitates reading all upstream commits, this can be expensive in repositories with a large number of upstream commits that need to be read. When using the merge backend, warnings will be issued for each dropped commit (unless--quiet
is given). Advice will also be issued unlessadvice.skippedCherryPicks
is set to false (see git-config[1]).A opção
--reapply-cherry-picks
permite que a reconstrução anteceda a leitura de todos os commits "upstream", melhorando muito o desempenho.Consulte também a seção "OPÇÕES INCOMPATÍVEIS" logo abaixo.
- --allow-empty-message
No-op. Rebasing commits with an empty message used to fail and this option would override that behavior, allowing commits with empty messages to be rebased. Now commits with an empty message do not cause rebasing to halt.
Consulte também a seção "OPÇÕES INCOMPATÍVEIS" logo abaixo.
- -m
- --merge
Usando estratégias de mesclagem para o rebase (padrão).
Note that a rebase merge works by replaying each commit from the working branch on top of the
<upstream>
branch. Because of this, when a merge conflict happens, the side reported as ours is the so-far rebased series, starting with<upstream>
, and theirs is the working branch. In other words, the sides are swapped.Consulte também a seção "OPÇÕES INCOMPATÍVEIS" logo abaixo.
- -s <estratégia>
- --strategy=<estratégia>
Use the given merge strategy, instead of the default
ort
. This implies--merge
.Como o
git rebase
repete cada commit do ramo de trabalho no cume do ramo <upstream> utilizando a estratégia informada, o uso danossa
estratégia simplesmente esvazia todos os patches do<ramo>
, que faz pouco sentido.Consulte também a seção "OPÇÕES INCOMPATÍVEIS" logo abaixo.
- -X <opção-da-estratégia>
- --strategy-option=<opção-da-estratégia>
Pass the <strategy-option> through to the merge strategy. This implies
--merge
and, if no strategy has been specified,-s ort
. Note the reversal of ours and theirs as noted above for the-m
option.Consulte também a seção "OPÇÕES INCOMPATÍVEIS" logo abaixo.
- --rerere-autoupdate
- --no-rerere-autoupdate
Após o mecanismo rerere reutilizar uma resolução gravada no conflito atual para atualizar os arquivos na árvore de trabalho, permita que ele também atualize o índice com o resultado da resolução. A opção
--no-rerere-autoupdate
é uma boa maneira de verificar novamente o que orerere
fez e também detectar possíveis erros da mesclagem antes de enviar o resultado para o índice com umgit add
separado.
- -S[<keyid>]
- --gpg-sign[=<keyid>]
- --no-gpg-sign
Commits assinados com o GPG O argumento
keyid
é opcional e a predefinição retorna para a identidade de quem fez o commit; caso seja utilizado, deve estar anexado a opção e sem espaço. A opção--no-gpg-sign
é útil para revogar a variável de configuraçãocommit.gpgSign
e a anterior--gpg-sign
.- -q
- --quiet
Fique em silêncio. Implica no uso da opção
--no-stat
.- -v
- --verbose
Seja loquaz. Implica no uso de
--stat
.- --stat
Exiba uma descrição do que mudou na upstream desde a última reconstrução (rebase). O diffstat também é controlado pela opção de configuração
rebase.stat
.- -n
- --no-stat
Não mostre um "diffstat" como parte do processo de reconstrução da fundação (rebase).
- --no-verify
This option bypasses the pre-rebase hook. See also githooks[5].
- --verify
Allows the pre-rebase hook to run, which is the default. This option can be used to override
--no-verify
. See also githooks[5].- -C<n>
Ensure at least
<n>
lines of surrounding context match before and after each change. When fewer lines of surrounding context exist they all must match. By default no context is ever ignored. Implies--apply
.Consulte também a seção "OPÇÕES INCOMPATÍVEIS" logo abaixo.
- --no-ff
- --force-rebase
- -f
Individually replay all rebased commits instead of fast-forwarding over the unchanged ones. This ensures that the entire history of the rebased branch is composed of new commits.
Pode ser útil após reverter uma mesclagem do ramo "topic", pois esta opção recria o ramo "topic" com os novos commits, para que possa ser recuperado com êxito sem precisar "reverter a reversão" (para mais detalhes, consulte o Como reverter uma falha da mesclagem).
- --fork-point
- --no-fork-point
Utilize reflog para encontrar um ancestral comum melhor entre a
<upstream>
e o<ramo>
ao calcular quais os commits foram introduzidos pelo<ramo>
.When
--fork-point
is active, fork_point will be used instead of<upstream>
to calculate the set of commits to rebase, where fork_point is the result ofgit merge-base --fork-point <upstream> <branch>
command (see git-merge-base[1]). If fork_point ends up being empty, the<upstream>
will be used as a fallback.Caso a
<upstream>
ou a opção--keep-base
seja utilizada na linha de comando, a predefinição será--no-fork-point
, caso contrário, a predefinição será--fork-point
. Consulte tambémrebase.forkpoint
em git-config[1].Caso o seu ramo teve como base no
<upstream>
, porém<upstream>
foi retrocedido e o seu ramo contém commits que foram eliminados, esta opção pode ser utilizada com a opção--keep-base
para eliminar estes commits do seu ramo.Consulte também a seção "OPÇÕES INCOMPATÍVEIS" logo abaixo.
- --ignore-whitespace
Ignore as diferenças dos espaços ao tentar reconciliar as diferenças. Atualmente, cada estrutura implementa uma aproximação deste comportamento:
- aplica o "backend"
Ao aplicar um patch, ignore as alterações no espaço das linhas do contexto. Infelizmente, isto significa que caso as linhas "antigas" sendo substituídas pelo patch difiram apenas pelo espaço do arquivo existente haverá um conflito de integração em vez da aplicação bem sucedida do patch.
- mescla o "backend"
Treat lines with only whitespace changes as unchanged when merging. Unfortunately, this means that any patch hunks that were intended to modify whitespace and nothing else will be dropped, even if the other side had no changes that conflicted.
- --whitespace=<opção>
This flag is passed to the
git apply
program (see git-apply[1]) that applies the patch. Implies--apply
.Consulte também a seção "OPÇÕES INCOMPATÍVEIS" logo abaixo.
- --committer-date-is-author-date
Em vez de usar a hora atual como a data de quem fez o commit, utilize a data do autor que fez o rebase do commit como a data do commit. Esta opção implica no uso de
--force-rebase
.- --ignore-date
- --reset-author-date
Instead of using the author date of the original commit, use the current time as the author date of the rebased commit. This option implies
--force-rebase
.Consulte também a seção "OPÇÕES INCOMPATÍVEIS" logo abaixo.
- --signoff
Adicione uma resposta
Assinado-por
em todos os commits que tiveram a sua fundação reconstruída. Observe que caso a opção--interactive
seja utilizada, apenas os commit marcados para serem selecionados, editados ou reformulados terão um caracteres de resposta adicionado.Consulte também a seção "OPÇÕES INCOMPATÍVEIS" logo abaixo.
- -i
- --interactive
Make a list of the commits which are about to be rebased. Let the user edit that list before rebasing. This mode can also be used to split commits (see SPLITTING COMMITS below).
The commit list format can be changed by setting the configuration option rebase.instructionFormat. A customized instruction format will automatically have the commit hash prepended to the format.
Consulte também a seção "OPÇÕES INCOMPATÍVEIS" logo abaixo.
- -r
- --rebase-merges[=(rebase-cousins|no-rebase-cousins)]
- --no-rebase-merges
By default, a rebase will simply drop merge commits from the todo list, and put the rebased commits into a single, linear branch. With
--rebase-merges
, the rebase will instead try to preserve the branching structure within the commits that are to be rebased, by recreating the merge commits. Any resolved merge conflicts or manual amendments in these merge commits will have to be resolved/re-applied manually.--no-rebase-merges
can be used to countermand both therebase.rebaseMerges
config option and a previous--rebase-merges
.When rebasing merges, there are two modes:
rebase-cousins
andno-rebase-cousins
. If the mode is not specified, it defaults tono-rebase-cousins
. Inno-rebase-cousins
mode, commits which do not have<upstream>
as direct ancestor will keep their original branch point, i.e. commits that would be excluded by git-log[1]'s--ancestry-path
option will keep their original ancestry by default. Inrebase-cousins
mode, such commits are instead rebased onto<upstream>
(or<onto>
, if specified).Atualmente, só é possível recriar a mesclagem dos commits utilizando a estratégia de mesclagem
ort
; diferentes estratégias de mesclagem podem ser utilizadas somente através dos comandos explícitos comoexec git merge -s <strategy> [...]
.Consulte também RECONSTRUINDO AS MESCLAGENS e OPÇÕES INCOMPATÍVEIS abaixo.
- -x <cmd>
- --exec <cmd>
Anexe "exec <cmd>" após cada linha, criando um commit no final do histórico. O
<cmd>
será interpretado como um ou mais comandos do shell. Qualquer comando que falhar interromperá a reconstrução da fundação, encerrando com o código 1.É possível executar vários comandos utilizando uma instância da opção
--exec
com vários comandos:git rebase -i --exec "cmd1 && cmd2 && ..."
ou utilizando mais de um
--exec
:git rebase -i --exec "cmd1" --exec "cmd2" --exec ...
Caso a opção
--autosquash
seja utilizado, as linhasexec
não serão anexadas aos commits intermediários e aparecerão apenas no final de cada série de compressão/correção.Utiliza o mecanismo
--interactive
internamente, porém pode ser executado sem a opção--interactive
de forma explicita.Consulte também a seção "OPÇÕES INCOMPATÍVEIS" logo abaixo.
- --root
Rebase all commits reachable from
<branch>
, instead of limiting them with an<upstream>
. This allows you to rebase the root commit(s) on a branch.Consulte também a seção "OPÇÕES INCOMPATÍVEIS" logo abaixo.
- --autosquash
- --no-autosquash
Automatically squash commits with specially formatted messages into previous commits being rebased. If a commit message starts with "squash! ", "fixup! " or "amend! ", the remainder of the subject line is taken as a commit specifier, which matches a previous commit if it matches the subject line or the hash of that commit. If no commit matches fully, matches of the specifier with the start of commit subjects are considered.
In the rebase todo list, the actions of squash, fixup and amend commits are changed from
pick
tosquash
,fixup
orfixup -C
, respectively, and they are moved right after the commit they modify. The--interactive
option can be used to review and edit the todo list before proceeding.The recommended way to create commits with squash markers is by using the
--squash
,--fixup
,--fixup=amend:
or--fixup=reword:
options of git-commit[1], which take the target commit as an argument and automatically fill in the subject line of the new commit from that.Settting configuration variable
rebase.autoSquash
to true enables auto-squashing by default for interactive rebase. The--no-autosquash
option can be used to override that setting.Consulte também a seção "OPÇÕES INCOMPATÍVEIS" logo abaixo.
- --autostash
- --no-autostash
Automatically create a temporary stash entry before the operation begins, and apply it after the operation ends. This means that you can run rebase on a dirty worktree. However, use with care: the final stash application after a successful rebase might result in non-trivial conflicts.
- --reschedule-failed-exec
- --no-reschedule-failed-exec
Reagende automaticamente os comandos
exec
que falharam. Isso só faz sentido no modo interativo (ou quando uma opção--exec
for utilizada).This option applies once a rebase is started. It is preserved for the whole rebase based on, in order, the command line option provided to the initial
git rebase
, therebase.rescheduleFailedExec
configuration (see git-config[1] or "CONFIGURATION" below), or it defaults to false.Recording this option for the whole rebase is a convenience feature. Otherwise an explicit
--no-reschedule-failed-exec
at the start would be overridden by the presence of arebase.rescheduleFailedExec=true
configuration whengit rebase --continue
is invoked. Currently, you cannot pass--[no-]reschedule-failed-exec
togit rebase --continue
.- --update-refs
- --no-update-refs
Atualize automaticamente todas as ramificações que apontem para os commits onde os "rebases" estejam sendo feitos. Quaisquer ramificações forem verificadas numa árvore de trabalho não são atualizadas desta maneira.
Caso a variável de configuração
rebase.updateRefs
esteja definida, então esta opção pode ser usada para substituir e desativar esta configuração.Consulte também a seção "OPÇÕES INCOMPATÍVEIS" logo abaixo.
OPÇÕES INCOMPATÍVEIS
As seguintes opções:
--apply
--whitespace
-C
são incompatíveis com as seguintes opções:
--merge
--strategy
--strategy-option
--autosquash
--rebase-merges
--interactive
--exec
--no-keep-empty
--empty=
--[no-]reapply-cherry-picks quando utilizado com --keep-base
--update-refs
--root quando utilizado sem o --onto
Além disso, os seguintes pares de opções são incompatíveis:
--keep-base e --onto
--keep-base e --root
--fork-point e --root
DIFERENÇAS COMPORTAMENTAIS
git rebase
has two primary backends: apply and merge. (The apply backend used to be known as the am backend, but the name led to confusion as it looks like a verb instead of a noun. Also, the merge backend used to be known as the interactive backend, but it is now used for non-interactive cases as well. Both were renamed based on lower-level functionality that underpinned each.) There are some subtle differences in how these two backends behave:
Os commits vazios
The apply backend unfortunately drops intentionally empty commits, i.e. commits that started empty, though these are rare in practice. It also drops commits that become empty and has no option for controlling this behavior.
É predefinido que a estrutura merge mantenha os commits intencionalmente vazios (com -i
são marcados como vazio no editor da lista de tarefas ou podem ser descartados automaticamente com a opção --no-keep-empty
).
Semelhante à estrutura aplicada, é predefinido que a estrutura da mesclagem derrube os commits que se tornaram vazios a menos que as opções -i
ou --interactive
sejam utilizadas (nesse caso o comando para e pergunta ao usuário o que fazer). A estrutura da mesclagem também possui uma opção --empty=(drop|keep|ask)
para alterar o comportamento da manipulação dos commits que se tornaram vazios.
Detecção da renomeação do diretório
Due to the lack of accurate tree information (arising from constructing fake ancestors with the limited information available in patches), directory rename detection is disabled in the apply backend. Disabled directory rename detection means that if one side of history renames a directory and the other adds new files to the old directory, then the new files will be left behind in the old directory without any warning at the time of rebasing that you may want to move these files into the new directory.
A detecção da renomeação do diretório funciona com a estrutura merge, neste caso, fornecendo informações para você.
Contexto
The apply backend works by creating a sequence of patches (by calling format-patch
internally), and then applying the patches in sequence (calling am
internally). Patches are composed of multiple hunks, each with line numbers, a context region, and the actual changes. The line numbers have to be taken with some fuzz, since the other side will likely have inserted or deleted lines earlier in the file. The context region is meant to help find how to adjust the line numbers in order to apply the changes to the right lines. However, if multiple areas of the code have the same surrounding lines of context, the wrong one can be picked. There are real-world cases where this has caused commits to be reapplied incorrectly with no conflicts reported. Setting diff.context
to a larger value may prevent such types of problems, but increases the chance of spurious conflicts (since it will require more lines of matching context to apply).
A estrutura merge trabalha com a cópia completa de casa arquivo relevante isolando-os destes tipos de problemas.
A rotulagem dos marcadores de conflitos
When there are content conflicts, the merge machinery tries to annotate each side’s conflict markers with the commits where the content came from. Since the apply backend drops the original information about the rebased commits and their parents (and instead generates new fake commits based off limited information in the generated patches), those commits cannot be identified; instead it has to fall back to a commit summary. Also, when merge.conflictStyle
is set to diff3
or zdiff3
, the apply backend will use "constructed merge base" to label the content from the merge base, and thus provide no information about the merge base commit whatsoever.
A estrutura merge funciona com commits completos nos dois lados do histórico e portanto não possuem tais limitações.
Ganchos
The apply backend has not traditionally called the post-commit hook, while the merge backend has. Both have called the post-checkout hook, though the merge backend has squelched its output. Further, both backends only call the post-checkout hook with the starting point commit of the rebase, not the intermediate commits nor the final commit. In each case, the calling of these hooks was by accident of implementation rather than by design (both backends were originally implemented as shell scripts and happened to invoke other commands like git checkout
or git commit
that would call the hooks). Both backends should have the same behavior, though it is not entirely clear which, if any, is correct. We will likely make rebase stop calling either of these hooks in the future.
Interruptabilidade
The apply backend has safety problems with an ill-timed interrupt; if the user presses Ctrl-C at the wrong time to try to abort the rebase, the rebase can enter a state where it cannot be aborted with a subsequent git rebase --abort
. The merge backend does not appear to suffer from the same shortcoming. (See https://lore.kernel.org/git/20200207132152.GC2868@szeder.dev/ for details.)
Reescrevendo os Commits
When a conflict occurs while rebasing, rebase stops and asks the user to resolve. Since the user may need to make notable changes while resolving conflicts, after conflicts are resolved and the user has run git rebase --continue
, the rebase should open an editor and ask the user to update the commit message. The merge backend does this, while the apply backend blindly applies the original commit message.
Diferenças diversas
Existem mais algumas diferenças comportamentais que a maioria das pessoas considerariam fazer de forma inconsequente, porém são mencionadas por questões de integridade:
Reflog: As duas estruturas que utilizarão palavras diferentes durante a descrição das alterações feitas no reflog, embora ambos façam a utilização da palavra "rebase".
Progress, informational, and error messages: The two backends provide slightly different progress and informational messages. Also, the apply backend writes error messages (such as "Your files would be overwritten…") to stdout, while the merge backend writes them to stderr.
Diretórios de estado: As duas estruturas mantêm a sua condição em diferentes diretórios dentro do
.git/
ESTRATÉGIAS DE MESCLAGEM
O mecanismo da mesclagem (comandos git merge
e git pull
) permite que as estruturas das estratégias de mesclagem sejam escolhidas com a opção -s
. Algumas estratégias também podem ter suas próprias opções, que podem ser passadas usando -X<opção>
como argumentos para o comando git merge
e/ou git pull
.
- ort
Isso é a estratégia predefinida ao obter o mesclar um ramo. Esta estratégia pode resolver apenas duas cabeças usando o algoritmo da mesclagem de 3 vias. Quando há mais de um ancestral comum que pode ser usado para a mesclagem de 3 vias, ele cria uma árvore mesclada dos ancestrais comuns e o usa como a árvore de referência para a mesclagem de 3 vias. Foi informado que isso resulta em menos conflitos durante mesclagem sem causar distorções pelos testes feitos nas mesclagens reais dos commits, retiradas do histórico de desenvolvimento do Linux kernel 2.6. Além disso, essa estratégia pode detectar e manipular as mesclagens envolvendo renomeações, não faz uso das cópias detectadas. O nome para este algoritmo é uma sigla de ("Ostensibly Recursive’s Twin") ele foi escrito como um substituto para o algoritmo padrão anterior, o
recursive
.A estratégia ort pode adotar as seguintes opções:
- ours
Esta opção impõem que os pedaços conflitantes que sejam resolvidos de forma automática e de maneira limpa, favorecendo a nossa versão. As alterações vindos de outra árvore que não conflitam com o nosso lado são refletidas no resultado da mesclagem. Para um arquivo binário, todo o conteúdo é retirado do nosso lado.
Isso não deve ser confundido com a estratégia da nossa de mesclagem, que sequer olha para o que a outra árvore contém. Descarta tudo o que a outra árvore fez, declarando que o nosso histórico contém tudo o que aconteceu nela.
- theirs
Este é o oposto do nosso; observe que, diferentemente do nosso, não existe uma estratégia de mesclagem deles para confundir esta opção de mesclagem.
- ignore-space-change
- ignore-all-space
- ignore-space-at-eol
- ignore-cr-at-eol
Trata as linhas com o tipo indicado da mudança do espaço como inalterado por uma mesclagem de três vias. As alterações de espaço combinadas com outras alterações em uma linha não são ignoradas. Consulte também git-diff[1]
-b
,-w
,--ignore-space-at-eol
, e--ignore-cr-at-eol
.Caso a versão their (dele) introduzir apenas as alterações de espaço em uma linha, a our (nossa) versão será utilizada;
Caso a our (nossa) versão introduzir alterações nos espaços, porém a versão their (dele) incluir uma alteração substancial, a versão their (dele) será utilizada;
Caso contrário, a mesclagem continuará de forma usual.
- renormalize
Executa uma averiguação e um check-in virtual de três estágios em um arquivo ao resolver uma mesclagem de três vias. Esta opção deve ser utilizada ao mesclar os ramos com diferentes filtros que estejam limpos ou as regras normais para a quebra de linha. Para obter mais detalhes, consulte "Mesclando ramificações com diferentes atributos de check-in/check-out" em gitattributes[5].
- no-renormalize
Desativa a opção
renormalize
. Substitui a variável de configuraçãomerge.renormalize
.- find-renames[=<n>]
Liga a detecção de renomeação, configurando opcionalmente o limite de similaridade. Esta é a predefinição. Isso substitui a configuração da variável merge.renames. Consulte também git-diff[1]
--find-renames
.- rename-threshold=<n>
É um sinônimo obsoleto para
find-renames=<n>
.- subtree[=<caminho>]
Essa opção é uma forma mais avançada da estratégia da subárvore, onde a estratégia adivinha como as duas árvores devem ser deslocadas para coincidirem uma com a outra durante a mesclagem. Em vez disso, o caminho definido é prefixado (ou removido desde o início) para criar a forma das duas árvores que serão coincididas.
- recursive
Isso pode resolver apenas duas cabeças usando o algoritmo da mesclagem de 3 vias. Quando há mais de um ancestral comum que pode ser usado para a mesclagem de 3 vias, ele cria uma árvore mesclada dos ancestrais comuns e o usa como a árvore de referência para a mesclagem de 3 vias. Foi informado que isso resulta em menos conflitos durante mesclagem sem causar distorções pelos testes feitos nas mesclagens reais dos commits, retiradas do histórico de desenvolvimento do Linux kernel 2.6. Adicionalmente, pode detectar e lidar com mesclagens envolvendo renomeações. Não faz uso das cópias que forem detectadas. Esta foi a estratégia padrão para resolver dois heads do Git v0.99.9k até a v2.33.0.
A estratégia recursive (recursiva) tem as mesmas opções que ort. Contudo, existem três opções adicionais que ort ignora (não documentada acima) que são potencialmente úteis com a estratégia recursiva:
- patience
É um sinônimo obsoleto para
diff-algorithm=patience
.- diff-algorithm=[patience|minimal|histogram|myers]
Usa um algoritmo diff diferente durante a mesclagem, pode ajudar a evitar as distorções que ocorrem devido as linhas coincidentes sem importância (como chaves das funções distintas). Consulte também git-diff[1]
--diff-algorithm
. Observe que oort
utiliza especificamente odiff-algorithm=histogram
enquantorecursive
é a predefinição para a configuraçãodiff.algorithm
.- no-renames
Desativa a detecção de renomeação. Isso substitui a variável de configuração
merge.renames
. Consulte tambémgit-diff[1]--no-renames
.
- resolve
Isso só pode resultar em dois cabeçalhos (ou seja, a ramificação atual e uma outra ramificada da que você obteve) utilizando um algoritmo de mesclagem de três vias. Ele tenta detectar cuidadosamente as ambiguidades cruzadas da mesclagem. Ele não lida com renomeações.
- octopus
Isso resolve os casos com mais de dois cabeçalhos, porém se recusa a fazer uma mesclagem complexa que precise de uma resolução manual. Destina-se primeiramente para ser usado para agrupar junto o tópico dos cabeçalhos. Esra é a estratégia de mesclagem predefinida durante a extração ou a mesclagem com mais de um ramo.
- ours
Isso resolve qualquer quantidade dos cabeçalhos, porém a árvore resultante da mesclagem é sempre a do cabeçalho atual do ramo, ignorando efetivamente todas as alterações de todas os outros ramos. Ele deve ser usado para substituir o histórico antigo de desenvolvimento das ramificações laterais. Observe que isso é diferente da opção
-Xours
da estratégia de mesclagem recursiva.- subtree
Esta é uma estratégia
ort
modificada. Ao mesclar as árvores A e B, caso B corresponda a uma subárvore de A, o B será ajustado primeiro para coincidir à estrutura da árvore A, em vez de ler as árvores no mesmo nível. Esse ajuste também é feito na árvore ancestral comum.
Com as estratégias que usma a mesclagem de 3 vias (incluindo a predefinição, ort), caso uma alteração seja feita em ambas as ramificações, porém depois revertida em uma das ramificações, essa alteração estará presente no resultado mesclado; algumas pessoas acham este comportamento confuso. Isso ocorre porque apenas os cabeçalhos e a base da mesclagem são consideradas ao fazer uma mesclagem, e não os commits individuais. Portanto, o algoritmo da mesclagem considera a alteração revertida como nenhuma alteração e substitui a versão alterada.
OBSERVAÇÕES
You should understand the implications of using git rebase
on a repository that you share. See also RECOVERING FROM UPSTREAM REBASE below.
When the rebase is run, it will first execute a pre-rebase
hook if one exists. You can use this hook to do sanity checks and reject the rebase if it isn’t appropriate. Please see the template pre-rebase
hook script for an example.
Após a conclusão, o <ramo>
será o ramo atual.
MODO INTERATIVO
Rebasing interactively means that you have a chance to edit the commits which are rebased. You can reorder the commits, and you can remove them (weeding out bad or otherwise unwanted patches).
O modo interativo é destinado para este tipo de fluxo de trabalho:
tenho uma ideia maravilhosa
hackear o código
preparar uma série para envio
enviar
onde o ponto 2. consiste em várias instâncias do
a) uso regular
termine algo digno de um commit
commit
b) correção independente
perceber que algo não funciona
conserte isso
faça o commit
Sometimes the thing fixed in b.2. cannot be amended to the not-quite perfect commit it fixes, because that commit is buried deeply in a patch series. That is exactly what interactive rebase is for: use it after plenty of "a"s and "b"s, by rearranging and editing commits, and squashing multiple commits into one.
Inicie-o com o último commit que você quer manter como está:
git rebase -i <após-este-commit>
An editor will be fired up with all the commits in your current branch (ignoring merge commits), which come after the given commit. You can reorder the commits in this list to your heart’s content, and you can remove them. The list looks more or less like this:
pick deadbee Uma linha deste commit pick fa1afe1 Uma linha do próximo commit ...
As descrições on-line são puramente para o seu prazer; o comando git rebase não examinará eles, porém os nomes dos commits ("deadbee" e "fa1afe1" neste exemplo), portanto, não exclua ou edite os nomes.
Ao substituir o comando "pick" pelo comando "edit", é possível dizer ao comando git rebase
para parar após aplicar este commit, para que seja possível editar os arquivos e/ou a mensagem do commit, alterar o commit e continuar com a reconstrução.
Para interromper um "rebase" (exatamente como um comando "edit" faria, mas sem fazer uma escolha seletiva de nenhum commit primeiro), use o comando "break".
Caso apenas queira editar a mensagem do commit para um commit, substitua o comando pick
pelo comando reword
.
Para eliminar um commit, substitua o comando "pick" por "drop" ou apenas exclua a linha coincidente.
If you want to fold two or more commits into one, replace the command "pick" for the second and subsequent commits with "squash" or "fixup". If the commits had different authors, the folded commit will be attributed to the author of the first commit. The suggested commit message for the folded commit is the concatenation of the first commit’s message with those identified by "squash" commands, omitting the messages of commits identified by "fixup" commands, unless "fixup -c" is used. In that case the suggested commit message is only the message of the "fixup -c" commit, and an editor is opened allowing you to edit the message. The contents (patch) of the "fixup -c" commit are still incorporated into the folded commit. If there is more than one "fixup -c" commit, the message from the final one is used. You can also use "fixup -C" to get the same behavior as "fixup -c" except without opening an editor.
O comando git rebase
será interrompido quando o "pick" for substituído por "edit" ou quando um comando falhar devido aos erros da mesclagem. Quando você terminar de editar e/ou resolver os conflitos, será possível continuar utilizando git rebase --continue
.
Como por exemplo, caso você queira reordenar os últimos 5 commits de maneira onde o que era HEAD~4
se torne o novo HEAD
. Para conseguir isso, você chamaria o comando git rebase
assim:
$ git rebase -i HEAD~5
E mova o primeiro patch para o ramo da lista.
Convém recriar a mesclagem dos commits, por exemplo, caso tenha um histórico como este:
X \ A---M---B / ---o---O---P---Q
Suponha que queira reconstruir o lado do ramo ao lado começando em "A" para "Q". Verifique se o HEAD
atual é "B" e chame
$ git rebase -i -r --onto Q O
Reordering and editing commits usually creates untested intermediate steps. You may want to check that your history editing did not break anything by running a test, or at least recompiling at intermediate points in history by using the "exec" command (shortcut "x"). You may do so by creating a todo list like this one:
pick deadbee Implement feature XXX fixup f1a5c00 Fix to feature XXX exec make pick c0ffeee The oneline of the next commit edit deadbab The oneline of the commit after exec cd subdir; make test ...
A reconstrução interativa será interrompida quando um comando falhar (ou seja, encerra com uma condição diferente de 0) oferecendo uma oportunidade para a correção do problema. Você pode continuar com o comando git rebase --continue
.
The "exec" command launches the command in a shell (the default one, usually /bin/sh), so you can use shell features (like "cd", ">", ";" …). The command is run from the root of the working tree.
$ git rebase -i --exec "make test"
This command lets you check that intermediate commits are compilable. The todo list becomes like that:
pick 5928aea one exec make test pick 04d0fda two exec make test pick ba46169 three exec make test pick f4593f9 four exec make test
DIVIDINDO OS COMMITS
In interactive mode, you can mark commits with the action "edit". However, this does not necessarily mean that git rebase
expects the result of this edit to be exactly one commit. Indeed, you can undo the commit, or you can add other commits. This can be used to split a commit into two:
Start an interactive rebase with
git rebase -i <commit>^
, where<commit>
is the commit you want to split. In fact, any commit range will do, as long as it contains that commit.Marque o commit que deseja dividir com a ação "edit".
When it comes to editing that commit, execute
git reset HEAD^
. The effect is that theHEAD
is rewound by one, and the index follows suit. However, the working tree stays the same.Now add the changes to the index that you want to have in the first commit. You can use
git add
(possibly interactively) orgit gui
(or both) to do that.Faça o commit do índice agora atual com qualquer mensagem do commit que seja apropriada.
Repita as duas últimas etapas até que a sua árvore de trabalho esteja limpa.
Continue a reconstrução com
git rebase --continue
.
Caso não tenha certeza absoluta que as revisões intermediárias são consistentes (elas compilam, passam no conjunto de testes, etc.), você deve usar o git stash
para armazenar o commit das alterações que ainda não foram feitas após cada commit, teste e corrija o commit caso correções sejam necessárias.
SE RECUPERANDO DA RECONSTRUÇÃO DA FUNDAÇÃO INICIAL (UPSTREM REBASE)
Rebasing (or any other form of rewriting) a branch that others have based work on is a bad idea: anyone downstream of it is forced to manually fix their history. This section explains how to do the fix from the downstream’s point of view. The real fix, however, would be to avoid rebasing the upstream in the first place.
To illustrate, suppose you are in a situation where someone develops a subsystem branch, and you are working on a topic that is dependent on this subsystem. You might end up with a history like the following:
o---o---o---o---o---o---o---o master \ o---o---o---o---o subsystem \ *---*---* topic
Caso a reconstrução da fundação do subsystem seja realizada contra o master, o seguinte acontece:
o---o---o---o---o---o---o---o master \ \ o---o---o---o---o o'--o'--o'--o'--o' subsystem \ *---*---* topic
Caso agora continue o desenvolvimento normalmente e eventualmente mescle o topic para subsystem, os commits do subsystem permanecerão duplicados para sempre:
o---o---o---o---o---o---o---o master \ \ o---o---o---o---o o'--o'--o'--o'--o'--M subsystem \ / *---*---*-..........-*--* topic
Such duplicates are generally frowned upon because they clutter up history, making it harder to follow. To clean things up, you need to transplant the commits on topic to the new subsystem tip, i.e., rebase topic. This becomes a ripple effect: anyone downstream from topic is forced to rebase too, and so on!
Existem dois tipos de correções, discutidos nas seguintes subseções:
- Caso fácil: as alterações são literalmente as mesmas.
Isso acontece caso a reconstrução do subsystem foi uma reconstrução simples e não houve conflitos.
- Caso difícil: as alterações não são as mesmas.
Isso acontece caso a reconstrução da fundação (rebase) do subsistema tiver conflitos ou utilizar o
--interactive
para omitir, editar, esmagar ou consertar consertos; ou se a inicial utilizou um dos comandoscommit --amend
,reset
ou um histórico completo da reescrita comofilter-repo
.
O caso fácil
Funciona apenas se as alterações (IDs do patch com base no conteúdo do diff) no subsystem que forem literalmente as mesmas antes e depois da reconstrução do subsystem.
Nesse caso, a correção é fácil porque o comando git rebase sabe ignorar as alterações que já estão presentes no novo upstream (a menos que --reapply-cherry-picks
seja utilizada). Então, se você diz (supondo que você esteja no topic)
$ git rebase subsystem
você vai acabar com o histórico fixo
o---o---o---o---o---o---o---o master \ o'--o'--o'--o'--o' subsystem \ *---*---* topic
O caso difícil
As coisas ficam mais complicadas caso as alterações do "subsistema" não coincidam de forma exata aquelas antes da reconstrução.
Note | Embora uma "recuperação fácil dos casos" às vezes pareça ser bem-sucedida
mesmo no caso difícil, pode haver consequências não intencionais. Para
Por exemplo, um commit que foi removido através do comando git rebase
--interactive será ressuscitado! |
The idea is to manually tell git rebase
"where the old subsystem ended and your topic began", that is, what the old merge base between them was. You will have to find a way to name the last commit of the old subsystem, for example:
With the subsystem reflog: after
git fetch
, the old tip of subsystem is atsubsystem@{1}
. Subsequent fetches will increase the number. (See git-reflog[1].)Em relação ao cume do topic: sabendo que o seu topic tem três commits, o cume antigo do subsystem deve ser
topic~3
.
Você pode então transplantar o antigo subsystem..topic
para o novo cume dizendo (para o caso do reflog e supondo que você já esteja no topic):
$ git rebase --onto subsystem subsystem@{1}
O efeito cascata de uma recuperação "difícil" (hard case) é especialmente ruim: todos baixaram do topic e agora terão que executar também uma reconstrução "difícil"!
RECONSTRUINDO AS MESCLAGENS
O comando de reconstrução interativa foi originalmente projetado para lidar com séries de patches individuais. Como tal, faz sentido excluir a mesclagem dos commits da lista de tarefas, pois o desenvolvedor pode ter mesclado o master
atual enquanto trabalhava no ramo, apenas para redefinir todos os commits para master
eventualmente (ignorando a mesclagem dos commits).
No entanto, existem razões legítimas pelas quais um desenvolvedor pode querer recriar as mesclagens dos commits: para manter a estrutura do ramo (ou a "topologia do commit") ao trabalhar em diversos ramos inter-relacionadas.
No exemplo a seguir, o desenvolvedor trabalha em um tópico no ramo que refatora a maneira como os botões são definidos, em outro tópico do ramo que utilize esta refatoração para implementar um botão "Relatar um bug". A saída do git log --graph --format=%s -5
pode ficar assim:
* Mescla o ramo 'report-a-bug' |\ | * Adiciona o botão de feedback * | Mescla o ramo 'refactor-button' |\ \ | |/ | * Utiliza a classe do Botão para todos os botões | * Extrai o botão genérico do DownloadButton
O desenvolvedor pode querer redefinir estes commits para um novo master
enquanto mantém a topologia da ramificação. Quando se espera que o primeiro tópico do ramo que seja integrado ao` master` muito antes do segundo por exemplo. Para resolver os conflitos da mesclagem com as alterações para a classe DownloadButton
que a transformou em master
por exemplo.
This rebase can be performed using the --rebase-merges
option. It will generate a todo list looking like this:
rotular para # Branch: refactor-button reset onto pick 123456 Extrai o botão genérico do DownloadButton pick 654321 Utiliza a classe do Botão para todos os botões label refactor-button # Branch: report-a-bug reset refactor-button # Utiliza a classe do Botão para todos os botões pick abcdef Adiciona o botão de feedback label report-a-bug reset onto merge -C a1b2c3 refactor-button # Mescla o 'refactor-button' merge -C 6f5e4d report-a-bug # Mescla o 'report-a-bug'
Ao contrário de uma reconstrução interativa regular, existem os comandos label
, reset
e merge
além dos comandos pick
.
O comando label
associa um rótulo ao HEAD
atual quando este comando for executado. Estes rótulos são criados como refs locais da árvore de trabalho (refs/rewritten/<label>
) que serão excluídos quando a reconstrução terminar. Dessa forma, as operações da reconstrução em várias árvores de trabalho vinculadas ao mesmo repositório não interferem entre si. Caso o comando label
falhe, este é imediatamente reagendado, com uma mensagem útil sobre como proceder.
O comando reset
redefine o HEAD
, o índice e a árvore de trabalho para a revisão específica. É semelhante a um comando exec git reset --hard <label>
, porém se recusa a sobrescrever os arquivos que não sejam monitorados. Se o comando reset
falhar, ele será imediatamente reagendado, com uma mensagem útil sobre como editar a lista de tarefas (normalmente acontece quando um comando reset
foi inserido manualmente na lista de tarefas e contém um erro de digitação).
The merge
command will merge the specified revision(s) into whatever is HEAD at that time. With -C <original-commit>
, the commit message of the specified merge commit will be used. When the -C
is changed to a lower-case -c
, the message will be opened in an editor after a successful merge so that the user can edit the message.
If a merge
command fails for any reason other than merge conflicts (i.e. when the merge operation did not even start), it is rescheduled immediately.
By default, the merge
command will use the ort
merge strategy for regular merges, and octopus
for octopus merges. One can specify a default strategy for all merges using the --strategy
argument when invoking rebase, or can override specific merges in the interactive list of commands by using an exec
command to call git merge
explicitly with a --strategy
argument. Note that when calling git merge
explicitly like this, you can make use of the fact that the labels are worktree-local refs (the ref refs/rewritten/onto
would correspond to the label onto
, for example) in order to refer to the branches you want to merge.
Observação: o primeiro comando (label onto
) rotula a revisão onde os commits são refeitos; O nome onto
é apenas uma convenção, como um aceno para a opção --onto
.
Também é possível introduzir commits para mesclagem completamente novos, adicionando um comando no formato merge <merge-head>
. Este formulário gera uma mensagem de commit provisória e sempre abre um editor para permitir que o usuário a edite. Pode ser útil quando por exemplo, um ramo de um tópico acaba resolvendo mais de um problema e quer ser dividido em dois ou mais ramos de tópico. Considere esta lista de tarefas:
pick 192837 Alterna do GNU Makefiles para o CMake pick 5a6c7e Documente a alteração para o CMake pick 918273 Corrija a detecção do OpenSSL no CMake pick afbecd http: adicione a compatibilidade com o TLS v1.3 pick fdbaec Corrija a detecção da cURL no CMake no Windows
O único commit nesta lista que não está relacionado ao CMake pode muito bem ter sido motivado ao trabalhar na correção de todos os erros introduzidos durante a mudança para o CMake, porém ele lida com um interesse diferente. Para dividir esse ramo em dois tópicos, a lista de tarefas pode ser editada desta maneira:
rotular para escolha afbecd http: adicione a compatibilidade para o TLS v1.3 label tlsv1.3 redefinir para pick 192837 Alterna do GNU Makefiles para o CMake pick 918273 Corrija a detecção do OpenSSL no CMake pick fdbaec Corrija a detecção da cURL no CMake no Windows pick 5a6c7e Documente a alteração para o CMake label cmake reset onto merge tlsv1.3 merge cmake
CONFIGURAÇÃO
Warning | Missing See original version for this content. |
Warning | Missing See original version for this content. |
Warning | Missing See original version for this content. |
GIT
Parte do conjunto git[1]