@ -297,6 +297,7 @@ If you want to see a file at a specific commit, you can also do this (where `<co
$ git show <commitid>:filename
```
<aname="wrong-thing-in-commit-message"></a>
### I wrote the wrong thing in a commit message
If you wrote the wrong thing and the commit has not yet been pushed, you can do the following to change the commit message without changing the changes in the commit:
Or do an [interactive rebase](#interactive-rebase) and remove the line(s) corresponding to commit(s) you want to see removed.
<aname="#force-push"></a>
<aname="force-push"></a>
### I tried to push my amended commit to a remote, but I got an error message
```sh
@ -454,7 +455,7 @@ In general, **avoid force pushing**. It is best to create and push a new commit
If you are *absolutely* sure that nobody is working on the same branch or you want to update the tip of the branch *unconditionally*, you can use `--force` (`-f`), but this should be avoided in general.
<ahref="undo-git-reset-hard"></a>
<aname="undo-git-reset-hard"></a>
### I accidentally did a hard reset, and I want my changes back
If you accidentally do `git reset --hard`, you can normally still get your commit back, as git keeps a log of everything for a few days.
@ -473,7 +474,7 @@ You'll see a list of your past commits, and a commit for the reset. Choose the S
And you should be good to go.
<ahref="undo-a-commit-merge"></a>
<aname="undo-a-commit-merge"></a>
### I accidentally committed and pushed a merge
If you accidentally merged a feature branch to the main development branch before it was ready to be merged, you can still undo the merge. But there's a catch: A merge commit has more than one parent (usually two).
@ -486,7 +487,7 @@ where the -m 1 option says to select parent number 1 (the branch into which the
Note: the parent number is not a commit identifier. Rather, a merge commit has a line `Merge: 8e2ce2d 86ac2e7`. The parent number is the 1-based index of the desired parent on this line, the first identifier is number 1, the second is number 2, and so on.
<ahref="undo-sensitive-commit-push"></a>
<aname="undo-sensitive-commit-push"></a>
### I accidentally committed and pushed files containing sensitive data
If you accidentally pushed files containing sensitive, or private data (passwords, keys, etc.), you can amend the previous commit. Keep in mind that once you have pushed a commit, you should consider any data it contains to be compromised. These steps can remove the sensitive data from your public repo or your local copy, but you **cannot** remove the sensitive data from other people's pulled copies. If you committed a password, **change it immediately**. If you committed a key, **re-generate it immediately**. Amending the pushed commit is not enough, since anyone could have pulled the original commit containing your sensitive data in the meantime.
@ -518,10 +519,10 @@ If you want to completely remove an entire file (and not keep it locally), then
If you have made other commits in the meantime (i.e. the sensitive data is in a commit before the previous commit), you will have to rebase.
### I want to remove a large file from ever existing in repo history
If the file you want to delete is secret or sensitive, instead see [how to remove sensitive files](#i-accidentally-committed-and-pushed-files-containing-sensitive-data).
If the file you want to delete is secret or sensitive, instead see [how to remove sensitive files](#undo-sensitive-commit-push).
Even if you delete a large or unwanted file in a recent commit, it still exists in git history, in your repo's `.git` folder, and will make `git clone` download unneeded files.
@ -592,7 +593,7 @@ If this does not work, you will need to manually push the repo history in chunks
```
Once the push operation succeeds the first time, decrease `<number>` gradually until a conventional `git push` succeeds.
### I need to change the content of a commit which is not my last
Consider you created some (e.g. three) commits and later realize you missed doing something that belongs contextually into the first of those commits. This bothers you, because if you'd create a new commit containing those changes, you'd have a clean code base, but your commits weren't atomic (i.e. changes that belonged to each other weren't in the same commit). In such a situation you may want to change the commit where these changes belong to, include them and have the following commits unaltered. In such a case, `git rebase` might save you.
@ -635,8 +636,7 @@ will do the rest of the work for you.
### I need to add staged changes to the previous commit
```sh
@ -684,17 +684,17 @@ $ git add -N filename.x
Then, you will need to use the `e` option to manually choose which lines to add. Running `git diff --cached` or
`git diff --staged` will show you which lines you have staged compared to which are still saved locally.
<ahref="stage-in-two-commits"></a>
<aname="stage-in-two-commits"></a>
### I want to add changes in one file to two different commits
`git add` will add the entire file to a commit. `git add -p` will allow to interactively select which changes you want to add.
<ahref="selective-unstage-edits"></a>
<aname="selective-unstage-edits"></a>
### I staged too many edits, and I want to break them out into a separate commit
`git reset -p` will open a patch mode reset dialog. This is similar to `git add -p`, except that selecting "yes" will unstage the change, removing it from the upcoming commit.
### I want to stage my unstaged edits, and unstage my staged edits
In many cases, you should unstage all of your staged files and then pick the file you want and commit it. However, if you want to switch the staged and unstaged edits, you can create a temporary commit to store your staged files, stage your unstaged files and then stash them. Then, reset the temporary commit and pop your stash.
@ -712,14 +712,14 @@ NOTE 2: Your staged files will be marked as unstaged if you don't use the `--ind
## Unstaged Edits
<ahref="move-unstaged-edits-to-new-branch"></a>
<aname="move-unstaged-edits-to-new-branch"></a>
### I want to move my unstaged edits to a new branch
```sh
$ git checkout -b my-branch
```
<ahref="move-unstaged-edits-to-old-branch"></a>
<aname="move-unstaged-edits-to-old-branch"></a>
### I want to move my unstaged edits to a different, existing branch
Sometimes we have one or more files that accidentally ended up being staged, and these files have not been committed before. To unstage them:
@ -887,7 +887,7 @@ $ git reset --hard c5bc55a
Done.
<ahref="discard-local-commits"></a>
<aname="discard-local-commits"></a>
### I want to discard local commits so my branch is the same as one on the server
Confirm that you haven't pushed your changes to the server.
@ -1055,7 +1055,7 @@ $ git fetch -p upstream
where, `upstream` is the remote you want to fetch from.
<aname='restore-a-deleted-branch'></a>
<aname="restore-a-deleted-branch"></a>
### I accidentally deleted my branch
If you're regularly pushing to remote, you should be safe most of the time. But still sometimes you may end up deleting your branches. Let's say we create a branch and create a new file:
@ -1179,7 +1179,7 @@ To delete the `old-name` remote branch and push the `new-name` local branch:
### I want to checkout to a remote branch that someone else is working on
First, fetch all branches from remote:
@ -1218,7 +1218,7 @@ With the `upstream` mode and the `simple` (default in Git 2.0) mode of the `push
$ git push
```
The behavior of the other modes of `git push` is described in the [doc of `push.default`](https://git-scm.com/docs/git-config#git-config-pushdefault).
The behavior of the other modes of `git push` is described in the [doc of `push.default`](https://git-scm.com/docs/git-config#Documentation/git-config.txt-pushdefault).
### I want to set a remote branch as the upstream for a local branch
@ -1236,7 +1236,7 @@ To set the upstream remote branch for another local branch:
### I want to set my HEAD to track the default remote branch
By checking your remote branches, you can see which remote branch your HEAD is tracking. In some cases, this is not the desired branch.
@ -1264,7 +1264,7 @@ You've made uncommitted changes and realise you're on the wrong branch. Stash ch
(correct_branch)$ git stash apply
```
<aname="i-want-to-split-a-branch-into-two"></a>
<aname="split-branch-into-two"></a>
### I want to split a branch into two
You've made a lot of commits on a branch and now want to separate it into two, ending with a branch up to an earlier commit and another with all the changes.
@ -1506,7 +1506,7 @@ If you want to keep one branch's version of the code, you can use `--ours` or `-
```
- When *merging*, use `--ours` to keep changes from the local branch, or `--theirs` to keep changes from the other branch.
- When *rebasing*, use `--theirs` to keep changes from the local branch, or `--ours` to keep changes from the other branch. For an explanation of this swap, see [this note in the Git documentation](https://git-scm.com/docs/git-rebase#git-rebase---merge).
- When *rebasing*, use `--theirs` to keep changes from the local branch, or `--ours` to keep changes from the other branch. For an explanation of this swap, see [this note in the Git documentation](https://git-scm.com/docs/git-rebase#Documentation/git-rebase.txt---merge).
If the merges are more complicated, you can use a visual diff editor:
@ -1624,7 +1624,7 @@ Commons parameters:
* `--reverse` prints in reverse order, it means that will show the first commit that made the change.
<aname="i-want-to-find-by-author-committer"></a>
<aname="find-by-committer"></a>
### I want to find by author/committer
To find all commits by author/committer you can use:
@ -1656,7 +1656,7 @@ While using wildcards, it's useful to inform `--name-status` to see the list of
@ -1065,7 +1065,7 @@ Si deseas conservar la versión del código de una rama, puedes usar `--us` o` -
```
- Cuando haces *merge*, usa `--ours` para mantener los cambios de la rama local, o` --theirs` para mantener los cambios de la otra rama.
- Cuando haces *rebase*, usa `--theirs` para mantener los cambios de la rama local, o` --ours` para mantener los cambios de la otra rama. Para obtener una explicación de este intercambio, consulte [esta nota en la documentación de Git] (https://git-scm.com/docs/git-rebase#git-rebase---merge).
- Cuando haces *rebase*, usa `--theirs` para mantener los cambios de la rama local, o` --ours` para mantener los cambios de la otra rama. Para obtener una explicación de este intercambio, consulte [esta nota en la documentación de Git] (https://git-scm.com/docs/git-rebase#Documentation/git-rebase.txt---merge).
Si las fusiones son más complicadas, puede usar un editor visual diff:
@ -174,6 +174,7 @@ Si vous voulez voir un fichier à un commit spécifique, vous pouvez aussi faire
$ git show <commitid>:nomdufichier
```
<aname="wrong-thing-in-commit-message"></a>
### J'ai commis une erreur dans un message de commit
Si vous vous êtes trompé·e et que le commit n'a pas encore été poussé, vous pouvez appliquer la commande suivante afin de changer le message du commit sans affecter les changements de ce même commit :
Ou faites un [rebase interactif](#interactive-rebase) et retirez les lignes correspondantes au(x) commit(s) que vous souhaitez supprimer.
<aname="#force-push"></a>
<aname="force-push"></a>
### J'ai essayé de pousser un commit modifié vers le dépôt distant, mais j'ai eu un message d'erreur
```sh
@ -279,7 +280,7 @@ En règle générale, **évitez de pousser de force**. Il est préférable de cr
Si vous êtes *absolument* sûr·e que personne n'est en train de travailler sur la même branche que vous ou que vous souhaitez mettre à jour la branche de manière *inconditionnelle*, vous pouvez utiliser `--force` (`-f`), mais cela devrait être évité en général.
<ahref="undo-git-reset-hard"></a>
<aname="undo-git-reset-hard"></a>
### J'ai fait un hard reset par accident, et je veux retrouver mes changements
Si vous avez accidentellement fait un `git reset --hard`, vous pouvez normalement retrouver votre commit, car Git garde un log de tout ce que vous faites pendant quelques jours.
@ -298,7 +299,7 @@ Vous verrez une liste de vos précédents commits, et un commit pour la réiniti
Et cela devrait faire l'affaire.
<ahref="undo-a-commit-merge"></a>
<aname="undo-a-commit-merge"></a>
### J'ai commité et poussé une fusion par accident
Si vous avez accidentellement fusionné une branche d'une fonctionnalité avec la branche de développement principale avant qu'elle ne soit prête à être fusionnée, vous pouvez toujours annuler cette fusion. Mais il y a un piège : un commit de fusion a plus d'un parent (en général deux).
@ -312,7 +313,7 @@ où l'option `-m 1` demande de sélectionner le parent numéro 1 (la branche ver
À noter : le numéro du parent n'est pas un identifiant de commit. Un commit de fusion ressemble plus à `Merge: 8e2ce2d 86ac2e7`. Le numéro du parent est l'index basé sur 1 du parent souhaité sur cette ligne, le premier identifiant est le numéro 1, le second le numéro 2, et ainsi de suite.
<ahref="undo-sensitive-commit-push"></a>
<aname="undo-sensitive-commit-push"></a>
### J'ai commité et poussé des fichiers contenant des données sensibles par accident
Si vous avez accidentellement poussé des fichiers contenant des données sensibles (mots de passe, clés, etc.), vous pouvez modifier le commit précédent. Gardez toutefois à l'esprit qu'une fois que vous avez poussé un commit, vous devez considérer n'importe quelle donnée qu'il contient comme étant compromise. Ces étapes peuvent supprimer les données sensibles de votre dépôt public ou de votre copie locale, mais vous ne **pouvez pas** supprimer les données sensibles des copies clonées par d'autres personnes. Si vous avez commité un mot de passe, **changez-le immédiatement**. Si vous avez commité une clé, **révoquez-la et régénérez-la immédiatement**. Modifier le commit poussé n'est pas suffisant, étant donné que n'importe qui aurait pu extraire le commit original contenant vos données sensibles pendant ce temps.
@ -345,7 +346,7 @@ Si vous avez créé d'autres commits pendant ce temps (c'est à dire que les don
### J'ai besoin d'ajouter des modifications indexées sur le commit précédent
```sh
@ -376,12 +377,12 @@ $ git add -N nomdufichier.x
Ensuite, vous devrez utiliser l'option `e` afin de choisir manuellement quelles lignes ajouter. Lancer `git diff --cached` ou `git diff --staged` vous montrera quelles lignes vous avez indexées comparées à celles qui sont toujours sauvegardées en local.
<ahref="stage-in-two-commits"></a>
<aname="stage-in-two-commits"></a>
### Je veux ajouter les changements d'un fichier dans deux commits différents
`git add` ajoutera le fichier entier à un commit. `git add -p` vous permettra de sélectionner interactivement quels changements vous souhaitez ajouter.
### Je veux indexer mes modifications indexées, et désindexer mes modifications indexées
Cela est délicat. La meilleure chose que nous pouvons vous conseiller est que vous devriez remiser vos modifications non indexées, puis utiliser `git reset`. Après cela, utilisez `pop` pour déremiser vos modifications, puis ajoutez-les :
@ -395,14 +396,14 @@ $ git add -A
## Modifications non indexées
<ahref="move-unstaged-edits-to-new-branch"></a>
<aname="move-unstaged-edits-to-new-branch"></a>
### Je veux déplacer mes modifications non indexées vers une nouvelle branche
```sh
$ git checkout -b ma-branche
```
<ahref="move-unstaged-edits-to-old-branch"></a>
<aname="move-unstaged-edits-to-old-branch"></a>
### Je veux déplacer mes modifications non indexées vers une branche différente existante
### Je veux désindexer un fichier indexé spécifique
Il arrive parfois que nous ayons un ou plusieurs fichiers qui ont été indexés par accident. Et ces fichiers n'ont pas été commités auparavant. Pour les désindexer :
@ -568,7 +569,7 @@ $ git reset --hard c5bc55a
Et voilà.
<ahref="discard-local-commits"></a>
<aname="discard-local-commits"></a>
### Je veux supprimer mes commits locaux afin que ma branche soit pareille à celle sur le serveur
Assurez-vous que vous n'avez pas poussé vos modifications sur le serveur.
@ -735,7 +736,7 @@ $ git fetch -p upstream
où `upstream` est le dépôt distant depuis lequel vous voulez mettre à jour.
<aname='restore-a-deleted-branch'></a>
<aname="restore-a-deleted-branch"></a>
### J'ai supprimé ma branche par accident
Si vous poussez régulièrement sur la branche distante, vous devriez ne pas avoir de problème la plupart du temps. Mais il arrive parfois que vous finissez par supprimer vos branches. Admettons que nous créons une nouvelle branche avec un nouveau fichier :
@ -853,7 +854,7 @@ Pour renommer une autre branche (locale) :
### Je veux me déplacer sur une branche distante sur laquelle quelqu'un est en train de travailler
Pour commencer, récupérez toutes les branches depuis le dépôt distant :
@ -892,7 +893,7 @@ Avec le mode `upstream` et le mode `simple` (défaut dans Git 2.0) de la configu
$ git push
```
Le comportement des autres modes de `git push` est détaillé dans la [documentation de `push.default`](https://git-scm.com/docs/git-config#git-config-pushdefault).
Le comportement des autres modes de `git push` est détaillé dans la [documentation de `push.default`](https://git-scm.com/docs/git-config#Documentation/git-config.txt-pushdefault).
### Je veux configurer une branche distante en tant qu'upstream pour une branche locale
@ -910,7 +911,7 @@ Pour configurer la branche distante en tant qu'upstream pour une autre branche l
### Je veux configurer mon HEAD pour suivre la branche distante par défaut
En vérifiant vos branches distantes, vous pouvez voir lesquelles d'entre-elles sont suivies par HEAD. Dans certains cas, ce n'est pas la branche désirée.
@ -1165,7 +1166,7 @@ Si vous voulez garder la version du code d'une des branches, vous pouvez utilise
```
- Quand vous *fusionnez*, utilisez `--ours` pour garder les modifications de la branche locale, ou `--theirs` pour garder les modifications de l'autre branche.
- Quand vous *rebasez*, utilisez `--theirs` pour garder les modifications de la branche locale, ou `--ours` pour garder les modifications de l'autre branche. Pour des explications concernant cet échange, consultez [cette note dans la documentation de Git](https://git-scm.com/docs/git-rebase#git-rebase---merge).
- Quand vous *rebasez*, utilisez `--theirs` pour garder les modifications de la branche locale, ou `--ours` pour garder les modifications de l'autre branche. Pour des explications concernant cet échange, consultez [cette note dans la documentation de Git](https://git-scm.com/docs/git-rebase#Documentation/git-rebase.txt---merge).
Si les fusions sont plus complexes, vous pouvez utiliser un éditeur de diff visuel :
@ -1261,7 +1262,7 @@ Paramètres communs :
* `--reverse` retourne les résultats dans l'ordre inverse, c'est à dire que la commande affichera le premier commit qui a fait la modification.
<aname="i-want-to-find-by-author-committer"></a>
<aname="find-by-committer"></a>
### Je veux rechercher par auteur·trice/validateur·trice
Pour rechercher des commits par auteur·trice/validateur·trice, vous pouvez utiliser :
리모트 브랜치를 확인해보는 것으로, HEAD가 트래킹 중인 리모트 브랜치를 볼 수 있어요. 몇몇 경우에는, 원하던 브랜치가 아닐거에요.
@ -1101,7 +1100,6 @@ noop
* 대신해서 `HEAD~2` 또는 더 기존 항목을 리베이스
<aname="merge-conflict"></a>
#### 충돌이 있어
리베이스를 똑바로 끝내지 못했다면, 충돌을 해결해야 할거에요.
@ -1137,7 +1135,7 @@ Changes not staged for commit:
```
- *머지*할때, `--ours`를 쓰면 로컬 브랜치의 변경점 유지하고, `--theirs` 는 다른 브랜치의 변경점를 유지해요.
- *리베이스*할 땐, `--theirs`가 로컬 브랜치의 변경점을 유지하고 `--ours`는 다른 브랜치의 변경점을 유지해요. 이런 차이에 관한 설명은 Git 정식 문서 중 [이 문서](https://git-scm.com/docs/git-rebase#git-rebase---merge)를 보세요.
- *리베이스*할 땐, `--theirs`가 로컬 브랜치의 변경점을 유지하고 `--ours`는 다른 브랜치의 변경점을 유지해요. 이런 차이에 관한 설명은 Git 정식 문서 중 [이 문서](https://git-scm.com/docs/git-rebase#Documentation/git-rebase.txt---merge)를 보세요.
Или сделайте [интерактивное перебазирование](#interactive-rebase) и удалите строки ненужных коммитов.
<aname="#force-push"></a>
<aname="force-push"></a>
### Я пытаюсь опубликовать исправленный коммит, но получаю сообщение об ошибке
```sh
@ -381,7 +382,7 @@ hint: See the 'Note about fast-forwards' in 'git push --help' for details.
Если Вы *абсолютно* уверены, что никто кроме Вас не работает с данной веткой или Вы хотите обновить вершину ветви в любом случае, то используйте `--force` (`-f`), но вообще этого следует избегать.
<ahref="undo-git-reset-hard"></a>
<aname="undo-git-reset-hard"></a>
### Я случайно сделал жесткий сброс (--hard) и теперь хочу вернуть свои изменения
Если Вы случайно сделали `git reset --hard`, то вы можете вернуть назад коммиты, т.к. Git несколько дней хранит все действия в журнале.
@ -400,7 +401,7 @@ hint: See the 'Note about fast-forwards' in 'git push --help' for details.
И Вы сможете продолжить работу.
<ahref="undo-a-commit-merge"></a>
<aname="undo-a-commit-merge"></a>
### Я случайно опубликовал ненужное слияние
Если Вы случайно сделали слияние в основную ветку разработки до того, как были сделаны все необходимые изменения, Вы по-прежнему можете отменить слияние. Но есть одна загвоздка: Коммит слияния имеет более одного родителя (обычно два).
@ -413,7 +414,7 @@ hint: See the 'Note about fast-forwards' in 'git push --help' for details.
Заметка: номер родителя - это не идентификатор коммита. Допустим, коммит слияния имеет строчку `Merge: 8e2ce2d 86ac2e7`. Номер родителя - это порядковый номер (отсчет с 1) нужного родителя в этой строчке, первый идентификатор - номер 1, второй - номер 2 и т.д.
<ahref="undo-sensitive-commit-push"></a>
<aname="undo-sensitive-commit-push"></a>
### Я случайно закоммитил и опубликовал файлы с конфиденциальными данными
Если Вы случайно опубликовали файлы, содержащие конфиденциальные данные (пароли, ключи и пр.), Вы можете изменить последний коммит с помощью amend. Помните, что как только Вы опубликовали коммит, то Вы должны считать всё его содержание скомпрометированным. С помощью дальнейших шагов можно удалить конфиденциальную информацию из публичного репозиторий или из Вашей локальной копии, вы **не сможете** удалить свою конфиденциальную информацию у людей, которые могли успеть скопировать себе её. Если Вы закоммитили пароль, то **незамедлительно поменяйте его**. Если Вы закоммитили ключ, то **незамедлительно сгенерируйте новый**. Изменения опубликованного коммита недостаточно, потому что кто-нибудь мог скопировать исходный коммит до того, как Вы успели его исправить.
### Я хочу удалить большой файл из истории репозитория
Если вы хотите удалить пароль или другую конфиденциальную информацию, то вместо этого смотрите [Я случайно закоммитил и опубликовал файлы с конфиденциальными данными](#%D0%AF-%D1%81%D0%BB%D1%83%D1%87%D0%B0%D0%B9%D0%BD%D0%BE-%D0%B7%D0%B0%D0%BA%D0%BE%D0%BC%D0%BC%D0%B8%D1%82%D0%B8%D0%BB-%D0%B8-%D0%BE%D0%BF%D1%83%D0%B1%D0%BB%D0%B8%D0%BA%D0%BE%D0%B2%D0%B0%D0%BB-%D1%84%D0%B0%D0%B9%D0%BB%D1%8B-%D1%81-%D0%BA%D0%BE%D0%BD%D1%84%D0%B8%D0%B4%D0%B5%D0%BD%D1%86%D0%B8%D0%B0%D0%BB%D1%8C%D0%BD%D1%8B%D0%BC%D0%B8-%D0%B4%D0%B0%D0%BD%D0%BD%D1%8B%D0%BC%D0%B8).
Если вы хотите удалить пароль или другую конфиденциальную информацию, то вместо этого смотрите [Я случайно закоммитил и опубликовал файлы с конфиденциальными данными](#undo-sensitive-commit-push).
Даже если вы удалите большие или ненужные файлы из последнего коммита, они останутся в истоии Git, в подкаталоге `.git` вашего репозитория и `git clone` будет загружать ненужные файлы.
### Мне нужно изменить содержимое коммита, который не является последним
Пусть Вы сделали несколько (например, три) коммитов и после этого поняли, что упустили что-то, что по смыслу относится к первому из этих трёх коммитов. Вы могли бы сделать новый коммит, содержащий эти изменения, и тогда уВас была бы чистая кодовая база, но Ваши коммиты не были бы атомарными (т.е. связанные изменения не содержались бы в едином коммите). В такой ситуации Вы бы хотели изменить коммит, к которому относятся эти изменения, а следующие коммиты оставить как есть. В таком случае Вас может спасти `git rebase`.
### Мне нужно добавить подготовленные изменения в предыдущий коммит
```sh
@ -590,17 +591,17 @@ $ git add -N filename.x
Затем используйте опцию `e` для ручного выбора строк. Запустив `git diff --cached` или
`git diff --staged`, Вы увидите какие строки вы подготовили по-сравнению с тем, что сохранено в рабочей копии.
<ahref="stage-in-two-commits"></a>
<aname="stage-in-two-commits"></a>
### Я хочу добавить изменения одного файла в два разных коммита
`git add` добавляет в коммит весь файл целиком. `git add -p` позволяет интерактивно выбрать изменения, которые Вы хотите добавить.
<ahref="selective-unstage-edits"></a>
<aname="selective-unstage-edits"></a>
### Я подготовил слишком много правок и теперь хочу разделить их на несколько отдельных коммитов
`git reset -p` откроет интерактивный диалог сброса. Это похоже на `git add -p`, за исключением того, что выбор "yes" уберёт правку из готовящегося коммита.
### Я хочу подготовить свои неподготовленные правки и убрать из подготовки то, что уже подготовлено
Это сложно. Лучшее, что я смог придумать это отложить (stash) неподготовленные изменения. Затем сделать сброс. После этого вернуть отложенные изменения и добавить их.
@ -614,14 +615,14 @@ $ git add -A
## Неподготовленные правки
<ahref="move-unstaged-edits-to-new-branch"></a>
<aname="move-unstaged-edits-to-new-branch"></a>
### Я хочу переместить мои неподготовленные правки в новую ветку
```sh
$ git checkout -b my-branch
```
<ahref="move-unstaged-edits-to-old-branch"></a>
<aname="move-unstaged-edits-to-old-branch"></a>
### Я хочу переместить неподготовленные правки в другую существующую ветку
### Я хочу настроить HEAD на отслеживание основной удаленной ветки
При просмотре удаленных веток можно увидеть какую удаленную ветку отслеживает HEAD. Может оказаться, что это не та ветка что нужно.
@ -1386,7 +1387,7 @@ Changes not staged for commit:
```
- Во время *слияния* используйте `--ours` для сохранения изменений из локальной ветки или `--theirs` для сохранения изменений из другой ветки.
- Во время *перебазирования* используйте `--theirs` для сохранения изменений из локальной ветки или `--ours` для сохранения изменений из другой ветки. Для объяснения такого обмена см. [эту заметку в документации Git](https://git-scm.com/docs/git-rebase#git-rebase---merge).
- Во время *перебазирования* используйте `--theirs` для сохранения изменений из локальной ветки или `--ours` для сохранения изменений из другой ветки. Для объяснения такого обмена см. [эту заметку в документации Git](https://git-scm.com/docs/git-rebase#Documentation/git-rebase.txt---merge).
Если слияние более сложное, можете воспользоваться визуальным редактором различий:
Hoặc thực hiện một [interactive rebase](#interactive-rebase) và loại bỏ các dòng tương ứng với các commit bạn muốn loại bỏ.
<aname="#force-push"></a>
<aname="force-push"></a>
### Tôi đã cố gắng push commit đã sửa đổi lên remote, nhưng tôi gặp thông báo lỗi
```sh
@ -401,7 +402,7 @@ Nói chung, **tránh force push**. Tốt nhất là tạo và push một commit
Nếu bạn *hoàn toàn chắc chắn* rằng không ai đang làm việc trên cùng một nhánh hoặc bạn muốn cập nhật đỉnh nhánh (tip of branch) *vô điều kiện*, bạn có thể sử dụng `--force` (`-f`), nhưng cách này nói chung nên tránh.
<ahref="undo-git-reset-hard"></a>
<aname="undo-git-reset-hard"></a>
### Tôi đã vô tình thực hiện hard reset và tôi muốn các thay đổi của tôi.
Nếu vô tình bạn thực hiện `git reset --hard`, bạn có thể vẫn phục hồi lại được commit của bạn, vì git giữ một bản log cho tất cả mọi thứ trong vài ngày.
@ -420,7 +421,7 @@ Bạn sẽ thấy danh sách các commit gần đây và một commit để rese
Thế này là xong.
<ahref="undo-a-commit-merge"></a>
<aname="undo-a-commit-merge"></a>
### Tôi vô tình commit và đẩy lên một merge
Nếu bạn vô tình merge một nhánh tính năng mới vào nhánh phát triển chính trước khi sẵn sàng để merge, bạn vẫn có thể đảo ngược merge. Nhưng có một điểm phải nắm được: Một commit merge có một hoặc nhiều hơn một parent (gốc) (thường là 2).
@ -433,7 +434,7 @@ Dòng `-m 1` là để cho biết cần chọn parent thứ nhất` (nhánh mà
Chú ý: Số parent không phải là số commit. Thay vào đó, một commit merge sẽ có một dòng như `Merge: 8e2ce2d 86ac2e7`. Số parent là số số nhận dạng đầu-1 (1-based index) của dòng nay, số nhận dạng đầu tiên là 1 cho parent thứ nhất, thứ 2 là cho parent 2, và tiếp tục như thế.
<ahref="undo-sensitive-commit-push"></a>
<aname="undo-sensitive-commit-push"></a>
### Tôi vô tình commit và đẩy các file chứa dữ liệu nhảy cảm
Nếu bạn vô tình push lên các file chứa dữ liệu nhạy cảm (mật khẩu, keys, etc.), bạn có thể amend commit trước. Lưu ý rằng khi bạn đã đẩy một commit, bạn nên coi bất kỳ dữ liệu nào đã bị đẩy như đã bị lộ. Các bước này có thể xoá dữ liệu nhạy cảm từ repo công khai (public repo) hoặc bản sao nội bộ, nhưng bạn *không thể* xóa dữ liệu nhạy cảm khỏi các bản sao đã được tải về bởi người khác. Nếu bạn có commit mật khẩu, *hãy thay đổi mật khẩu ngay lập tức*. Nếu bạn đã commit một key, *hãy tạo lại key đó ngay lập tức*. Việc amend commit đã đẩy là không đủ, vì bất kỳ ai cũng có thể đã pull commit chứa dữ liệu nhạy cảm của bạn trong thời gian đấy.
@ -465,7 +466,7 @@ Nếu bạn muốn xóa hoàn toàn toàn bộ tệp (và không giữ tệp t
Nếu bạn đã thực hiện các commit khác (tức là dữ liệu nhạy cảm nằm tại commit trước commit mới nhất), bạn sẽ phải rebase.
### Tôi cần thay đổi nội dung của một commit nhưng không phải là cái mới nhất
Giả sử bạn đã có vài (v.d. ba) commit và sau nhận ra là bạn quên mất không cho vào một thứ gì đó hợp hơn với commit đầu tiên. Việc này làm phiền bạn vì mặc dù nếu tiếp tục commit bạn sẽ có lịch sử sạch sẽ nhưng commit của bạn không nguyên chất (những thay đổi liên quan với nhau nên ở cùng một commit). Trong trường hợp như vậy, bạn chắc muốn cho thêm những thay đổi liên quan vào commit mong muốn nhưng không muốn những commit sau tiếp cũng phải sửa theo. Trong trường hợp như vây, `git rebase` có thể cứu bạn.
@ -582,8 +583,7 @@ Lệnh trên sẽ giải quyết phần còn lại.
### Tôi cần cho thêm các thay đổi đang trong stage vào commit trước
```sh
@ -631,17 +631,17 @@ $ git add -N filename.x
Sau đó, bạn sẽ cần sử dụng `e` để thủ công thêm dòng. Chạy lệnh `git diff --cached` hoặc
`git diff --staged` sẽ cho bạn thấy những dòng bạn đã stage so với những dòng vẫn lưu ở local.
<ahref="stage-in-two-commits"></a>
<aname="stage-in-two-commits"></a>
### Tôi muốn thêm các thay đổi trong một file vào 2 commit khác nhau
`git add` sẽ thêm toàn bộ file vào một commit. `git add -p` sẽ cho vào chế độ tương tác để chọn những thay đổi bạn muốn thêm vào.
<ahref="selective-unstage-edits"></a>
<aname="selective-unstage-edits"></a>
### Tôi cho lên stage quá nhiều thay đổi, và tôi muốn tách ra thành các commit khác nhau
`git reset -p` sẽ mở chế độ patch và hộp thoại để reset. Việc này sẽ giống như với lệnh `git add -p`, ngoại trừ là việc chọn "yes" sẽ đưa thay đổi khỏi stage, loại trừ nó khỏi commit tiếp đến.
### Tôi muốn cho lên stage các chỉnh sửa chưa được stage và hã khỏi stage các chỉnh sửa đã stage
Phần lớn thời gian, bạn nên hạ tất cả các file đã trên stage và chọn lại những file bạn muốn commit.Nhưng giả sử bạn muốn thay các thay đổi lên và hạ stage, bạn có thể tạo một commit tạm thời, nâng lên stage các thay đổi, rồi stash (cất) nó. Sau đó, reset cái commit tạm thời rồi pop cái stage bạn vừa cất.
@ -659,14 +659,14 @@ GHI CHÚ 2: Các file đã nâng lên stage sẽ bị hạ nếu không có thê
## Thay đổi chưa lên sân (Unstaged Edits)
<ahref="move-unstaged-edits-to-new-branch"></a>
<aname="move-unstaged-edits-to-new-branch"></a>
### Tôi muốn di chuyển các chỉnh sửa chưa lên stage sang một nhánh mới
```sh
$ git checkout -b nhánh-mới
```
<ahref="move-unstaged-edits-to-old-branch"></a>
<aname="move-unstaged-edits-to-old-branch"></a>
### Tôi muốn di chuyển các chỉnh sửa chưa stage của tôi đến một nhánh khác đã tồn tại
### Tôi muốn hạ khỏi stage một file cụ thể đã stage
Đôi khi, chúng ta có một hoặc nhiều file đã vô tình lên stage và các file này chưa được commit trước đó. Để hạ chúng khỏi stage:
@ -834,7 +834,7 @@ $ git reset --hard c5bc55a
Xong.
<ahref="discard-local-commits"></a>
<aname="discard-local-commits"></a>
### Tôi muốn loại bỏ các commit tại local để nhánh của tôi giống như nhánh trên server
Kiểm tra rằng bạn chưa push các thay đổi của mình đến server.
@ -975,7 +975,7 @@ Bây giờ, hãy *cherry-pick* commit cho bug #21 trên đầu của nhánh. Nó
(21)$ git cherry-pick e3851e8
```
Tại thời điểm này, có khả năng có thể có xung đột hợp (merge conflicts). Hãy xem phần [**There were conflicts**](#merge-conflict) trong [phần interactive rebasing ở trên](#interactive-rebase) để làm thế nào giải quyết xung đột hợp.
Tại thời điểm này, có khả năng có thể có xung đột hợp (merge conflicts). Hãy xem phần [**Có một vài xung đột**](#merge-conflict) trong [phần interactive rebasing ở trên](#interactive-rebase) để làm thế nào giải quyết xung đột hợp.
Bây giờ chúng ta hãy tạo một nhánh mới cho bug # 14, cũng dựa trên nhánh main:
@ -1002,7 +1002,7 @@ $ git fetch -p upstream
upstream` là remote bạn muốn fetch (gọi) về.
<aname='restore-a-deleted-branch'></a>
<aname="restore-a-deleted-branch"></a>
### Tôi vô tình xóa nhánh của tôi
Nếu bạn thường xuyên push lên remote, bạn sẽ an toàn phần lớn thời gian. Nhưng đôi khi bạn có thể sẽ xóa các nhánh của bạn. Giả sử chúng ta tạo một nhánh và tạo một tệp mới:
@ -1126,7 +1126,7 @@ Giả sử bạn muốn xoá tất cả các nhánh bắt đầu với `fix/`:
### Tôi muốn checkout đến một nhánh remote mà người khác đang làm việc trên đó
Đầu tiên, fetch tất cả nhánh từ remote:
@ -1165,7 +1165,7 @@ Với chế độ `upstream` và `simple` (mặc định trong Git 2.0) của c
$ git push
```
Các hành vi của các chế độ khác của `git push` được mô tả trong [doc cho `push.default`](https://git-scm.com/docs/git-config#git-config-pushdefault).
Các hành vi của các chế độ khác của `git push` được mô tả trong [doc cho `push.default`](https://git-scm.com/docs/git-config#Documentation/git-config.txt-pushdefault).
### Tôi muốn thiết lập một nhánh remote làm upstream (luồng trước) cho một nhánh local
### Tôi muốn để HEAD của tôi dõi theo nhánh mặc định của remote
Bằng cách kiểm tra các nhánh remote của bạn, bạn có thể thấy nhánh remote nào mà HEAD của bạn đang theo dõi. Trong một số trường hợp, có thể đấy không phải là nhánh mong muốn.
@ -1211,7 +1211,7 @@ Bạn đã thực hiện các thay đổi chưa được commit và nhận ra b
(correct_branch)$ git stash apply
```
<aname="i-want-to-split-a-branch-into-two"></a>
<aname="split-branch-into-two"></a>
### Tôi muốn tách một nhánh thành hai
Bạn đã tạo rất nhiều commit trên một nhành và bây giờ bạn muốn tách nhánh ra thành hai, một nhánh kết thúc với một commit cũ, và một nhánh với tất cả các thay đổi.
@ -1453,7 +1453,7 @@ Nếu bạn muốn giữ phiên bản code của một nhánh, bạn có thể s
```
- Khi *đang merge*, sử dụng `--ours` để giữ các thay đổi từ nhánh local, hoặc `--theirs` để giữ các thay đổi từ nhánh khác.
- Khi *đang rebase*, sử dụng `--theirs` để giữ các thay đổi từ nhánh local, hoặc `--ours` để giữ các thay đổi từ nhánh khác. Để hiểu giải thích về sự hoán đổi này, hãy xem [ghi chú này trong tài liệu Git](https://git-scm.com/docs/git-rebase#git-rebase---merge).
- Khi *đang rebase*, sử dụng `--theirs` để giữ các thay đổi từ nhánh local, hoặc `--ours` để giữ các thay đổi từ nhánh khác. Để hiểu giải thích về sự hoán đổi này, hãy xem [ghi chú này trong tài liệu Git](https://git-scm.com/docs/git-rebase#Documentation/git-rebase.txt---merge).
Nếu việc merge phức tạp hơn, bạn có thể sử dụng trình chỉnh sửa khác biệt trực quan (visual diff editor):
@ -1571,7 +1571,7 @@ Các cờ thường dùng:
* `--reverse` in theo thứ tự ngược lại, có nghĩa là hiển thị commit đầu tiên đã thực hiện thay đổi.
<aname="i-want-to-find-by-author-committer"></a>
<aname="find-by-committer"></a>
### Tôi muốn tìm tác giả hoặc người commit
Để tìm tất cả commit từ tác giả hoặc người commit bạn có thể sử dụng:
@ -1603,7 +1603,7 @@ Trong khi sử dụng ký tự đại diện bất kỳ, sẽ hữu ích hơn kh