Git команды

Merge team policy: definitions, pros, and cons

Always Merge-based policies instead flow like this: When a feature branch is complete merge it to your target branch ( or or ).

Make sure the merge is explicit with , which forces to record a merge commit in all cases, even if the changes could be replayed automatically on top of the target branch.

Pros:

Traceability: This helps keeping information about the historical existence of a feature branch and groups together all commits part of the feature.

Cons:

History can become intensely polluted by lots of merge commits, and visual charts of your repository can have rainbow branch lines that don’t add too much information, if not outright obfuscate what’s happening. (Now to be fair, confusion is easily solved by knowing how to navigate your history; The trick here is to use, for example, git log —first-parent to make sense of what happened.)

Commit Level Operations

The parameters that you pass to and determine their scope. When you don’t include a file path as a parameter, they operate on whole commits. That’s what we’ll be exploring in this section. Note that has no file-level counterpart.

Reset A Specific Commit

On the commit-level, resetting is a way to move the tip of a branch to a different commit. This can be used to remove commits from the current branch. For example, the following command moves the branch backwards by two commits.

The two commits that were on the end of are now dangling, or orphaned commits. This means they will be deleted the next time Git performs a garbage collection. In other words, you’re saying that you want to throw away these commits. This can be visualized as the following:

This usage of is a simple way to undo changes that haven’t been shared with anyone else. It’s your go-to command when you’ve started working on a feature and find yourself thinking, “Oh crap, what am I doing? I should just start over.”

In addition to moving the current branch, you can also get to alter the staged snapshot and/or the working directory by passing it one of the following flags:

  • – The staged snapshot and working directory are not altered in any way.
  • – The staged snapshot is updated to match the specified commit, but the working directory is not affected. This is the default option.
  • – The staged snapshot and the working directory are both updated to match the specified commit.
     

It’s easier to think of these modes as defining the scope of a operation. For further detailed information visit the page.

Checkout old commits

The command is used to update the state of the repository to a specific point in the projects history. When passed with a branch name, it lets you switch between branches.

Internally, all the above command does is move to a different branch and update the working directory to match. Since this has the potential to overwrite local changes, Git forces you to commit or stash any changes in the working directory that will be lost during the checkout operation. Unlike , doesn’t move any branches around.

You can also check out arbitrary commits by passing the commit reference instead of a branch. This does the exact same thing as checking out a branch: it moves the reference to the specified commit. For example, the following command will check out the grandparent of the current commit:

This is useful for quickly inspecting an old version of your project. However, since there is no branch reference to the current , this puts you in a detached state. This can be dangerous if you start adding new commits because there will be no way to get back to them after you switch to another branch. For this reason, you should always create a new branch before adding commits to a detached .

Undo Public Commits with Revert

Reverting undoes a commit by creating a new commit. This is a safe way to undo changes, as it has no chance of re-writing the commit history. For example, the following command will figure out the changes contained in the 2nd to last commit, create a new commit undoing those changes, and tack the new commit onto the existing project.

This can be visualized as the following:

Contrast this with , which does alter the existing commit history. For this reason, should be used to undo changes on a public branch, and should be reserved for undoing changes on a private branch.

You can also think of as a tool for undoing committed changes, while is for undoing uncommitted changes.

Like , has the potential to overwrite files in the working directory, so it will ask you to commit or stash changes that would be lost during the revert operation.

Ejemplos

Elimina el archivo especificado del entorno de ensayo, pero el directorio de trabajo se mantiene intacto. Deshace la preparación de un archivo sin sobrescribir los cambios.

Restablece el entorno de ensayo para que refleje la confirmación más reciente, pero el directorio de trabajo se mantiene intacto. Deshace la preparación de todos los archivos sin sobrescribir los cambios, lo que te da la oportunidad de volver a crear la instantánea preparada desde cero.

Restablece el entorno de ensayo y el directorio de trabajo para que reflejen la confirmación más reciente. Además de deshacer la preparación de los cambios, el indicador le dice a Git que sobrescriba todos los cambios en el directorio de trabajo también. Dicho de otra manera: borra todos los cambios no confirmados, así que asegúrate de que realmente quieres descartar tus desarrollos locales antes de utilizarlo.

Retrocede el extremo de la rama actual a , restablece el entorno de ensayo para que coincida, pero deja solo al directorio de trabajo. Todos los cambios realizados desde se encontrarán en el directorio de trabajo, que te permite volver a confirmar el historial del proyecto utilizando instantáneas más limpias y más atómicas.

Retrocede el extremo de la rama actual a y restablece tanto el entorno de ensayo como el directorio de trabajo para que coincidan. Esto descarta no solo los cambios no confirmados, sino todas las confirmaciones posteriores también.

Wie es funktioniert

Oberflächlich betrachtet zeigt ein ähnliches Verhalten wie . Während nur auf den -Ref-Pointer angewendet wird, verschiebt den -Ref-Pointer und den aktuellen Branch-Ref-Pointer. Das folgende Beispiel veranschaulicht dieses Verhalten:

In diesem Beispiel sehen wir eine Reihe von Commits im -Branch. Der -Ref und der -Branch-Ref verweisen derzeit auf Commit d. Führen wir nun und aus und vergleichen.

git checkout b

Mit verweist der -Ref weiterhin auf . Der -Ref wurde entfernt und verweist jetzt auf Commit . Das Repository befindet sich nun in einem Zustand mit «losgelöstem » (im Englischen «detached HEAD»).

git reset b

hingegen verschiebt sowohl den als auch die Branch-Refs zum angegebenen Commit.

aktualisiert nicht nur die Commit-Ref-Pointer, sondern ändert auch den Zustand der drei Bäume. Ref-Pointer werden immer geändert. Das Update betrifft den dritten Baum, nämlich den Commit-Baum. Mit den Befehlszeilenargumenten und kannst du die Änderungen am Staging-Index und am Arbeitsverzeichnis beeinflussen.

File-level Operations

The and commands also accept an optional file path as a parameter. This dramatically alters their behavior. Instead of operating on entire snapshots, this forces them to limit their operations to a single file.

Git Reset A Specific File

When invoked with a file path, updates the staged snapshot to match the version from the specified commit. For example, this command will fetch the version of in the 2nd-to-last commit and stage it for the next commit:

As with the commit-level version of , this is more commonly used with rather than an arbitrary commit. Running will unstage . The changes it contains will still be present in the working directory.

The , , and flags do not have any effect on the file-level version of , as the staged snapshot is always updated, and the working directory is never updated.

Git Checkout File

Checking out a file is similar to using with a file path, except it updates the working directory instead of the stage. Unlike the commit-level version of this command, this does not move the reference, which means that you won’t switch branches.

For example, the following command makes in the working directory match the one from the 2nd-to-last commit:

Just like the commit-level invocation of , this can be used to inspect old versions of a project—but the scope is limited to the specified file.

If you stage and commit the checked-out file, this has the effect of “reverting” to the old version of that file. Note that this removes all of the subsequent changes to the file, whereas the command undoes only the changes introduced by the specified commit.

Like , this is commonly used with as the commit reference. For instance, has the effect of discarding unstaged changes to . This is similar behavior to , but it operates only on the specified file.

git reset und die drei Bäume von Git

Um die richtige Anwendung von zu verstehen, müssen wir daher zunächst die internen Zustandsmanagementsysteme in Git nachvollziehen. Manchmal werden diese Mechanismen die «drei Bäume» von Git genannt. «Baum» ist vielleicht nicht das ideale Wort, denn es handelt sich hier streng genommen nicht um herkömmliche Baumstrukturen von Daten. Git nutzt jedoch Knoten- und Pointer-basierte Datenstrukturen, um den zeitlichen Verlauf von Veränderungen aufzuzeichnen. Am besten lassen sich diese Mechanismen veranschaulichen, wenn wir in einem Repository ein Changeset erstellen und dieses durch die drei Bäume verfolgen. 

Zunächst einmal erstellen wir mit den folgenden Befehlen ein neues Repository:

Im Code-Beispiel oben wird ein neues Git-Repository mit einer einzigen leeren Datei, , erstellt. Zu diesem Zeitpunkt gibt es im Beispiel-Repository nach dem Hinzufügen von einen einzigen Commit ().

Entender os perigos do rebase

Uma ressalva a ser considerada ao trabalhar com o Git Rebase é que os conflitos de mesclagem podem se tornar mais frequentes durante um fluxo de trabalho de rebase. Isto ocorre caso você tenha uma ramificação antiga que se desviou da principal. Em determinadas ocasiões você vai querer fazer o rebase contra a branch principal e nesse momento ela vai poder conter muitas novas confirmações que vão conflitar com as alterações da ramificação. Isto é resolvido com facilidade fazendo o rebase da ramificação com frequência contra a branch principal e fazendo confirmações mais frequentes. Os argumentos da linha de comando e podem ser passados para o para avançar ou reiniciar o rebase ao lidar com conflitos.

Uma ressalva de rebase mais séria é a perda de confirmações ao reescrever o histórico interativo. Executar o rebase no modo interativo e executar subcomandos como squash ou drop vai remover as confirmações do log imediato da ramificação. À primeira vista, isso pode parecer como se as confirmações tivessem desaparecido de vez. Usando o , estas confirmações podem ser restauradas e todo o rebase pode ser desfeito. Para mais informações sobre como usar o para encontrar confirmações perdidas, visite página de documentação do Git reflog.

O Git Rebase em si não é tão perigoso. Os casos de verdadeiro perigo surgem ao executar rebases interativos com reescrita de histórico e colocar os resultados em uma ramificação remota que é compartilhada por outros usuários. Este padrão deve ser evitado, pois ele tem o potencial de substituir o trabalho remoto de outros usuários quando eles fizerem o pull.

Научись любить командную строку. Оставь в покое IDE

По целому ряду причин (например из-за подкоманд Git) разумно использовать командную строку. Git безумно мощный. IDE тоже, но по-своему. Я использую IDE каждый день (IntelliJ IDEA) и активно использовал другие (Eclipse), но никогда не видел интеграции с Git, которая могла бы посоперничать с легкостью и мощью командной строки.

Некоторые функции Git, которые реализованы в IDE, имеют неоценимое значение. Например вызов git rm при удалении файла и правильное использование git при его переименовании. Но все разваливается, когда ты начинаешь пытаться закоммитить, смержить, сделать rebase или выполнить сложный анализ истории через IDE.

Когда дело доходит до настоящей мощи Git — это все-таки командная строка.

Независимо от того, что ты используешь (Bash или Z shell), есть сценарии завершения табуляции, которые решают бОльшую часть боли из-за запоминания подкоманд и переключателей.

Funcionamiento

A nivel superficial, tiene un comportamiento similar a . Mientras que solo opera en el puntero de referencia , moverá el puntero de referencia y el puntero de referencia de la rama actual. Para demostrar mejor este comportamiento, vamos a analizar el siguiente ejemplo:

Este ejemplo demuestra una secuencia de confirmaciones en la rama . La referencia y la referencia de la rama en esos momentos apuntan a la confirmación d. Ahora vamos a ejecutar y a comparar, tanto como

git checkout b

Con , la referencia sigue apuntando a . La referencia se ha movido y ahora apunta a la confirmación . Ahora el repositorio se encuentra en un estado de » desasociado».

git reset b

En comparación, mueve tanto las referencias de como las de rama a la confirmación especificada.

Además de actualizar los punteros de referencia de las confirmaciones, modificará el estado de los tres árboles. La modificación del puntero de referencia sucede siempre y es una actualización del tercer árbol, el árbol de confirmaciones. Los argumentos de las líneas de comandos , y indican cómo modificar los árboles del índice del entorno de ensayo y del directorio de trabajo.

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

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

Adblock
detector