Showing preview only (614K chars total). Download the full file or copy to clipboard to get everything.
Repository: k88hudson/git-flight-rules
Branch: master
Commit: 80d27e63e154
Files: 14
Total size: 597.7 KB
Directory structure:
gitextract_i6mlkrch/
├── .gitignore
├── .travis.yml
├── CONTRIBUTE.md
├── LICENSE
├── README.md
├── README_es.md
├── README_fr.md
├── README_ja.md
├── README_kr.md
├── README_ru.md
├── README_vi.md
├── README_zh-CN.md
├── README_zh-TW.md
└── package.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
node_modules/
package-lock.json
================================================
FILE: .travis.yml
================================================
language: ruby
rvm:
- 2.2
before_script:
- gem install awesome_bot
- npm install
script:
- awesome_bot README.md --allow-dupe --allow-redirect --allow-ssl
- awesome_bot README_*.md --allow-dupe --allow-redirect --allow-ssl
- npm run toc
- npm run diff
================================================
FILE: CONTRIBUTE.md
================================================
# Contributing
This is a community built document. Dive in and help out!
### Issues
- Please jump in and help us out by making PRs for open issues.
- If you see anything you'd think could be improved, feel free to open an issue. This doesn't just mean for new additions you'd like to see - although those are very appreciated, too.
### Pull Requests
- Please title your pull requests appropriately, summing up what your commits are about.
- Make sure that your submission doesn't exist somewhere else in the document.
- If you can, run `doctoc README.md` before adding a new section, or after editing a section - this keeps the Table of Contents up to date. If you don't have it, you can install [DocToc here](https://github.com/thlorenz/doctoc).
- Include the relevant branch before the `$` in a shell command, if needed. If not needed, please do not include a branch name.
- Please label code blocks as `sh` to help out [linguist](https://github.com/github/linguist), unless the language is different.
- Try and put relevant flight rules in the same general area of the document - deletes with deletes, commit amends with commit amends, and so on. We're working on making this better, so no worries if it is confusing - just throw the submission on the end.
- Link to places you found answers or procedures if especially complicated, or if linking to a larger discussion of how to do something. This normally means linking to Stack Overflow.
- Generally, conform to this schema:
<a name="example-title"></a>
# Example Title
Brief description of the problem.
```sh
(relevant branch)$ git blah blah
```
## Translation
We use a translation tool called [GitLocalize][gl]. Please follow these steps to get started with your contributions:
1. Go to [GitLocalize's k88hudson/git-flight-rules repository][gl-repo].
1. Sign up using your GitHub account :octocat:.
1. Find the document you are going to translate.
1. Happy translating :sparkles: .
1. When you are done, send the translation for reviews.
1. The reviewed translation will be sent as a Pull Request to GitHub by the language moderator in the community.
To learn more about how GitLocalize works, visit their [help page][gl-help]. If you find any issues or feature requests, please file them in [GitLocalize's issue tracker][gl-issue-tracker].
[gl]: https://gitlocalize.com
[gl-help]: https://docs.gitlocalize.com/
[gl-issue-tracker]: https://github.com/gitlocalize/feedback
[gl-repo]: https://gitlocalize.com/repo/598
================================================
FILE: LICENSE
================================================
Attribution-ShareAlike 4.0 International
=======================================================================
Creative Commons Corporation ("Creative Commons") is not a law firm and
does not provide legal services or legal advice. Distribution of
Creative Commons public licenses does not create a lawyer-client or
other relationship. Creative Commons makes its licenses and related
information available on an "as-is" basis. Creative Commons gives no
warranties regarding its licenses, any material licensed under their
terms and conditions, or any related information. Creative Commons
disclaims all liability for damages resulting from their use to the
fullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and
conditions that creators and other rights holders may use to share
original works of authorship and other material subject to copyright
and certain other rights specified in the public license below. The
following considerations are for informational purposes only, are not
exhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are
intended for use by those authorized to give the public
permission to use material in ways otherwise restricted by
copyright and certain other rights. Our licenses are
irrevocable. Licensors should read and understand the terms
and conditions of the license they choose before applying it.
Licensors should also secure all rights necessary before
applying our licenses so that the public can reuse the
material as expected. Licensors should clearly mark any
material not subject to the license. This includes other CC-
licensed material, or material used under an exception or
limitation to copyright. More considerations for licensors:
wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public
licenses, a licensor grants the public permission to use the
licensed material under specified terms and conditions. If
the licensor's permission is not necessary for any reason--for
example, because of any applicable exception or limitation to
copyright--then that use is not regulated by the license. Our
licenses grant only permissions under copyright and certain
other rights that a licensor has authority to grant. Use of
the licensed material may still be restricted for other
reasons, including because others have copyright or other
rights in the material. A licensor may make special requests,
such as asking that all changes be marked or described.
Although not required by our licenses, you are encouraged to
respect those requests where reasonable. More_considerations
for the public:
wiki.creativecommons.org/Considerations_for_licensees
=======================================================================
Creative Commons Attribution-ShareAlike 4.0 International Public
License
By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution-ShareAlike 4.0 International Public License ("Public
License"). To the extent this Public License may be interpreted as a
contract, You are granted the Licensed Rights in consideration of Your
acceptance of these terms and conditions, and the Licensor grants You
such rights in consideration of benefits the Licensor receives from
making the Licensed Material available under these terms and
conditions.
Section 1 -- Definitions.
a. Adapted Material means material subject to Copyright and Similar
Rights that is derived from or based upon the Licensed Material
and in which the Licensed Material is translated, altered,
arranged, transformed, or otherwise modified in a manner requiring
permission under the Copyright and Similar Rights held by the
Licensor. For purposes of this Public License, where the Licensed
Material is a musical work, performance, or sound recording,
Adapted Material is always produced where the Licensed Material is
synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright
and Similar Rights in Your contributions to Adapted Material in
accordance with the terms and conditions of this Public License.
c. BY-SA Compatible License means a license listed at
creativecommons.org/compatiblelicenses, approved by Creative
Commons as essentially the equivalent of this Public License.
d. Copyright and Similar Rights means copyright and/or similar rights
closely related to copyright including, without limitation,
performance, broadcast, sound recording, and Sui Generis Database
Rights, without regard to how the rights are labeled or
categorized. For purposes of this Public License, the rights
specified in Section 2(b)(1)-(2) are not Copyright and Similar
Rights.
e. Effective Technological Measures means those measures that, in the
absence of proper authority, may not be circumvented under laws
fulfilling obligations under Article 11 of the WIPO Copyright
Treaty adopted on December 20, 1996, and/or similar international
agreements.
f. Exceptions and Limitations means fair use, fair dealing, and/or
any other exception or limitation to Copyright and Similar Rights
that applies to Your use of the Licensed Material.
g. License Elements means the license attributes listed in the name
of a Creative Commons Public License. The License Elements of this
Public License are Attribution and ShareAlike.
h. Licensed Material means the artistic or literary work, database,
or other material to which the Licensor applied this Public
License.
i. Licensed Rights means the rights granted to You subject to the
terms and conditions of this Public License, which are limited to
all Copyright and Similar Rights that apply to Your use of the
Licensed Material and that the Licensor has authority to license.
j. Licensor means the individual(s) or entity(ies) granting rights
under this Public License.
k. Share means to provide material to the public by any means or
process that requires permission under the Licensed Rights, such
as reproduction, public display, public performance, distribution,
dissemination, communication, or importation, and to make material
available to the public including in ways that members of the
public may access the material from a place and at a time
individually chosen by them.
l. Sui Generis Database Rights means rights other than copyright
resulting from Directive 96/9/EC of the European Parliament and of
the Council of 11 March 1996 on the legal protection of databases,
as amended and/or succeeded, as well as other essentially
equivalent rights anywhere in the world.
m. You means the individual or entity exercising the Licensed Rights
under this Public License. Your has a corresponding meaning.
Section 2 -- Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License,
the Licensor hereby grants You a worldwide, royalty-free,
non-sublicensable, non-exclusive, irrevocable license to
exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or
in part; and
b. produce, reproduce, and Share Adapted Material.
2. Exceptions and Limitations. For the avoidance of doubt, where
Exceptions and Limitations apply to Your use, this Public
License does not apply, and You do not need to comply with
its terms and conditions.
3. Term. The term of this Public License is specified in Section
6(a).
4. Media and formats; technical modifications allowed. The
Licensor authorizes You to exercise the Licensed Rights in
all media and formats whether now known or hereafter created,
and to make technical modifications necessary to do so. The
Licensor waives and/or agrees not to assert any right or
authority to forbid You from making technical modifications
necessary to exercise the Licensed Rights, including
technical modifications necessary to circumvent Effective
Technological Measures. For purposes of this Public License,
simply making modifications authorized by this Section 2(a)
(4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor -- Licensed Material. Every
recipient of the Licensed Material automatically
receives an offer from the Licensor to exercise the
Licensed Rights under the terms and conditions of this
Public License.
b. Additional offer from the Licensor -- Adapted Material.
Every recipient of Adapted Material from You
automatically receives an offer from the Licensor to
exercise the Licensed Rights in the Adapted Material
under the conditions of the Adapter's License You apply.
c. No downstream restrictions. You may not offer or impose
any additional or different terms or conditions on, or
apply any Effective Technological Measures to, the
Licensed Material if doing so restricts exercise of the
Licensed Rights by any recipient of the Licensed
Material.
6. No endorsement. Nothing in this Public License constitutes or
may be construed as permission to assert or imply that You
are, or that Your use of the Licensed Material is, connected
with, or sponsored, endorsed, or granted official status by,
the Licensor or others designated to receive attribution as
provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not
licensed under this Public License, nor are publicity,
privacy, and/or other similar personality rights; however, to
the extent possible, the Licensor waives and/or agrees not to
assert any such rights held by the Licensor to the limited
extent necessary to allow You to exercise the Licensed
Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this
Public License.
3. To the extent possible, the Licensor waives any right to
collect royalties from You for the exercise of the Licensed
Rights, whether directly or through a collecting society
under any voluntary or waivable statutory or compulsory
licensing scheme. In all other cases the Licensor expressly
reserves any right to collect such royalties.
Section 3 -- License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the
following conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified
form), You must:
a. retain the following if it is supplied by the Licensor
with the Licensed Material:
i. identification of the creator(s) of the Licensed
Material and any others designated to receive
attribution, in any reasonable manner requested by
the Licensor (including by pseudonym if
designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of
warranties;
v. a URI or hyperlink to the Licensed Material to the
extent reasonably practicable;
b. indicate if You modified the Licensed Material and
retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this
Public License, and include the text of, or the URI or
hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any
reasonable manner based on the medium, means, and context in
which You Share the Licensed Material. For example, it may be
reasonable to satisfy the conditions by providing a URI or
hyperlink to a resource that includes the required
information.
3. If requested by the Licensor, You must remove any of the
information required by Section 3(a)(1)(A) to the extent
reasonably practicable.
b. ShareAlike.
In addition to the conditions in Section 3(a), if You Share
Adapted Material You produce, the following conditions also apply.
1. The Adapter's License You apply must be a Creative Commons
license with the same License Elements, this version or
later, or a BY-SA Compatible License.
2. You must include the text of, or the URI or hyperlink to, the
Adapter's License You apply. You may satisfy this condition
in any reasonable manner based on the medium, means, and
context in which You Share Adapted Material.
3. You may not offer or impose any additional or different terms
or conditions on, or apply any Effective Technological
Measures to, Adapted Material that restrict exercise of the
rights granted under the Adapter's License You apply.
Section 4 -- Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that
apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
to extract, reuse, reproduce, and Share all or a substantial
portion of the contents of the database;
b. if You include all or a substantial portion of the database
contents in a database in which You have Sui Generis Database
Rights, then the database in which You have Sui Generis Database
Rights (but not its individual contents) is Adapted Material,
including for purposes of Section 3(b); and
c. You must comply with the conditions in Section 3(a) if You Share
all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not
replace Your obligations under this Public License where the Licensed
Rights include other Copyright and Similar Rights.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
c. The disclaimer of warranties and limitation of liability provided
above shall be interpreted in a manner that, to the extent
possible, most closely approximates an absolute disclaimer and
waiver of all liability.
Section 6 -- Term and Termination.
a. This Public License applies for the term of the Copyright and
Similar Rights licensed here. However, if You fail to comply with
this Public License, then Your rights under this Public License
terminate automatically.
b. Where Your right to use the Licensed Material has terminated under
Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided
it is cured within 30 days of Your discovery of the
violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any
right the Licensor may have to seek remedies for Your violations
of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the
Licensed Material under separate terms or conditions or stop
distributing the Licensed Material at any time; however, doing so
will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
License.
Section 7 -- Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different
terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the
Licensed Material not stated herein are separate from and
independent of the terms and conditions of this Public License.
Section 8 -- Interpretation.
a. For the avoidance of doubt, this Public License does not, and
shall not be interpreted to, reduce, limit, restrict, or impose
conditions on any use of the Licensed Material that could lawfully
be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is
deemed unenforceable, it shall be automatically reformed to the
minimum extent necessary to make it enforceable. If the provision
cannot be reformed, it shall be severed from this Public License
without affecting the enforceability of the remaining terms and
conditions.
c. No term or condition of this Public License will be waived and no
failure to comply consented to unless expressly agreed to by the
Licensor.
d. Nothing in this Public License constitutes or may be interpreted
as a limitation upon, or waiver of, any privileges and immunities
that apply to the Licensor or You, including from the legal
processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its public
licenses. Notwithstanding, Creative Commons may elect to apply one of
its public licenses to material it publishes and in those instances
will be considered the “Licensor.” The text of the Creative Commons
public licenses is dedicated to the public domain under the CC0 Public
Domain Dedication. Except for the limited purpose of indicating that
material is shared under a Creative Commons public license or as
otherwise permitted by the Creative Commons policies published at
creativecommons.org/policies, Creative Commons does not authorize the
use of the trademark "Creative Commons" or any other trademark or logo
of Creative Commons without its prior written consent including,
without limitation, in connection with any unauthorized modifications
to any of its public licenses or any other arrangements,
understandings, or agreements concerning use of licensed material. For
the avoidance of doubt, this paragraph does not form part of the
public licenses.
Creative Commons may be contacted at creativecommons.org.
================================================
FILE: README.md
================================================
# Flight rules for Git
🌍
*[English](README.md) ∙ [Español](README_es.md) ∙ [Русский](README_ru.md) ∙ [繁體中文](README_zh-TW.md) ∙ [简体中文](README_zh-CN.md) ∙ [한국어](README_kr.md) ∙ [Tiếng Việt](README_vi.md) ∙ [Français](README_fr.md) ∙ [日本語](README_ja.md)*
#### What are "flight rules"?
A guide for astronauts (now, programmers using Git) about what to do when things go wrong.
> *Flight Rules* are the hard-earned body of knowledge recorded in manuals that list, step-by-step, what to do if X occurs, and why. Essentially, they are extremely detailed, scenario-specific standard operating procedures. [...]
> NASA has been capturing our missteps, disasters and solutions since the early 1960s, when Mercury-era ground teams first started gathering "lessons learned" into a compendium that now lists thousands of problematic situations, from engine failure to busted hatch handles to computer glitches, and their solutions.
— Chris Hadfield, *An Astronaut's Guide to Life on Earth*.
#### Conventions for this document
For clarity's sake all examples in this document use a customized bash prompt in order to indicate the current branch and whether or not there are staged changes. The branch is enclosed in parentheses, and a `*` next to the branch name indicates staged changes.
All commands should work for at least git version 2.13.0. See the [git website](https://www.git-scm.com/) to update your local git version.
[](https://gitter.im/k88hudson/git-flight-rules?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
**Table of Contents** *generated with [DocToc](https://github.com/thlorenz/doctoc)*
- [Repositories](#repositories)
- [I want to start a local repository](#i-want-to-start-a-local-repository)
- [I want to clone a remote repository](#i-want-to-clone-a-remote-repository)
- [I set the wrong remote repository](#i-set-the-wrong-remote-repository)
- [I want to add code to someone else's repository](#i-want-to-add-code-to-someone-elses-repository)
- [Suggesting code via pull requests](#suggesting-code-via-pull-requests)
- [Suggesting code via patches](#suggesting-code-via-patches)
- [I need to update my fork with latest updates from the original repository](#i-need-to-update-my-fork-with-latest-updates-from-the-original-repository)
- [Editing Commits](#editing-commits)
- [What did I just commit?](#what-did-i-just-commit)
- [I wrote the wrong thing in a commit message](#i-wrote-the-wrong-thing-in-a-commit-message)
- [I committed with the wrong name and email configured](#i-committed-with-the-wrong-name-and-email-configured)
- [I want to remove a file from the previous commit](#i-want-to-remove-a-file-from-the-previous-commit)
- [I want to move a change from one commit to another](#i-want-to-move-a-change-from-one-commit-to-another)
- [I want to delete or remove my last commit](#i-want-to-delete-or-remove-my-last-commit)
- [Delete/remove arbitrary commit](#deleteremove-arbitrary-commit)
- [I tried to push my amended commit to a remote, but I got an error message](#i-tried-to-push-my-amended-commit-to-a-remote-but-i-got-an-error-message)
- [I accidentally did a hard reset, and I want my changes back](#i-accidentally-did-a-hard-reset-and-i-want-my-changes-back)
- [I accidentally committed and pushed a merge](#i-accidentally-committed-and-pushed-a-merge)
- [I accidentally committed and pushed files containing sensitive data](#i-accidentally-committed-and-pushed-files-containing-sensitive-data)
- [I want to remove a large file from ever existing in repo history](#i-want-to-remove-a-large-file-from-ever-existing-in-repo-history)
- [Recommended Technique: Use third-party bfg](#recommended-technique-use-third-party-bfg)
- [Built-in Technique: Use git-filter-branch](#built-in-technique-use-git-filter-branch)
- [Final Step: Pushing your changed repo history](#final-step-pushing-your-changed-repo-history)
- [I need to change the content of a commit which is not my last](#i-need-to-change-the-content-of-a-commit-which-is-not-my-last)
- [Staging](#staging)
- [I want to stage all tracked files and leave untracked files](#i-want-to-stage-all-tracked-files-and-leave-untracked-files)
- [To stage part of tracked files](#to-stage-part-of-tracked-files)
- [I need to add staged changes to the previous commit](#i-need-to-add-staged-changes-to-the-previous-commit)
- [I want to stage part of a new file, but not the whole file](#i-want-to-stage-part-of-a-new-file-but-not-the-whole-file)
- [I want to add changes in one file to two different commits](#i-want-to-add-changes-in-one-file-to-two-different-commits)
- [I staged too many edits, and I want to break them out into a separate commit](#i-staged-too-many-edits-and-i-want-to-break-them-out-into-a-separate-commit)
- [I want to stage my unstaged edits, and unstage my staged edits](#i-want-to-stage-my-unstaged-edits-and-unstage-my-staged-edits)
- [I want to unstage a specific staged file](#i-want-to-unstage-a-specific-staged-file)
- [Discarding changes](#discarding-changes)
- [I want to discard my local uncommitted changes (staged and unstaged)](#i-want-to-discard-my-local-uncommitted-changes-staged-and-unstaged)
- [I want to discard specific unstaged changes](#i-want-to-discard-specific-unstaged-changes)
- [I want to discard specific unstaged files](#i-want-to-discard-specific-unstaged-files)
- [I want to discard only my unstaged local changes](#i-want-to-discard-only-my-unstaged-local-changes)
- [I want to discard all of my untracked files](#i-want-to-discard-all-of-my-untracked-files)
- [Branches](#branches)
- [I want to list all branches](#i-want-to-list-all-branches)
- [Create a branch from a commit](#create-a-branch-from-a-commit)
- [I pulled from/into the wrong branch](#i-pulled-frominto-the-wrong-branch)
- [I want to discard local commits so my branch is the same as one on the server](#i-want-to-discard-local-commits-so-my-branch-is-the-same-as-one-on-the-server)
- [I want to move my unstaged edits to a new branch](#i-want-to-move-my-unstaged-edits-to-a-new-branch)
- [I want to move my unstaged edits to a different, existing branch](#i-want-to-move-my-unstaged-edits-to-a-different-existing-branch)
- [I committed to main instead of a new branch](#i-committed-to-main-instead-of-a-new-branch)
- [I want to keep the whole file from another ref-ish](#i-want-to-keep-the-whole-file-from-another-ref-ish)
- [I made several commits on a single branch that should be on different branches](#i-made-several-commits-on-a-single-branch-that-should-be-on-different-branches)
- [I want to delete local branches that were deleted upstream](#i-want-to-delete-local-branches-that-were-deleted-upstream)
- [I accidentally deleted my branch](#i-accidentally-deleted-my-branch)
- [I want to delete a branch](#i-want-to-delete-a-branch)
- [I want to delete multiple branches](#i-want-to-delete-multiple-branches)
- [I want to rename a branch](#i-want-to-rename-a-branch)
- [I want to checkout to a remote branch that someone else is working on](#i-want-to-checkout-to-a-remote-branch-that-someone-else-is-working-on)
- [I want to create a new remote branch from current local one](#i-want-to-create-a-new-remote-branch-from-current-local-one)
- [I want to set a remote branch as the upstream for a local branch](#i-want-to-set-a-remote-branch-as-the-upstream-for-a-local-branch)
- [I want to set my HEAD to track the default remote branch](#i-want-to-set-my-head-to-track-the-default-remote-branch)
- [I made changes on the wrong branch](#i-made-changes-on-the-wrong-branch)
- [I want to split a branch into two](#i-want-to-split-a-branch-into-two)
- [Rebasing and Merging](#rebasing-and-merging)
- [I want to undo rebase/merge](#i-want-to-undo-rebasemerge)
- [I rebased, but I don't want to force push](#i-rebased-but-i-dont-want-to-force-push)
- [I need to combine commits](#i-need-to-combine-commits)
- [Safe merging strategy](#safe-merging-strategy)
- [I need to merge a branch into a single commit](#i-need-to-merge-a-branch-into-a-single-commit)
- [I want to combine only unpushed commits](#i-want-to-combine-only-unpushed-commits)
- [I need to abort the merge](#i-need-to-abort-the-merge)
- [I need to update the parent commit of my branch](#i-need-to-update-the-parent-commit-of-my-branch)
- [Check if all commits on a branch are merged](#check-if-all-commits-on-a-branch-are-merged)
- [Possible issues with interactive rebases](#possible-issues-with-interactive-rebases)
- [The rebase editing screen says 'noop'](#the-rebase-editing-screen-says-noop)
- [There were conflicts](#there-were-conflicts)
- [Stash](#stash)
- [Stash all edits](#stash-all-edits)
- [Stash specific files](#stash-specific-files)
- [Stash with message](#stash-with-message)
- [Apply a specific stash from list](#apply-a-specific-stash-from-list)
- [Stash while keeping unstaged edits](#stash-while-keeping-unstaged-edits)
- [Finding](#finding)
- [I want to find a string in any commit](#i-want-to-find-a-string-in-any-commit)
- [I want to find by author/committer](#i-want-to-find-by-authorcommitter)
- [I want to list commits containing specific files](#i-want-to-list-commits-containing-specific-files)
- [I want to view the commit history for a specific function](#i-want-to-view-the-commit-history-for-a-specific-function)
- [Find a tag where a commit is referenced](#find-a-tag-where-a-commit-is-referenced)
- [Submodules](#submodules)
- [Clone all submodules](#clone-all-submodules)
- [Remove a submodule](#remove-a-submodule)
- [Miscellaneous Objects](#miscellaneous-objects)
- [Copy a folder or file from one branch to another](#copy-a-folder-or-file-from-one-branch-to-another)
- [Restore a deleted file](#restore-a-deleted-file)
- [Delete tag](#delete-tag)
- [Recover a deleted tag](#recover-a-deleted-tag)
- [Deleted Patch](#deleted-patch)
- [Exporting a repository as a Zip file](#exporting-a-repository-as-a-zip-file)
- [Push a branch and a tag that have the same name](#push-a-branch-and-a-tag-that-have-the-same-name)
- [Tracking Files](#tracking-files)
- [I want to change a file name's capitalization, without changing the contents of the file](#i-want-to-change-a-file-names-capitalization-without-changing-the-contents-of-the-file)
- [I want to overwrite local files when doing a git pull](#i-want-to-overwrite-local-files-when-doing-a-git-pull)
- [I want to remove a file from Git but keep the file](#i-want-to-remove-a-file-from-git-but-keep-the-file)
- [I want to revert a file to a specific revision](#i-want-to-revert-a-file-to-a-specific-revision)
- [I want to list changes of a specific file between commits or branches](#i-want-to-list-changes-of-a-specific-file-between-commits-or-branches)
- [I want Git to ignore changes to a specific file](#i-want-git-to-ignore-changes-to-a-specific-file)
- [Debugging with Git](#debugging-with-git)
- [Configuration](#configuration)
- [I want to add aliases for some Git commands](#i-want-to-add-aliases-for-some-git-commands)
- [I want to add an empty directory to my repository](#i-want-to-add-an-empty-directory-to-my-repository)
- [I want to cache a username and password for a repository](#i-want-to-cache-a-username-and-password-for-a-repository)
- [I want to make Git ignore permissions and filemode changes](#i-want-to-make-git-ignore-permissions-and-filemode-changes)
- [I want to set a global user](#i-want-to-set-a-global-user)
- [I've no idea what I did wrong](#ive-no-idea-what-i-did-wrong)
- [Git Shortcuts](#git-shortcuts)
- [Git Bash](#git-bash)
- [PowerShell on Windows](#powershell-on-windows)
- [Other Resources](#other-resources)
- [Books](#books)
- [Tutorials](#tutorials)
- [Scripts and Tools](#scripts-and-tools)
- [GUI Clients](#gui-clients)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Repositories
### I want to start a local repository
To initialize an existing directory as a Git repository:
```sh
(my-folder) $ git init
```
### I want to clone a remote repository
To clone (copy) a remote repository, copy the URL for the repository, and run:
```sh
$ git clone [url]
```
This will save it to a folder named the same as the remote repository's. Make sure you have a connection to the remote server you are cloning from (for most purposes this means making sure you are connected to the internet).
To clone it into a folder with a different name than the default repository name:
```sh
$ git clone [url] name-of-new-folder
```
### I set the wrong remote repository
There are a few possible problems here:
If you cloned the wrong repository, simply delete the directory created after running `git clone` and clone the correct repository.
If you set the wrong repository as the origin of an existing local repository, change the URL of your origin by running:
```sh
$ git remote set-url origin [url of the actual repo]
```
For more, see [this StackOverflow topic](https://stackoverflow.com/questions/2432764/how-to-change-the-uri-url-for-a-remote-git-repository#2432799).
### I want to add code to someone else's repository
Git doesn't allow you to add code to someone else's repository without access rights. Neither does GitHub, which is not the same as Git, but rather a hosted service for Git repositories. However, you can suggest code using patches, or, on GitHub, forks and pull requests.
First, a bit about forking. A fork is a copy of a repository. It is not a git operation, but is a common action on GitHub, Bitbucket, GitLab — or anywhere people host Git repositories. You can fork a repository through the hosted UI.
#### Suggesting code via pull requests
After you've forked a repository, you normally need to clone the repository to your machine. You can do some small edits on GitHub, for instance, without cloning, but this isn't a github-flight-rules list, so let's go with how to do this locally.
```sh
# if you are using ssh
$ git clone git@github.com:k88hudson/git-flight-rules.git
# if you are using https
$ git clone https://github.com/k88hudson/git-flight-rules.git
```
If you `cd` into the resulting directory, and type `git remote`, you'll see a list of the remotes. Normally there will be one remote - `origin` - which will point to `k88hudson/git-flight-rules`. In this case, we also want a remote that will point to your fork.
First, to follow a Git convention, we normally use the remote name `origin` for your own repository and `upstream` for whatever you've forked. So, rename the `origin` remote to `upstream`
```sh
$ git remote rename origin upstream
```
You can also do this using `git remote set-url`, but it takes longer and is more steps.
Then, set up a new remote that points to your project.
```sh
$ git remote add origin git@github.com:YourName/git-flight-rules.git
```
Note that now you have two remotes.
- `origin` references your own repository.
- `upstream` references the original one.
From origin, you can read and write. From upstream, you can only read.
When you've finished making whatever changes you like, push your changes (normally in a branch) to the remote named `origin`. If you're on a branch, you could use `--set-upstream` to avoid specifying the remote tracking branch on every future push using this branch. For instance:
```sh
$ (feature/my-feature) git push --set-upstream origin feature/my-feature
```
There is no way to suggest a pull request using the CLI using Git (although there are tools, like [hub](http://github.com/github/hub), which will do this for you). So, if you're ready to make a pull request, go to your GitHub (or another Git host) and create a new pull request. Note that your host automatically links the original and forked repositories.
After all of this, do not forget to respond to any code review feedback.
#### Suggesting code via patches
Another approach to suggesting code changes that doesn't rely on third party sites such as Github is to use `git format-patch`.
`format-patch` creates a .patch file for one or more commits. This file is essentially a list of changes that looks similar to the commit diffs you can view on Github.
A patch can be viewed and even edited by the recipient and applied using `git am`.
For example, to create a patch based on the previous commit you would run `git format-patch HEAD^` which would create a .patch file called something like 0001-My-Commit-Message.patch.
To apply this patch file to your repository you would run `git am ./0001-My-Commit-Message.patch`.
Patches can also be sent via email using the `git send-email` command. For information on usage and configuration see: https://git-send-email.io
#### I need to update my fork with latest updates from the original repository
After a while, the `upstream` repository may have been updated, and these updates need to be pulled into your `origin` repo. Remember that like you, other people are contributing too. Suppose that you are in your own feature branch and you need to update it with the original repository updates.
You probably have set up a remote that points to the original project. If not, do this now. Generally we use `upstream` as a remote name:
```sh
$ (main) git remote add upstream <link-to-original-repository>
# $ (main) git remote add upstream git@github.com:k88hudson/git-flight-rules.git
```
Now you can fetch from upstream and get the latest updates.
```sh
$ (main) git fetch upstream
$ (main) git merge upstream/main
# or using a single command
$ (main) git pull upstream main
```
## Editing Commits
<a name="diff-last"></a>
### What did I just commit?
Let's say that you just blindly committed changes with `git commit -a` and you're not sure what the actual content of the commit you just made was. You can show the latest commit on your current HEAD with:
```sh
(main)$ git show
```
Or
```sh
$ git log -n1 -p
```
If you want to see a file at a specific commit, you can also do this (where `<commitid>` is the commit you're interested in):
```sh
$ git show <commitid>:filename
```
<a name="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:
```sh
$ git commit --amend --only
```
This will open your default text editor, where you can edit the message. On the other hand, you can do this all in one command:
```sh
$ git commit --amend --only -m 'xxxxxxx'
```
If you have already pushed the message, you can amend the commit and force push, but this is not recommended.
<a name="commit-wrong-author"></a>
### I committed with the wrong name and email configured
If it's a single commit, amend it
```sh
$ git commit --amend --no-edit --author "New Authorname <authoremail@mydomain.com>"
```
An alternative is to correctly configure your author settings in `git config --global author.(name|email)` and then use
```sh
$ git commit --amend --reset-author --no-edit
```
If you need to change for multiple commits, you can use
```sh
$ git -c rebase.instructionFormat='%s%nexec GIT_COMMITTER_DATE="%cD" GIT_AUTHOR_DATE="%aD" git commit --amend --no-edit --reset-author' rebase -r <commit>
```
`<commit>` is a commit before all your bad commits. If you need to change all of history in the current branch including the root of the branch, put `--root` there instead.
If you need to change all of history, see the man page for `git filter-branch`.
Note this will change the history and a force push is required.
### I want to remove a file from the previous commit
In order to remove changes for a file from the previous commit, do the following:
```sh
$ git checkout HEAD^ myfile
$ git add myfile
$ git commit --amend --no-edit
```
In case the file was newly added to the commit and you want to remove it (from Git alone), do:
```sh
$ git rm --cached myfile
$ git commit --amend --no-edit
```
This is particularly useful when you have an open patch and you have committed an unnecessary file, and need to force push to update the patch on a remote. The `--no-edit` option is used to keep the existing commit message.
<a name="move-change-to-new-commit"></a>
### I want to move a change from one commit to another
If you've made a commit that includes changes that would fit better in another commit, you can move the changes to the other commit using an interactive rebase. This comes from [stackoverflow](https://stackoverflow.com/a/54985304/2491502).
For example, you have three commits (a, b, c). On b, you've changes file1 and file2 and you want to move the change on file1 from commit b to commit a.
First, rebase interactively:
```sh
$ git rebase -i HEAD~3
```
This will open an editor with the following:
```sh
pick a
pick b
pick c
```
Change the lines with a and b to edit:
```sh
edit a
edit b
pick c
```
Save and close the editor. This will bring you to commit b. Now, reset the file1 changes:
```sh
$ git reset HEAD~1 file1
```
This will unstage the changes in file1. Now, stash those changes and continue the rebase:
```sh
$ git stash
$ git rebase --continue
```
Now you will be editing commit a. Unstash the changes then add them to the current commit and continue the rebase:
```sh
$ git stash pop
$ git add file1
$ git commit --amend --no-edit
$ git rebase --continue
```
Now your rebase is complete, with the changes from b on a. If you wanted to move the changes from b to c, you would have to do two rebases since c comes before b: one to get the changes out of b, then another to edit c and add the stashed changes.
<a name="delete-pushed-commit"></a>
### I want to delete or remove my last commit
If you need to delete pushed commits, you can use the following. However, it will irreversibly change your history, and mess up the history of anyone else who had already pulled from the repository. In short, if you're not sure, you should never do this, ever.
```sh
$ git reset HEAD^ --hard
$ git push --force-with-lease [remote] [branch]
```
If you haven't pushed, to reset Git to the state it was in before you made your last commit (while keeping your staged changes):
```
(my-branch)$ git reset --soft HEAD^
```
This only works if you haven't pushed. If you have pushed, the only truly safe thing to do is `git revert SHAofBadCommit`. That will create a new commit that undoes all the previous commit's changes. Or, if the branch you pushed to is rebase-safe (ie. other devs aren't expected to pull from it), you can just use `git push --force-with-lease`. For more, see [the above section](#deleteremove-last-pushed-commit).
<a name="delete-any-commit"></a>
### Delete/remove arbitrary commit
The same warning applies as above. Never do this if possible.
```sh
$ git rebase --onto SHA1_OF_BAD_COMMIT^ SHA1_OF_BAD_COMMIT
$ git push --force-with-lease [remote] [branch]
```
Or do an [interactive rebase](#interactive-rebase) and remove the line(s) corresponding to commit(s) you want to see removed.
<a name="force-push"></a>
### I tried to push my amended commit to a remote, but I got an error message
```sh
To https://github.com/yourusername/repo.git
! [rejected] mybranch -> mybranch (non-fast-forward)
error: failed to push some refs to 'https://github.com/tanay1337/webmaker.org.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
```
Note that, as with rebasing (see below), amending **replaces the old commit with a new one**, so you must force push (`--force-with-lease`) your changes if you have already pushed the pre-amended commit to your remote. Be careful when you do this – *always* make sure you specify a branch!
```sh
(my-branch)$ git push origin mybranch --force-with-lease
```
In general, **avoid force pushing**. It is best to create and push a new commit rather than force-pushing the amended commit as it will cause conflicts in the source history for any other developer who has interacted with the branch in question or any child branches. `--force-with-lease` will still fail, if someone else was also working on the same branch as you, and your push would overwrite those changes.
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.
<a name="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.
Note: This is only valid if your work is backed up, i.e., either committed or stashed. `git reset --hard` _will remove_ uncommitted modifications, so use it with caution. (A safer option is `git reset --keep`.)
```sh
(main)$ git reflog
```
You'll see a list of your past commits, and a commit for the reset. Choose the SHA of the commit you want to return to, and reset again:
```sh
(main)$ git reset --hard SHA1234
```
And you should be good to go.
<a name="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).
The command to use
```sh
(feature-branch)$ git revert -m 1 <commit>
```
where the -m 1 option says to select parent number 1 (the branch into which the merge was made) as the parent to revert to.
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.
<a name="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.
If you edit the file and remove the sensitive data, then run
```sh
(feature-branch)$ git add edited_file
(feature-branch)$ git commit --amend --no-edit
(feature-branch)$ git push --force-with-lease origin [branch]
```
If you want to remove an entire file (but keep it locally), then run
```sh
(feature-branch)$ git rm --cached sensitive_file
echo sensitive_file >> .gitignore
(feature-branch)$ git add .gitignore
(feature-branch)$ git commit --amend --no-edit
(feature-branch)$ git push --force-with-lease origin [branch]
```
Alternatively store your sensitive data in local environment variables.
If you want to completely remove an entire file (and not keep it locally), then run
```sh
(feature-branch)$ git rm sensitive_file
(feature-branch)$ git commit --amend --no-edit
(feature-branch)$ git push --force-with-lease origin [branch]
```
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.
<a name="remove-large-file-in-repo-history"></a>
### 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](#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.
The actions in this part of the guide will require a force push, and rewrite large sections of repo history, so if you are working with remote collaborators, check first that any local work of theirs is pushed.
There are two options for rewriting history, the built-in `git-filter-branch` or [`bfg-repo-cleaner`](https://rtyley.github.io/bfg-repo-cleaner/). `bfg` is significantly cleaner and more performant, but it is a third-party download and requires java. We will describe both alternatives. The final step is to force push your changes, which requires special consideration on top of a regular force push, given that a great deal of repo history will have been permanently changed.
#### Recommended Technique: Use third-party bfg
Using bfg-repo-cleaner requires java. Download the bfg jar from the link [here](https://rtyley.github.io/bfg-repo-cleaner/). Our examples will use `bfg.jar`, but your download may have a version number, e.g. `bfg-1.13.0.jar`.
To delete a specific file.
```sh
(main)$ git rm path/to/filetoremove
(main)$ git commit -m "Commit removing filetoremove"
(main)$ java -jar ~/Downloads/bfg.jar --delete-files filetoremove
```
Note that in bfg you must use the plain file name even if it is in a subdirectory.
You can also delete a file by pattern, e.g.:
```sh
(main)$ git rm *.jpg
(main)$ git commit -m "Commit removing *.jpg"
(main)$ java -jar ~/Downloads/bfg.jar --delete-files *.jpg
```
With bfg, the files that exist on your latest commit will not be affected. For example, if you had several large .tga files in your repo, and then in an earlier commit, you deleted a subset of them, this call does not touch files present in the latest commit
Note, if you renamed a file as part of a commit, e.g. if it started as `LargeFileFirstName.mp4` and a commit changed it to `LargeFileSecondName.mp4`, running `java -jar ~/Downloads/bfg.jar --delete-files LargeFileSecondName.mp4` will not remove it from git history. Either run the `--delete-files` command with both filenames, or with a matching pattern.
#### Built-in Technique: Use git-filter-branch
`git-filter-branch` is more cumbersome and has less features, but you may use it if you cannot install or run `bfg`.
In the below, replace `filepattern` may be a specific name or pattern, e.g. `*.jpg`. This will remove files matching the pattern from all history and branches.
```sh
(main)$ git filter-branch --force --index-filter 'git rm --cached --ignore-unmatch filepattern' --prune-empty --tag-name-filter cat -- --all
```
Behind-the-scenes explanation:
`--tag-name-filter cat` is a cumbersome, but simplest, way to apply the original tags to the new commits, using the command cat.
`--prune-empty` removes any now-empty commits.
#### Final Step: Pushing your changed repo history
Once you have removed your desired files, test carefully that you haven't broken anything in your repo - if you have, it is easiest to re-clone your repo to start over.
To finish, optionally use git garbage collection to minimize your local .git folder size, and then force push.
```sh
(main)$ git reflog expire --expire=now --all && git gc --prune=now --aggressive
(main)$ git push origin --force --tags
```
Since you just rewrote the entire git repo history, the `git push` operation may be too large, and return the error `“The remote end hung up unexpectedly”`. If this happens, you can try increasing the git post buffer:
```sh
(main)$ git config http.postBuffer 524288000
(main)$ git push --force
```
If this does not work, you will need to manually push the repo history in chunks of commits. In the command below, try increasing `<number>` until the push operation succeeds.
```sh
(main)$ git push -u origin HEAD~<number>:refs/head/main --force
```
Once the push operation succeeds the first time, decrease `<number>` gradually until a conventional `git push` succeeds.
<a name="change-content-of-commit-not-my-last"></a>
### 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.
Consider a situation where you want to change the third last commit you made.
```sh
(your-branch)$ git rebase -i HEAD~4
```
gets you into interactive rebase mode, which allows you to edit any of your last three commits. A text editor pops up, showing you something like
```sh
pick 9e1d264 The third last commit
pick 4b6e19a The second to last commit
pick f4037ec The last commit
```
which you change into
```sh
edit 9e1d264 The third last commit
pick 4b6e19a The second to last commit
pick f4037ec The last commit
```
This tells rebase that you want to edit your third last commit and keep the other two unaltered. Then you'll save (and close) the editor. Git will then start to rebase. It stops on the commit you want to alter, giving you the chance to edit that commit. Now you can apply the changes which you missed applying when you initially committed that commit. You do so by editing and staging them. Afterwards you'll run
```sh
(your-branch)$ git commit --amend
```
which tells Git to recreate the commit. Also, Git will ask you to write a new commit message, using the original commit message as a starting point. Having done that, the hard part is solved.
```sh
(your-branch)$ git rebase --continue
```
will do the rest of the work for you.
## Staging
<a name="stage-tracked-files-and-leave-untracked-files"></a>
### I want to stage all tracked files and leave untracked files
```sh
$ git add -u
```
#### To stage part of tracked files
```sh
# to stage files with ext .txt
$ git add -u *.txt
# to stage all files inside directory src
$ git add -u src/
```
<a name="add-staged-changes-to-previous-commit"></a>
### I need to add staged changes to the previous commit
```sh
(my-branch*)$ git commit --amend
```
If you already know you don't want to change the commit message, you can tell git to reuse the commit message:
```sh
(my-branch*)$ git commit --amend -C HEAD
```
<a name="commit-partial-new-file"></a>
### I want to stage part of a new file, but not the whole file
Normally, if you want to stage part of a file, you run this:
```sh
$ git add --patch filename.x
```
`-p` will work for short. This will open interactive mode. You would be able to use the `s` option to split the commit - however, if the file is new, you will not have this option. To add a new file, do this:
```sh
$ 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.
<a name="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.
<a name="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.
<a name="unstaging-edits-and-staging-the-unstaged"></a>
### 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.
```sh
$ git commit -m "WIP"
$ git add . # This will also add untracked files.
$ git stash
$ git reset HEAD^
$ git stash pop --index 0
```
NOTE 1: The reason to use `pop` here is want to keep idempotent as much as possible.
NOTE 2: Your staged files will be marked as unstaged if you don't use the `--index` flag. ([This link](https://stackoverflow.com/questions/31595873/git-stash-with-staged-files-does-stash-convert-staged-files-to-unstaged?answertab=active#tab-top) explains why.)
<a name="unstage-specific-staged-file"></a>
### I want to unstage a specific staged file
Sometimes we have one or more files that accidentally ended up being staged, and these files have not been committed before. To unstage them:
```sh
$ git reset -- <filename>
```
This results in unstaging the file and make it look like it's untracked.
## Discarding changes
<a name="discard-local-uncommitted-changes"></a>
### I want to discard my local uncommitted changes (staged and unstaged)
If you want to discard all your local staged and unstaged changes, you can do this:
```sh
(my-branch)$ git reset --hard
# or
(main)$ git checkout -f
```
This will unstage all files you might have staged with `git add`:
```sh
$ git reset
```
This will revert all local uncommitted changes (should be executed in repo root):
```sh
$ git checkout .
```
You can also revert uncommitted changes to a particular file or directory:
```sh
$ git checkout [some_dir|file.txt]
```
Yet another way to revert all uncommitted changes (longer to type, but works from any subdirectory):
```sh
$ git reset --hard HEAD
```
This will remove all local untracked files, so only files tracked by Git remain:
```sh
$ git clean -fd
```
`-x` will also remove all ignored files.
### I want to discard specific unstaged changes
When you want to get rid of some, but not all changes in your working copy.
Checkout undesired changes, keep good changes.
```sh
$ git checkout -p
# Answer y to all of the snippets you want to drop
```
Another strategy involves using `stash`. Stash all the good changes, reset working copy, and reapply good changes.
```sh
$ git stash -p
# Select all of the snippets you want to save
$ git reset --hard
$ git stash pop
```
Alternatively, stash your undesired changes, and then drop stash.
```sh
$ git stash -p
# Select all of the snippets you don't want to save
$ git stash drop
```
### I want to discard specific unstaged files
When you want to get rid of one specific file in your working copy.
```sh
$ git checkout myFile
```
Alternatively, to discard multiple files in your working copy, list them all.
```sh
$ git checkout myFirstFile mySecondFile
```
### I want to discard only my unstaged local changes
When you want to get rid of all of your unstaged local uncommitted changes
```sh
$ git checkout .
```
<a name="discard-all-untracked-files"></a>
### I want to discard all of my untracked files
When you want to get rid of all of your untracked files
```sh
$ git clean -f
```
## Branches
### I want to list all branches
List local branches
```sh
$ git branch
```
List remote branches
```sh
$ git branch -r
```
List all branches (both local and remote)
```sh
$ git branch -a
```
<a name="create-branch-from-commit"></a>
### Create a branch from a commit
```sh
$ git checkout -b <branch> <SHA1_OF_COMMIT>
```
<a name="pull-wrong-branch"></a>
### I pulled from/into the wrong branch
This is another chance to use `git reflog` to see where your HEAD pointed before the bad pull.
```sh
(main)$ git reflog
ab7555f HEAD@{0}: pull origin wrong-branch: Fast-forward
c5bc55a HEAD@{1}: checkout: checkout message goes here
```
Simply reset your branch back to the desired commit:
```sh
$ git reset --hard c5bc55a
```
Done.
<a name="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.
`git status` should show how many commits you are ahead of origin:
```sh
(my-branch)$ git status
# On branch my-branch
# Your branch is ahead of 'origin/my-branch' by 2 commits.
# (use "git push" to publish your local commits)
#
```
One way of resetting branch `my-branch` to match `origin/my-branch` (to have the same as what is on the remote) is to do this:
```sh
(my-branch)$ git reset --hard origin/my-branch
```
<a name="move-unstaged-edits-to-new-branch"></a>
### I want to move my unstaged edits to a new branch
```sh
$ git checkout -b my-branch
```
<a name="move-unstaged-edits-to-old-branch"></a>
### I want to move my unstaged edits to a different, existing branch
```sh
$ git stash
$ git checkout my-branch
$ git stash pop
```
<a name="commit-wrong-branch"></a>
### I committed to main instead of a new branch
Create the new branch while remaining on main:
```sh
(main)$ git branch my-branch
```
Reset the branch main to the previous commit:
```sh
(main)$ git reset --hard HEAD^
```
`HEAD^` is short for `HEAD^1`. This stands for the first parent of `HEAD`, similarly `HEAD^2` stands for the second parent of the commit (merges can have 2 parents).
Note that `HEAD^2` is **not** the same as `HEAD~2` (see [this link](http://www.paulboxley.com/blog/2011/06/git-caret-and-tilde) for more information).
Alternatively, if you don't want to use `HEAD^`, find out what the commit hash you want to set your main branch to (`git log` should do the trick). Then reset to that hash. `git push` will make sure that this change is reflected on your remote.
For example, if the hash of the commit that your main branch is supposed to be at is `a13b85e`:
```sh
(main)$ git reset --hard a13b85e
HEAD is now at a13b85e
```
Checkout the new branch to continue working:
```sh
(main)$ git checkout my-branch
```
<a name="keep-whole-file"></a>
### I want to keep the whole file from another ref-ish
Say you have a working spike (see note), with hundreds of changes. Everything is working. Now, you commit into another branch to save that work:
```sh
(solution)$ git add -A && git commit -m "Adding all changes from this spike into one big commit."
```
When you want to put it into a branch (maybe feature, maybe `develop`), you're interested in keeping whole files. You want to split your big commit into smaller ones.
Say you have:
* branch `solution`, with the solution to your spike. One ahead of `develop`.
* branch `develop`, where you want to add your changes.
You can solve it bringing the contents to your branch:
```sh
(develop)$ git checkout solution -- file1.txt
```
This will get the contents of that file in branch `solution` to your branch `develop`:
```sh
# On branch develop
# Your branch is up-to-date with 'origin/develop'.
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# modified: file1.txt
```
Then, commit as usual.
Note: Spike solutions are made to analyze or solve the problem. These solutions are used for estimation and discarded once everyone gets clear visualization of the problem. ~ [Wikipedia](https://en.wikipedia.org/wiki/Extreme_programming_practices).
<a name="cherry-pick"></a>
### I made several commits on a single branch that should be on different branches
Say you are on your main branch. Running `git log`, you see you have made two commits:
```sh
(main)$ git log
commit e3851e817c451cc36f2e6f3049db528415e3c114
Author: Alex Lee <alexlee@example.com>
Date: Tue Jul 22 15:39:27 2014 -0400
Bug #21 - Added CSRF protection
commit 5ea51731d150f7ddc4a365437931cd8be3bf3131
Author: Alex Lee <alexlee@example.com>
Date: Tue Jul 22 15:39:12 2014 -0400
Bug #14 - Fixed spacing on title
commit a13b85e984171c6e2a1729bb061994525f626d14
Author: Aki Rose <akirose@example.com>
Date: Tue Jul 21 01:12:48 2014 -0400
First commit
```
Let's take note of our commit hashes for each bug (`e3851e8` for #21, `5ea5173` for #14).
First, let's reset our main branch to the correct commit (`a13b85e`):
```sh
(main)$ git reset --hard a13b85e
HEAD is now at a13b85e
```
Now, we can create a fresh branch for our bug #21:
```sh
(main)$ git checkout -b 21
(21)$
```
Now, let's *cherry-pick* the commit for bug #21 on top of our branch. That means we will be applying that commit, and only that commit, directly on top of whatever our head is at.
```sh
(21)$ git cherry-pick e3851e8
```
At this point, there is a possibility there might be conflicts. See the [**There were conflicts**](#merge-conflict) section in the [interactive rebasing section above](#interactive-rebase) for how to resolve conflicts.
Now let's create a new branch for bug #14, also based on main
```sh
(21)$ git checkout main
(main)$ git checkout -b 14
(14)$
```
And finally, let's cherry-pick the commit for bug #14:
```sh
(14)$ git cherry-pick 5ea5173
```
<a name="delete-stale-local-branches"></a>
### I want to delete local branches that were deleted upstream
Once you merge a pull request on GitHub, it gives you the option to delete the merged branch in your fork. If you aren't planning to keep working on the branch, it's cleaner to delete the local copies of the branch so you don't end up cluttering up your working checkout with a lot of stale branches.
```sh
$ git fetch -p upstream
```
where, `upstream` is the remote you want to fetch from.
<a name="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:
```sh
(main)$ git checkout -b my-branch
(my-branch)$ git branch
(my-branch)$ touch foo.txt
(my-branch)$ ls
README.md foo.txt
```
Let's add it and commit.
```sh
(my-branch)$ git add .
(my-branch)$ git commit -m 'foo.txt added'
(my-branch)$ foo.txt added
1 files changed, 1 insertions(+)
create mode 100644 foo.txt
(my-branch)$ git log
commit 4e3cd85a670ced7cc17a2b5d8d3d809ac88d5012
Author: siemiatj <siemiatj@example.com>
Date: Wed Jul 30 00:34:10 2014 +0200
foo.txt added
commit 69204cdf0acbab201619d95ad8295928e7f411d5
Author: Kate Hudson <katehudson@example.com>
Date: Tue Jul 29 13:14:46 2014 -0400
Fixes #6: Force pushing after amending commits
```
Now we're switching back to main and 'accidentally' removing our branch.
```sh
(my-branch)$ git checkout main
Switched to branch 'main'
Your branch is up-to-date with 'origin/main'.
(main)$ git branch -D my-branch
Deleted branch my-branch (was 4e3cd85).
(main)$ echo oh noes, deleted my branch!
oh noes, deleted my branch!
```
At this point you should get familiar with 'reflog', an upgraded logger. It stores the history of all the action in the repo.
```
(main)$ git reflog
69204cd HEAD@{0}: checkout: moving from my-branch to main
4e3cd85 HEAD@{1}: commit: foo.txt added
69204cd HEAD@{2}: checkout: moving from main to my-branch
```
As you can see we have commit hash from our deleted branch. Let's see if we can restore our deleted branch.
```sh
(main)$ git checkout -b my-branch-help
Switched to a new branch 'my-branch-help'
(my-branch-help)$ git reset --hard 4e3cd85
HEAD is now at 4e3cd85 foo.txt added
(my-branch-help)$ ls
README.md foo.txt
```
Voila! We got our removed file back. `git reflog` is also useful when rebasing goes terribly wrong.
### I want to delete a branch
To delete a remote branch:
```sh
(main)$ git push origin --delete my-branch
```
You can also do:
```sh
(main)$ git push origin :my-branch
```
To delete a local branch:
```sh
(main)$ git branch -d my-branch
```
To delete a local branch that *has not* been merged to the current branch or an upstream:
```sh
(main)$ git branch -D my-branch
```
### I want to delete multiple branches
Say you want to delete all branches that start with `fix/`:
```sh
(main)$ git branch | grep 'fix/' | xargs git branch -d
```
### I want to rename a branch
To rename the current (local) branch:
```sh
(main)$ git branch -m new-name
```
To rename a different (local) branch:
```sh
(main)$ git branch -m old-name new-name
```
To delete the `old-name` remote branch and push the `new-name` local branch:
```sh
(main)$ git push origin :old_name new_name
```
<a name="working-on-checkout-remote-branch"></a>
### I want to checkout to a remote branch that someone else is working on
First, fetch all branches from remote:
```sh
(main)$ git fetch --all
```
Say you want to checkout to `daves` from the remote.
```sh
(main)$ git checkout --track origin/daves
Branch daves set up to track remote branch daves from origin.
Switched to a new branch 'daves'
```
(`--track` is shorthand for `git checkout -b [branch] [remotename]/[branch]`)
This will give you a local copy of the branch `daves`, and any update that has been pushed will also show up remotely.
### I want to create a new remote branch from current local one
```sh
$ git push <remote> HEAD
```
If you would also like to set that remote branch as upstream for the current one, use the following instead:
```sh
$ git push -u <remote> HEAD
```
With the `upstream` mode and the `simple` (default in Git 2.0) mode of the `push.default` config, the following command will push the current branch with regards to the remote branch that has been registered previously with `-u`:
```sh
$ 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#Documentation/git-config.txt-pushdefault).
### I want to set a remote branch as the upstream for a local branch
You can set a remote branch as the upstream for the current local branch using:
```sh
$ git branch --set-upstream-to [remotename]/[branch]
# or, using the shorthand:
$ git branch -u [remotename]/[branch]
```
To set the upstream remote branch for another local branch:
```sh
$ git branch -u [remotename]/[branch] [local-branch]
```
<a name="head-to-track-remote-branch"></a>
### 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.
```sh
$ git branch -r
origin/HEAD -> origin/gh-pages
origin/main
```
To change `origin/HEAD` to track `origin/main`, you can run this command:
```sh
$ git remote set-head origin --auto
origin/HEAD set to main
```
### I made changes on the wrong branch
You've made uncommitted changes and realise you're on the wrong branch. Stash changes and apply them to the branch you want:
```sh
(wrong_branch)$ git stash
(wrong_branch)$ git checkout <correct_branch>
(correct_branch)$ git stash apply
```
<a name="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.
Use `git log` to find the commit where you want to split. Then do the following:
```sh
(original_branch)$ git checkout -b new_branch
(new_branch)$ git checkout original_branch
(original_branch)$ git reset --hard <sha1 split here>
```
If you had previously pushed the `original_branch` to remote, you will need to do a force push. For more information check [Stack Overflow](https://stackoverflow.com/questions/28983458/how-to-split-a-branch-in-two-with-git/28983843#28983843)
## Rebasing and Merging
<a name="undo-rebase"></a>
### I want to undo rebase/merge
You may have merged or rebased your current branch with a wrong branch, or you can't figure it out or finish the rebase/merge process. Git saves the original HEAD pointer in a variable called ORIG_HEAD before doing dangerous operations, so it is simple to recover your branch at the state before the rebase/merge.
```sh
(my-branch)$ git reset --hard ORIG_HEAD
```
<a name="force-push-rebase"></a>
### I rebased, but I don't want to force push
Unfortunately, you have to force push, if you want those changes to be reflected on the remote branch. This is because you have changed the history. The remote branch won't accept changes unless you force push. This is one of the main reasons many people use a merge workflow, instead of a rebasing workflow - large teams can get into trouble with developers force pushing. Use this with caution. A safer way to use rebase is not to reflect your changes on the remote branch at all, and instead to do the following:
```sh
(main)$ git checkout my-branch
(my-branch)$ git rebase -i main
(my-branch)$ git checkout main
(main)$ git merge --ff-only my-branch
```
For more, see [this SO thread](https://stackoverflow.com/questions/11058312/how-can-i-use-git-rebase-without-requiring-a-forced-push).
<a name="interactive-rebase"></a>
### I need to combine commits
Let's suppose you are working in a branch that is/will become a pull-request against `main`. In the simplest case when all you want to do is to combine *all* commits into a single one and you don't care about commit timestamps, you can reset and recommit. Make sure the main branch is up to date and all your changes committed, then:
```sh
(my-branch)$ git reset --soft main
(my-branch)$ git commit -am "New awesome feature"
```
If you want more control, and also to preserve timestamps, you need to do something called an interactive rebase:
```sh
(my-branch)$ git rebase -i main
```
If you aren't working against another branch you'll have to rebase relative to your `HEAD`. If you want to squash the last 2 commits, for example, you'll have to rebase against `HEAD~2`. For the last 3, `HEAD~3`, etc.
```sh
(main)$ git rebase -i HEAD~2
```
After you run the interactive rebase command, you will see something like this in your text editor:
```vim
pick a9c8a1d Some refactoring
pick 01b2fd8 New awesome feature
pick b729ad5 fixup
pick e3851e8 another fix
# Rebase 8074d12..b729ad5 onto 8074d12
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out
```
All the lines beginning with a `#` are comments, they won't affect your rebase.
Then you replace `pick` commands with any in the list above, and you can also remove commits by removing corresponding lines.
For example, if you want to **leave the oldest (first) commit alone and combine all the following commits with the second oldest**, you should edit the letter next to each commit except the first and the second to say `f`:
```vim
pick a9c8a1d Some refactoring
pick 01b2fd8 New awesome feature
f b729ad5 fixup
f e3851e8 another fix
```
If you want to combine these commits **and rename the commit**, you should additionally add an `r` next to the second commit or simply use `s` instead of `f`:
```vim
pick a9c8a1d Some refactoring
pick 01b2fd8 New awesome feature
s b729ad5 fixup
s e3851e8 another fix
```
You can then rename the commit in the next text prompt that pops up.
```vim
Newer, awesomer features
# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
# rebase in progress; onto 8074d12
# You are currently editing a commit while rebasing branch 'main' on '8074d12'.
#
# Changes to be committed:
# modified: README.md
#
```
If everything is successful, you should see something like this:
```sh
(main)$ Successfully rebased and updated refs/heads/main.
```
#### Safe merging strategy
`--no-commit` performs the merge but pretends the merge failed and does not autocommit, giving the user a chance to inspect and further tweak the merge result before committing. `no-ff` maintains evidence that a feature branch once existed, keeping project history consistent.
```sh
(main)$ git merge --no-ff --no-commit my-branch
```
#### I need to merge a branch into a single commit
```sh
(main)$ git merge --squash my-branch
```
<a name="rebase-unpushed-commits"></a>
#### I want to combine only unpushed commits
Sometimes you have several work in progress commits that you want to combine before you push them upstream. You don't want to accidentally combine any commits that have already been pushed upstream because someone else may have already made commits that reference them.
```sh
(main)$ git rebase -i @{u}
```
This will do an interactive rebase that lists only the commits that you haven't already pushed, so it will be safe to reorder/fix/squash anything in the list.
#### I need to abort the merge
Sometimes the merge can produce problems in certain files, in those cases we can use the option `abort` to abort the current conflict resolution process, and try to reconstruct the pre-merge state.
```sh
(my-branch)$ git merge --abort
```
This command is available since Git version >= 1.7.4
### I need to update the parent commit of my branch
Say I have a main branch, a feature-1 branch branched from main, and a feature-2 branch branched off of feature-1. If I make a commit to feature-1, then the parent commit of feature-2 is no longer accurate (it should be the head of feature-1, since we branched off of it). We can fix this with `git rebase --onto`.
```sh
(feature-2)$ git rebase --onto feature-1 <the first commit in your feature-2 branch that you don't want to bring along> feature-2
```
This helps in sticky scenarios where you might have a feature built on another feature that hasn't been merged yet, and a bugfix on the feature-1 branch needs to be reflected in your feature-2 branch.
### Check if all commits on a branch are merged
To check if all commits on a branch are merged into another branch, you should diff between the heads (or any commits) of those branches:
```sh
(main)$ git log --graph --left-right --cherry-pick --oneline HEAD...feature/120-on-scroll
```
This will tell you if any commits are in one but not the other, and will give you a list of any nonshared between the branches. Another option is to do this:
```sh
(main)$ git log main ^feature/120-on-scroll --no-merges
```
### Possible issues with interactive rebases
<a name="noop"></a>
#### The rebase editing screen says 'noop'
If you're seeing this:
```
noop
```
That means you are trying to rebase against a branch that is at an identical commit, or is *ahead* of your current branch. You can try:
* making sure your main branch is where it should be
* rebase against `HEAD~2` or earlier instead
<a name="merge-conflict"></a>
#### There were conflicts
If you are unable to successfully complete the rebase, you may have to resolve conflicts.
First run `git status` to see which files have conflicts in them:
```sh
(my-branch)$ git status
On branch my-branch
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
both modified: README.md
```
In this example, `README.md` has conflicts. Open that file and look for the following:
```vim
<<<<<<< HEAD
some code
=========
some code
>>>>>>> new-commit
```
You will need to resolve the differences between the code that was added in your new commit (in the example, everything from the middle line to `new-commit`) and your `HEAD`.
If you want to keep one branch's version of the code, you can use `--ours` or `--theirs`:
```sh
(main*)$ git checkout --ours README.md
```
- 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#Documentation/git-rebase.txt---merge).
If the merges are more complicated, you can use a visual diff editor:
```sh
(main*)$ git mergetool -t opendiff
```
After you have resolved all conflicts and tested your code, `git add` the files you have changed, and then continue the rebase with `git rebase --continue`
```sh
(my-branch)$ git add README.md
(my-branch)$ git rebase --continue
```
If after resolving all the conflicts you end up with an identical tree to what it was before the commit, you need to `git rebase --skip` instead.
If at any time you want to stop the entire rebase and go back to the original state of your branch, you can do so:
```sh
(my-branch)$ git rebase --abort
```
<a name="stashing"></a>
## Stash
### Stash all edits
To stash all the edits in your working directory
```sh
$ git stash
```
If you also want to stash untracked files, use `-u` option.
```sh
$ git stash -u
```
### Stash specific files
To stash only one file from your working directory
```sh
$ git stash push working-directory-path/filename.ext
```
To stash multiple files from your working directory
```sh
$ git stash push working-directory-path/filename1.ext working-directory-path/filename2.ext
```
<a name="stash-msg"></a>
### Stash with message
```sh
$ git stash save <message>
```
or
```sh
$ git stash push -m <message>
```
<a name="stash-apply-specific"></a>
### Apply a specific stash from list
First check your list of stashes with message using
```sh
$ git stash list
```
Then apply a specific stash from the list using
```sh
$ git stash apply "stash@{n}"
```
Here, 'n' indicates the position of the stash in the stack. The topmost stash will be position 0.
Furthermore, using a time-based stash reference is also possible.
```sh
$ git stash apply "stash@{2.hours.ago}"
```
<a name="stage-and-keep-unstaged"></a>
### Stash while keeping unstaged edits
You can manually create a `stash commit`, and then use `git stash store`.
```sh
$ git stash create
$ git stash store -m <message> CREATED_SHA1
```
## Finding
### I want to find a string in any commit
To find a certain string which was introduced in any commit, you can use the following structure:
```sh
$ git log -S "string to find"
```
Commons parameters:
* `--source` means to show the ref name given on the command line by which each commit was reached.
* `--all` means to start from every branch.
* `--reverse` prints in reverse order, it means that will show the first commit that made the change.
<a name="find-by-committer"></a>
### I want to find by author/committer
To find all commits by author/committer you can use:
```sh
$ git log --author=<name or email>
$ git log --committer=<name or email>
```
Keep in mind that author and committer are not the same. The `--author` is the person who originally wrote the code; on the other hand, the `--committer`, is the person who committed the code on behalf of the original author.
### I want to list commits containing specific files
To find all commits containing a specific file you can use:
```sh
$ git log -- <path to file>
```
You would usually specify an exact path, but you may also use wild cards in the path and file name:
```sh
$ git log -- **/*.js
```
While using wildcards, it's useful to inform `--name-status` to see the list of committed files:
```sh
$ git log --name-status -- **/*.js
```
<a name="view-commit-history-for-specific-function"></a>
### I want to view the commit history for a specific function
To trace the evolution of a single function you can use:
```sh
$ git log -L :FunctionName:FilePath
```
Note that you can combine this with further `git log` options, like [revision ranges](https://git-scm.com/docs/gitrevisions) and [commit limits](https://git-scm.com/docs/git-log/#_commit_limiting).
### Find a tag where a commit is referenced
To find all tags containing a specific commit:
```sh
$ git tag --contains <commitid>
```
## Submodules
<a name="clone-submodules"></a>
### Clone all submodules
```sh
$ git clone --recursive git://github.com/foo/bar.git
```
If already cloned:
```sh
$ git submodule update --init --recursive
```
<a name="delete-submodule"></a>
### Remove a submodule
Creating a submodule is pretty straight-forward, but deleting them less so. The commands you need are:
```sh
$ git submodule deinit submodulename
$ git rm submodulename
$ git rm --cached submodulename
$ rm -rf .git/modules/submodulename
```
## Miscellaneous Objects
### Copy a folder or file from one branch to another
```sh
$ git checkout <branch-you-want-the-directory-from> -- <folder-name or file-name>
```
### Restore a deleted file
First find the commit when the file last existed:
```sh
$ git rev-list -n 1 HEAD -- filename
```
Then checkout that file:
```
git checkout deletingcommitid^ -- filename
```
### Delete tag
```sh
$ git tag -d <tag_name>
$ git push <remote> :refs/tags/<tag_name>
```
<a name="recover-tag"></a>
### Recover a deleted tag
If you want to recover a tag that was already deleted, you can do so by following these steps: First, you need to find the unreachable tag:
```sh
$ git fsck --unreachable | grep tag
```
Make a note of the tag's hash. Then, restore the deleted tag with following, making use of [`git update-ref`](https://git-scm.com/docs/git-update-ref):
```sh
$ git update-ref refs/tags/<tag_name> <hash>
```
Your tag should now have been restored.
### Deleted Patch
If someone has sent you a pull request on GitHub, but then deleted their original fork, you will be unable to clone their repository or to use `git am` as the [.diff, .patch](https://github.com/blog/967-github-secrets) URLs become unavailable. But you can checkout the PR itself using [GitHub's special refs](https://gist.github.com/piscisaureus/3342247). To fetch the content of PR#1 into a new branch called pr_1:
```sh
$ git fetch origin refs/pull/1/head:pr_1
From github.com:foo/bar
* [new ref] refs/pull/1/head -> pr_1
```
### Exporting a repository as a Zip file
```sh
$ git archive --format zip --output /full/path/to/zipfile.zip main
```
### Push a branch and a tag that have the same name
If there is a tag on a remote repository that has the same name as a branch you will get the following error when trying to push that branch with a standard `$ git push <remote> <branch>` command.
```sh
$ git push origin <branch>
error: dst refspec same matches more than one.
error: failed to push some refs to '<git server>'
```
Fix this by specifying you want to push the head reference.
```sh
$ git push origin refs/heads/<branch-name>
```
If you want to push a tag to a remote repository that has the same name as a branch, you can use a similar command.
```sh
$ git push origin refs/tags/<tag-name>
```
## Tracking Files
<a name="change-file-name-capitalization-without-changing-contents"></a>
### I want to change a file name's capitalization, without changing the contents of the file
```sh
(main)$ git mv --force myfile MyFile
```
### I want to overwrite local files when doing a git pull
```sh
(main)$ git fetch --all
(main)$ git reset --hard origin/main
```
<a name="remove-from-git"></a>
### I want to remove a file from Git but keep the file
```sh
(main)$ git rm --cached log.txt
```
### I want to revert a file to a specific revision
Assuming the hash of the commit you want is c5f567:
```sh
(main)$ git checkout c5f567 -- file1/to/restore file2/to/restore
```
If you want to revert to changes made just 1 commit before c5f567, pass the commit hash as c5f567~1:
```sh
(main)$ git checkout c5f567~1 -- file1/to/restore file2/to/restore
```
### I want to list changes of a specific file between commits or branches
Assuming you want to compare last commit with file from commit c5f567:
```sh
$ git diff HEAD:path_to_file/file c5f567:path_to_file/file
# or
$ git diff HEAD c5f567 -- path_to_file/file
```
If you are going to compare changes between the tips of the `main` and the `staging` branches:
```sh
$ git diff main:path_to_file/file staging:path_to_file/file
# or
$ git diff main staging -- path_to_file/file
```
### I want Git to ignore changes to a specific file
This works great for config templates or other files that require locally adding credentials that shouldn't be committed.
```sh
$ git update-index --assume-unchanged file-to-ignore
```
Note that this does *not* remove the file from source control - it is only ignored locally. To undo this and tell Git to notice changes again, this clears the ignore flag:
```sh
$ git update-index --no-assume-unchanged file-to-stop-ignoring
```
## Debugging with Git
The [git-bisect](https://git-scm.com/docs/git-bisect) command uses a binary search to find which commit in your Git history introduced a bug.
Suppose you're on the `main` branch, and you want to find the commit that broke some feature. You start bisect:
```sh
$ git bisect start
```
Then you should specify which commit is bad, and which one is known to be good. Assuming that your *current* version is bad, and `v1.1.1` is good:
```sh
$ git bisect bad
$ git bisect good v1.1.1
```
Now `git-bisect` selects a commit in the middle of the range that you specified, checks it out, and asks you whether it's good or bad. You should see something like:
```sh
$ Bisecting: 5 revision left to test after this (roughly 5 step)
$ [c44abbbee29cb93d8499283101fe7c8d9d97f0fe] Commit message
$ (c44abbb)$
```
You will now check if this commit is good or bad. If it's good:
```sh
$ (c44abbb)$ git bisect good
```
and `git-bisect` will select another commit from the range for you. This process (selecting `good` or `bad`) will repeat until there are no more revisions left to inspect, and the command will finally print a description of the **first** bad commit.
## Configuration
### I want to add aliases for some Git commands
On OS X and Linux, your git configuration file is stored in ```~/.gitconfig```. I've added some example aliases I use as shortcuts (and some of my common typos) in the ```[alias]``` section as shown below:
```vim
[alias]
a = add
amend = commit --amend
c = commit
ca = commit --amend
ci = commit -a
co = checkout
d = diff
dc = diff --changed
ds = diff --staged
extend = commit --amend -C HEAD
f = fetch
loll = log --graph --decorate --pretty=oneline --abbrev-commit
m = merge
one = log --pretty=oneline
outstanding = rebase -i @{u}
reword = commit --amend --only
s = status
unpushed = log @{u}
wc = whatchanged
wip = rebase -i @{u}
zap = fetch -p
day = log --reverse --no-merges --branches=* --date=local --since=midnight --author=\"$(git config --get user.name)\"
delete-merged-branches = "!f() { git checkout --quiet main && git branch --merged | grep --invert-match '\\*' | xargs -n 1 git branch --delete; git checkout --quiet @{-1}; }; f"
```
### I want to add an empty directory to my repository
You can’t! Git doesn’t support this, but there’s a hack. You can create a .gitignore file in the directory with the following contents:
```
# Ignore everything in this directory
*
# Except this file
!.gitignore
```
Another common convention is to make an empty file in the folder, titled .gitkeep.
```sh
$ mkdir mydir
$ touch mydir/.gitkeep
```
You can also name the file as just .keep , in which case the second line above would be ```touch mydir/.keep```
### I want to cache a username and password for a repository
You might have a repository that requires authentication. In which case you can cache a username and password so you don't have to enter it on every push and pull. Credential helper can do this for you.
```sh
$ git config --global credential.helper cache
# Set git to use the credential memory cache
```
```sh
$ git config --global credential.helper 'cache --timeout=3600'
# Set the cache to timeout after 1 hour (setting is in seconds)
```
To find a credential helper:
```sh
$ git help -a | grep credential
# Shows you possible credential helpers
```
For OS specific credential caching:
```sh
$ git config --global credential.helper osxkeychain
# For OSX
```
```sh
$ git config --global credential.helper manager
# Git for Windows 2.7.3+
```
```sh
$ git config --global credential.helper gnome-keyring
# Ubuntu and other GNOME-based distros
```
More credential helpers can likely be found for different distributions and operating systems.
### I want to make Git ignore permissions and filemode changes
```sh
$ git config core.fileMode false
```
If you want to make this the default behaviour for logged-in users, then use:
```sh
$ git config --global core.fileMode false
```
### I want to set a global user
To configure user information used across all local repositories, and to set a name that is identifiable for credit when review version history:
```sh
$ git config --global user.name “[firstname lastname]”
```
To set an email address that will be associated with each history marker:
```sh
git config --global user.email “[valid-email]”
```
## I've no idea what I did wrong
So, you're screwed - you `reset` something, or you merged the wrong branch, or you force pushed and now you can't find your commits. You know, at some point, you were doing alright, and you want to go back to some state you were at.
This is what `git reflog` is for. `reflog` keeps track of any changes to the tip of a branch, even if that tip isn't referenced by a branch or a tag. Basically, every time HEAD changes, a new entry is added to the reflog. This only works for local repositories, sadly, and it only tracks movements (not changes to a file that weren't recorded anywhere, for instance).
```sh
(main)$ git reflog
0a2e358 HEAD@{0}: reset: moving to HEAD~2
0254ea7 HEAD@{1}: checkout: moving from 2.2 to main
c10f740 HEAD@{2}: checkout: moving from main to 2.2
```
The reflog above shows a checkout from main to the 2.2 branch and back. From there, there's a hard reset to an older commit. The latest activity is represented at the top labeled `HEAD@{0}`.
If it turns out that you accidentally moved back, the reflog will contain the commit main pointed to (0254ea7) before you accidentally dropped 2 commits.
```sh
$ git reset --hard 0254ea7
```
Using `git reset` it is then possible to change main back to the commit it was before. This provides a safety net in case history was accidentally changed.
(copied and edited from [Source](https://www.atlassian.com/git/tutorials/rewriting-history/git-reflog)).
<a name="git-shortcuts"></a>
## Git Shortcuts
### Git Bash
Once you're comfortable with what the above commands are doing, you might want to create some shortcuts for Git Bash. This allows you to work a lot faster by doing complex tasks in really short commands.
```sh
alias sq=squash
function squash() {
git rebase -i HEAD~$1
}
```
Copy those commands to your .bashrc or .bash_profile.
### PowerShell on Windows
If you are using PowerShell on Windows, you can also set up aliases and functions. Add these commands to your profile, whose path is defined in the `$profile` variable. Learn more at the [About Profiles](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_profiles) page on the Microsoft documentation site.
```powershell
Set-Alias sq Squash-Commits
function Squash-Commits {
git rebase -i HEAD~$1
}
```
# Other Resources
## Books
* [Learn Enough Git to Be Dangerous](https://www.learnenough.com/git-tutorial) - A book by Michael Hartl covering Git from basics
* [Pro Git](https://git-scm.com/book/en/v2) - Scott Chacon and Ben Straub's excellent book about Git
* [Git Internals](https://github.com/pluralsight/git-internals-pdf) - Scott Chacon's other excellent book about Git
* [Nasa handbook](https://www.nasa.gov/wp-content/uploads/2018/09/nasa_systems_engineering_handbook_0.pdf)
## Tutorials
* [19 Git Tips For Everyday Use](https://www.alexkras.com/19-git-tips-for-everyday-use) - A list of useful Git one liners
* [Atlassian's Git tutorial](https://www.atlassian.com/git/tutorials) Get Git right with tutorials from beginner to advanced.
* [Getting solid at Git rebase vs. merge](https://medium.com/@porteneuve/getting-solid-at-git-rebase-vs-merge-4fa1a48c53aa)
* [Git and GitHub Cartoons](https://allisonhorst.com/git-github) – Cartoons by Allison Horst that showcase how to use Git.
* [Git Commands and Best Practices Cheat Sheet](https://zeroturnaround.com/rebellabs/git-commands-and-best-practices-cheat-sheet) - A Git cheat sheet in a blog post with more explanations
* [Git from the inside out](https://codewords.recurse.com/issues/two/git-from-the-inside-out) - A tutorial that dives into Git's internals
* [git-workflow](https://github.com/asmeurer/git-workflow) - [Aaron Meurer](https://github.com/asmeurer)'s howto on using Git to contribute to open source repositories
* [GitHub as a workflow](https://hugogiraudel.com/2015/08/13/github-as-a-workflow/) - An interesting take on using GitHub as a workflow, particularly with empty PRs
* [Githug](https://github.com/Gazler/githug) - A game to learn more common Git workflows
* [Learn Git branching](https://learngitbranching.js.org/) An interactive web based branching/merging/rebasing tutorial
* [learnGitBranching](https://github.com/pcottle/learnGitBranching) - An interactive git visualization to challenge and educate!
## Scripts and Tools
* [firstaidgit.io](http://firstaidgit.io/) A searchable selection of the most frequently asked Git questions
* [git-extra-commands](https://github.com/unixorn/git-extra-commands) - a collection of useful extra Git scripts
* [git-extras](https://github.com/tj/git-extras) - GIT utilities -- repo summary, repl, changelog population, author commit percentages and more
* [git-fire](https://github.com/qw3rtman/git-fire) - git-fire is a Git plugin that helps in the event of an emergency by adding all current files, committing, and pushing to a new branch (to prevent merge conflicts).
* [git-tips](https://github.com/git-tips/tips) - Small Git tips
* [git-town](https://github.com/Originate/git-town) - Generic, high-level Git workflow support! http://www.git-town.com
## GUI Clients
* [GitKraken](https://www.gitkraken.com/) - The downright luxurious Git client, for Windows, Mac & Linux
* [git-cola](https://git-cola.github.io/) - another Git client for Windows and OS X
* [GitUp](https://github.com/git-up/GitUp) - A newish GUI that has some very opinionated ways of dealing with Git's complications
* [gitx-dev](https://rowanj.github.io/gitx/) - another graphical Git client for OS X
* [Sourcetree](https://www.sourcetreeapp.com/) - Simplicity meets power in a beautiful and free Git GUI. For Windows and Mac.
* [Tower](https://www.git-tower.com/) - graphical Git client for OS X (paid)
* [tig](https://jonas.github.io/tig/) - terminal text-mode interface for Git
* [Magit](https://magit.vc/) - Interface to Git implemented as an Emacs package.
* [GitExtensions](https://github.com/gitextensions/gitextensions) - a shell extension, a Visual Studio 2010-2015 plugin and a standalone Git repository tool.
* [Fork](https://git-fork.com/) - a fast and friendly Git client for Mac (beta)
* [gmaster](https://gmaster.io/) - a Git client for Windows that has 3-way merge, analyze refactors, semantic diff and merge (beta)
* [gitk](https://git-scm.com/docs/gitk) - a Git client for linux to allow simple view of repo state.
* [SublimeMerge](https://www.sublimemerge.com/) - Blazing fast, extensible client that provides 3-way merges, powerful search and syntax highlighting, in active development.
================================================
FILE: README_es.md
================================================
# Reglas de vuelo para git
🌍
*[English](README.md) ∙ [Español](README_es.md) ∙ [Русский](README_ru.md) ∙ [繁體中文](README_zh-TW.md) ∙ [简体中文](README_zh-CN.md) ∙ [한국어](README_kr.md) ∙ [Tiếng Việt](README_vi.md) ∙ [Français](README_fr.md) ∙ [日本語](README_ja.md)*
#### ¿Qué son "reglas de vuelo"?
Una guía para astronautas (ahora, programadores usando git) acerca de qué hacer cuando las cosas van mal.
> *Las reglas de vuelo* son los conocimientos adquiridos con tanto esfuerzo en manuales que enumeran, paso a paso, qué hacer si ocurre X y por qué. Básicamente, son procedimientos operativos extremadamente detallados y específicos de cada escenario. [...]
> La NASA ha estado capturando nuestros errores, desastres y soluciones desde principios de la década de 1960, cuando los equipos de tierra de la era Mercurio comenzaron a recopilar "lecciones aprendidas" en un compendio que ahora enumera miles de situaciones problemáticas, desde fallas en el motor hasta fallas reventadas en computadoras, y sus soluciones.
— Chris Hadfield, *An Astronaut's Guide to Life*.
#### Convenciones para este documento
En aras de la claridad, todos los ejemplos de este documento usan un indicador de bash personalizado para señalar la rama actual y si hay cambios escalonados o no. La rama se incluye entre paréntesis, y un `*` al lado del nombre de la rama indica cambios realizados.
[](https://gitter.im/k88hudson/git-flight-rules?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
**Table of Contents** *generated with [DocToc](https://github.com/thlorenz/doctoc)*
- [Repositorios](#repositorios)
- [Quiero empezar un repositorio local](#quiero-empezar-un-repositorio-local)
- [Quiero clonar un repositorio remoto](#quiero-clonar-un-repositorio-remoto)
- [Editando commits](#editando-commits)
- [¿Qué acabo de hacer en el commit?](#%C2%BFqu%C3%A9-acabo-de-hacer-en-el-commit)
- [Escribí algo mal en el mensaje del commit](#escrib%C3%AD-algo-mal-en-el-mensaje-del-commit)
- [Hice un commit con el nombre y correo mal configurado](#hice-un-commit-con-el-nombre-y-correo-mal-configurado)
- [Quiero remover un archivo de un commit](#quiero-remover-un-archivo-de-un-commit)
- [Quiero borrar o remover mi último commit](#quiero-borrar-o-remover-mi-%C3%BAltimo-commit)
- [Eliminar/remover commit arbitrario](#eliminarremover-commit-arbitrario)
- [Intenté subir mi commit enmendado al repositorio remoto, pero obtuve un mensaje de error](#intent%C3%A9-subir-mi-commit-enmendado-al-repositorio-remoto-pero-obtuve-un-mensaje-de-error)
- [Accidentalmente hice un hard reset y quiero mis cambios de vuelta](#accidentalmente-hice-un-hard-reset-y-quiero-mis-cambios-de-vuelta)
- [Accidentalment hice un commit y empujé una fusión](#accidentalment-hice-un-commit-y-empuj%C3%A9-una-fusi%C3%B3n)
- [Accidentalmente hice un commit y empujé archivos que contienen data sensible](#accidentalmente-hice-un-commit-y-empuj%C3%A9-archivos-que-contienen-data-sensible)
- [Staging](#staging)
- [Necesito agregar otros cambios al commit anterior](#necesito-agregar-otros-cambios-al-commit-anterior)
- [Quiero agregar parte de un nuevo archivo, pero no todo el archivo](#quiero-agregar-parte-de-un-nuevo-archivo-pero-no-todo-el-archivo)
- [Quiero agregar cambios en un archivo a dos commits diferentes](#quiero-agregar-cambios-en-un-archivo-a-dos-commits-diferentes)
- [Quiero crear mis ediciones sin escalonar y eliminar mis ediciones escalonadas](#quiero-crear-mis-ediciones-sin-escalonar-y-eliminar-mis-ediciones-escalonadas)
- [Ediciones sin escena](#ediciones-sin-escena)
- [Deseo mover mis ediciones sin escena a una nueva rama](#deseo-mover-mis-ediciones-sin-escena-a-una-nueva-rama)
- [Deseo mover mis ediciones sin escena a una rama diferente existente](#deseo-mover-mis-ediciones-sin-escena-a-una-rama-diferente-existente)
- [Quiero descartar mis cambios locales no confirmados (en escena y sin escena)](#quiero-descartar-mis-cambios-locales-no-confirmados-en-escena-y-sin-escena)
- [Quiero descartar cambios específicos no planificados](#quiero-descartar-cambios-espec%C3%ADficos-no-planificados)
- [Quiero descartar archivos específicos no escaneados](#quiero-descartar-archivos-espec%C3%ADficos-no-escaneados)
- [Deseo descartar solo mis cambios locales sin escenario](#deseo-descartar-solo-mis-cambios-locales-sin-escenario)
- [Quiero descartar todos mis archivos sin seguimiento](#quiero-descartar-todos-mis-archivos-sin-seguimiento)
- [Ramas](#ramas)
- [Quiero enumerar todas las ramas](#quiero-enumerar-todas-las-ramas)
- [Crear una rama desde una confirmación](#crear-una-rama-desde-una-confirmaci%C3%B3n)
- [Hice pull de / en la rama incorrecta](#hice-pull-de--en-la-rama-incorrecta)
- [Quiero descartar confirmaciones locales para que mi rama sea la misma que la del servidor](#quiero-descartar-confirmaciones-locales-para-que-mi-rama-sea-la-misma-que-la-del-servidor)
- [Hice commit a main en lugar de una nueva rama](#hice-commit-a-main-en-lugar-de-una-nueva-rama)
- [Quiero mantener todo el archivo de otro ref-ish](#quiero-mantener-todo-el-archivo-de-otro-ref-ish)
- [Realicé varios commits en una sola rama que debería estar en diferentes ramas](#realic%C3%A9-varios-commits-en-una-sola-rama-que-deber%C3%ADa-estar-en-diferentes-ramas)
- [Quiero eliminar las ramas locales que se eliminaron en sentido ascendente](#quiero-eliminar-las-ramas-locales-que-se-eliminaron-en-sentido-ascendente)
- [Accidentalmente borré mi rama](#accidentalmente-borr%C3%A9-mi-rama)
- [Quiero eliminar una rama](#quiero-eliminar-una-rama)
- [Quiero eliminar varias ramas](#quiero-eliminar-varias-ramas)
- [Quiero cambiar el nombre de una rama](#quiero-cambiar-el-nombre-de-una-rama)
- [Quiero hacer checkout en una rama remota en la que alguien más está trabajando](#quiero-hacer-checkout-en-una-rama-remota-en-la-que-alguien-m%C3%A1s-est%C3%A1-trabajando)
- [Quiero crear una nueva rama remota desde la actual local](#quiero-crear-una-nueva-rama-remota-desde-la-actual-local)
- [Quiero configurar una rama remota como upstream para una rama local](#quiero-configurar-una-rama-remota-como-upstream-para-una-rama-local)
- [Quiero configurar mi HEAD para rastrear la rama remota predeterminada](#quiero-configurar-mi-head-para-rastrear-la-rama-remota-predeterminada)
- [Rebasing y Merging](#rebasing-y-merging)
- [Quiero deshacer rebase/merge](#quiero-deshacer-rebasemerge)
- [Hice rebase, pero no quiero forzar el push](#hice-rebase-pero-no-quiero-forzar-el-push)
- [Necesito combinar commits](#necesito-combinar-commits)
- [Estrategia de merge segura](#estrategia-de-merge-segura)
- [Necesito fusionar una rama en un solo commit](#necesito-fusionar-una-rama-en-un-solo-commit)
- [Quiero combinar solo los commits sin haber hecho push](#quiero-combinar-solo-los-commits-sin-haber-hecho-push)
- [Necesito abortar el merge](#necesito-abortar-el-merge)
- [Comprobar si se combinan todos los commits de un branch](#comprobar-si-se-combinan-todos-los-commits-de-un-branch)
- [Posibles problemas con rebase interactivos](#posibles-problemas-con-rebase-interactivos)
- [La pantalla de edición de rebase dice 'noop'](#la-pantalla-de-edici%C3%B3n-de-rebase-dice-noop)
- [Hubo conflictos](#hubo-conflictos)
- [Stash](#stash)
- [Usar stash en todos los cambios](#usar-stash-en-todos-los-cambios)
- [Usar stash para archivos específicos](#usar-stash-para-archivos-espec%C3%ADficos)
- [Usar stash con un mensaje](#usar-stash-con-un-mensaje)
- [Aplicar un stash específico de la lista](#aplicar-un-stash-espec%C3%ADfico-de-la-lista)
- [Búsqueda](#b%C3%BAsqueda)
- [Quiero encontra un string en algún commit](#quiero-encontra-un-string-en-alg%C3%BAn-commit)
- [Quiero buscar por autor / committer](#quiero-buscar-por-autor--committer)
- [Quiero enumerar commits que contienen archivos específicos](#quiero-enumerar-commits-que-contienen-archivos-espec%C3%ADficos)
- [Encontrar una etiqueta donde se hace referencia a un commit](#encontrar-una-etiqueta-donde-se-hace-referencia-a-un-commit)
- [Submódulos](#subm%C3%B3dulos)
- [Clonar todos los submódulos](#clonar-todos-los-subm%C3%B3dulos)
- [Remover un submódulo](#remover-un-subm%C3%B3dulo)
- [Objetos diversos](#objetos-diversos)
- [Restaurar un archivo eliminado](#restaurar-un-archivo-eliminado)
- [Eliminar una etiqueta](#eliminar-una-etiqueta)
- [Recuperar una etiqueta eliminada](#recuperar-una-etiqueta-eliminada)
- [Patch eliminado](#patch-eliminado)
- [Exportar un repositorio como un archivo Zip](#exportar-un-repositorio-como-un-archivo-zip)
- [Seguimiento de archivos](#seguimiento-de-archivos)
- [Quiero cambiar el uso de mayúsculas de un nombre de archivo, sin cambiar el contenido del archivo](#quiero-cambiar-el-uso-de-may%C3%BAsculas-de-un-nombre-de-archivo-sin-cambiar-el-contenido-del-archivo)
- [Quiero sobrescribir los archivos locales cuando hago un git pull](#quiero-sobrescribir-los-archivos-locales-cuando-hago-un-git-pull)
- [Quiero eliminar un archivo de Git pero mantener el archivo](#quiero-eliminar-un-archivo-de-git-pero-mantener-el-archivo)
- [Quiero revertir un archivo a una revisión específica](#quiero-revertir-un-archivo-a-una-revisi%C3%B3n-espec%C3%ADfica)
- [Configuración](#configuraci%C3%B3n)
- [Quiero agregar alias para algunos comandos de Git](#quiero-agregar-alias-para-algunos-comandos-de-git)
- [Quiero agregar un directorio vacío a mi repositorio](#quiero-agregar-un-directorio-vac%C3%ADo-a-mi-repositorio)
- [Quiero guardar en caché un nombre de usuario y contraseña para un repositorio](#quiero-guardar-en-cach%C3%A9-un-nombre-de-usuario-y-contrase%C3%B1a-para-un-repositorio)
- [Quiero hacer que Git ignore los permisos y cambios en el modo de archivo](#quiero-hacer-que-git-ignore-los-permisos-y-cambios-en-el-modo-de-archivo)
- [No tengo idea de lo que hice mal](#no-tengo-idea-de-lo-que-hice-mal)
- [Otros recursos](#otros-recursos)
- [Libros](#libros)
- [Tutoriales](#tutoriales)
- [Scripts y herramientas](#scripts-y-herramientas)
- [Clientes GUI](#clientes-gui)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Repositorios
### Quiero empezar un repositorio local
Para inicializar un directorio existente como un repositorio de Git:
```sh
(my-folder) $ git init
```
### Quiero clonar un repositorio remoto
Para clonar (copiar) un repositorio remoto, copia la url del repositorio y ejecuta:
```sh
$ git clone [url]
```
## Editando commits
### ¿Qué acabo de hacer en el commit?
Digamos que simplemente hiciste cambios a ciegas con `git commit -a` y no estás seguro de cuál fue el contenido real de la confirmación que acabas de realizar. Puedes mostrar el último commit en su HEAD actual con:
```sh
(main)$ git show
```
o
```sh
$ git log -n1 -p
```
### Escribí algo mal en el mensaje del commit
Si escribiste algo mal y todavía no has subido tu commit, puedes hacer lo siguiente para cambiar el mensaje del commit:
```sh
$ git commit --amend --only
```
Esto abrirá tu editor de texto por defecto, donde puedes editar el mensaje. Por otro lado, tú puedes hacer todo esto con un solo comando:
```sh
$ git commit --amend --only -m 'xxxxxxx'
```
Si ya has subido tu commit, puedes corregirlo usando amend y luego forzar el push, pero esto no es recomendado.
### Hice un commit con el nombre y correo mal configurado
Si es un solo commit, corrígelo
```sh
$ git commit --amend --author "Nuevo autor <authoremail@mydomain.com>"
```
Si necesitas cambiar todo el historial, mira la página 'git filter-branch' del manual
### Quiero remover un archivo de un commit
Para remover un archivo de un commit, haz lo siguiente:
```sh
$ git checkout HEAD^ miArchivo
$ git add -A
$ git commit --amend
```
Esto es particularmente útil cuando tienes un patch abierto y has hecho commit de un archivo innecesario, necesitar forzar el push para actualizar el parche en un control remoto.
### Quiero borrar o remover mi último commit
Si necesitas eliminar commits, puedes usar lo siguiente. Sin embargo, cambiará irreversiblemente su historial y arruinará la historia de cualquier otra persona que ya haya clonado el repositorio. En resumen, si no estás seguro, nunca deberías hacer esto, nunca.
```sh
$ git reset HEAD^ --hard
$ git push --force-with-lease [remote] [branch]
```
Si no has subido tus cambios, para resetear Git al estado en el que estaba antes de realizar tu último commit (mientras mantengas tus cambios en staging):
```
(my-branch)$ git reset --soft HEAD^
```
Esto solo funciona si no subiste tu commit. Si lo hiciste, la única cosa segura por hacer es `git revert SHAofBadCommit`. Eso creará un nuevo commit que deshace todos los cambios del anterior commit. O, si la rama que subiste es segura ante reorganizaciones (ej. otros desarrolladores no esperan recibir cambios desde ahí), puedes usar `git push --force-with-lease`. Para más, mira [la sección de arriba](#quiero-borrar-o-remover-mi-ultimo-commit).
### Eliminar/remover commit arbitrario
La misma advertencia de arriba. Nunca hagas esto si es posible.
```sh
$ git rebase --onto SHA1_OF_BAD_COMMIT^ SHA1_OF_BAD_COMMIT
$ git push --force-with-lease [remote] [branch]
```
O haz un [rebase-interactivo](#rebase-interactivo) y remueve la(s) línea(s) correspondientes al commit que quieres remover.
### Intenté subir mi commit enmendado al repositorio remoto, pero obtuve un mensaje de error
```sh
To https://github.com/yourusername/repo.git
! [rejected] mybranch -> mybranch (non-fast-forward)
error: failed to push some refs to 'https://github.com/tanay1337/webmaker.org.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
```
Ten en cuenta que, al igual que con el rebase (ver más abajo), usar amend **reemplaza el anterior commit con uno nuevo**, por lo que debes forzar el push (`--force-with-lease`) de tus cambios si ya has hecho una confirmación previamente enmendada al repositorio remoto. ¡Ten cuidado cuando hagas esto – *siempre* asegúrate de especificar una rama!
```sh
(my-branch)$ git push origin mybranch --force-with-lease
```
En general, **evita forzar el push**. Es mejor crear y subir un nuevo commit que forzar el commit enmendado porque causará conflictos en el historial fuente para cualquier otro desarrolador que ha interactuado con la rama en cuestión o una de sus ramas hijas. `--force-with-lease` aún fallará, si alguien más estuviera trabajando en la misma rama que tú, y tu push forzado sobrescribiría sus cambios.
Si estás *absolutamente* seguro que nadie está trabajando en la misma rama o que tú quieres actualizar la rama *incondicionalmente*, puedes usar `--force` (`-f`), pero esto debería ser evitado en general.
### Accidentalmente hice un hard reset y quiero mis cambios de vuelta
Si accidentalmente hiciste `git reset --hard`, puedes volver a obtener tus commits de vuelta ya que git mantiene un registro de todo durante unos días.
```sh
(main)$ git reflog
```
Verás una lista de tus antiguos commits, y un commit para el reset. Escoge el SHA del commit al que quieres retornar y has el reset de nuevo:
```sh
(main)$ git reset --hard SHA1234
```
Y deberías estar ubicado en ese commit.
### Accidentalment hice un commit y empujé una fusión
Si accidentalmente fusionaste una rama a la principal de desarrollo antes de que esté lista para fusionar, todavía puedes deshacer esa fusión. Pero hay un problema: Un commit de fusión tiene más de un padre (usualmente 2).
El comando a usar
```sh
(feature-branch)$ git revert -m 1 <commit>
```
donde la opción -m 1 option menciona seleccionar el padre número 1 (la rama en la cual se hizo la fusión) como el padre a revertirlo.
Nota: el número padre no es un identificador de commit. Más bien, un commit de fusión tiene una línea `Merge: 8e2ce2d 86ac2e7`. El número padre empieza con el número 1 como índice, el primer identificador es número 1, el segundo es el número 2, y así
### Accidentalmente hice un commit y empujé archivos que contienen data sensible
Si accidentalment empujaste archivos que contienen data sensible (contraseñas, llaves, etc.), puedes modificar el commit previo. Ten en mente que una vez que hayas hecho un commit, debes considerar cualquier información que éste contiene para ser empujado. Estos pasos pueden remover la data sensible de tu repo público o tu copia local, pero **no puedes** remover la data sensible de copias jaladas de otras personas. Si quieres hacer un commit de una contraseña, **cámbialo de inmediato**. Si hiciste commit de una llave, **regenérala de inmediato**. Modificar el commit enviado no es suficiente, ya que cualquiera podría haber retirado el commit original que contiene sus datos confidenciales en ese tiempo.
Si editas un archivo y remueves la data sensible, entonces ejecuta
```sh
(feature-branch)$ git add edited_file
(feature-branch)$ git commit --amend --no-edit
(feature-branch)$ git push --force-with-lease origin [branch]
```
Si quieres remover un archivo entero (pero mantenerlo localmente), entonces ejecuta
```sh
(feature-branch)$ git rm --cached sensitive_file
echo sensitive_file >> .gitignore
(feature-branch)$ git add .gitignore
(feature-branch)$ git commit --amend --no-edit
(feature-branch)$ git push --force-with-lease origin [branch]
```
Alternativamente guarda tu data sensible en variables de entorno locales.
Si quieres remover completamente un archivo completo (y no mantenerlo localmente), entonces ejecuta
```sh
(feature-branch)$ git rm sensitive_file
(feature-branch)$ git commit --amend --no-edit
(feature-branch)$ git push --force-with-lease origin [branch]
```
Si haz hecho otros commits durante ese tiempo (ej. la data sensible está en un commit antes de ese commit), necesitarás hacer un rebase.
## Staging
### Necesito agregar otros cambios al commit anterior
```sh
(mi-rama*)$ git commit --amend
```
### Quiero agregar parte de un nuevo archivo, pero no todo el archivo
Normalmente, si deseas representar parte de un archivo, ejecuta esto:
```sh
$ git add --patch archivo.x
```
`-p` funcionará para abreviar. Esto abrirá el modo interactivo. Puedes usar la opción `s` para dividir la confirmación; sin embargo, si el archivo es nuevo, no tendrás esta opción. Para agregar un nuevo archivo, usa esto:
```sh
$ git add -N archivo.x
```
Luego, necesitarás usar la opción `e` para elegir manualmente qué líneas agregar. Ejecutando `git diff --cached` o
`git diff -staged` se mostrará qué líneas ha comparado con las que todavía se guardan localmente.
### Quiero agregar cambios en un archivo a dos commits diferentes
`git add` agregará el archivo completo a un commit. `git add -p` te permitirá seleccionar interactivamente los cambios que deseas agregar.
### Quiero crear mis ediciones sin escalonar y eliminar mis ediciones escalonadas
Esto es complicado. Lo mejor que creo es que debes esconder tus ediciones sin escena. Luego, restablecer. Después de eso, muestra tus cambios ocultos y agrégalos.
```sh
$ git stash -k
$ git reset --hard
$ git stash pop
$ git add -A
```
## Ediciones sin escena
### Deseo mover mis ediciones sin escena a una nueva rama
```sh
$ git checkout -b mi-rama
```
### Deseo mover mis ediciones sin escena a una rama diferente existente
```sh
$ git stash
$ git checkout my-rama
$ git stash pop
```
### Quiero descartar mis cambios locales no confirmados (en escena y sin escena)
Si deseas descartar todos los cambios organizados y no supervisados locales, puede hacer esto:
```sh
(mi-rama) $ git reset --hard
# o
(main) $ git checkout -f
```
Esto borrará todos los archivos que hayas organizado con `git add`:
```sh
$ git reset
```
Esto revertirá todos los cambios locales no confirmados (se debe ejecutar en la raíz del repositorio):
```sh
$ git checkout .
```
También puedes revertir cambios no confirmados a un archivo o directorio en particular:
```sh
$ git checkout [some_dir | file.txt]
```
Otra forma de revertir todos los cambios no confirmados (más largo de escribir, pero funciona desde cualquier subdirectorio):
```sh
$ git reset --hard HEAD
```
Esto eliminará todos los archivos locales sin seguimiento, por lo que solo se conservarán los archivos rastreados por Git:
```sh
$ git clean -fd
```
`-x` también eliminará todos los archivos ignorados.
### Quiero descartar cambios específicos no planificados
Cuando desees deshacerse de algunos, pero no de todos los cambios en su copia de trabajo.
Verifica los cambios no deseados, mantén buenos cambios.
```sh
$ git checkout -p
# Responde y a todos los cambios que desea eliminar
```
Otra estrategia implica el uso de `stash`. Guarda todos los buenos cambios, restablece la copia de trabajo y vuelve a aplicar los buenos cambios.
```sh
$ git stash -p
# Selecciona todos los cambios que desea guardar
$ git reset --hard
$ git stash pop
```
Alternativamente, oculta sus cambios no deseados, y luego deja el escondite.
```sh
$ git stash -p
# Selecciona todos los cambios que no quiere guardar
$ git stash drop
```
### Quiero descartar archivos específicos no escaneados
Cuando desees deshacerse de un archivo específico en su copia de trabajo.
```sh
$ git checkout myFile
```
Alternativamente, para descartar varios archivos en su copia de trabajo, enumera todos.
```sh
$ git checkout myFirstFile mySecondFile
```
### Deseo descartar solo mis cambios locales sin escenario
Cuando desees deshacerse de todos sus cambios no confirmados locales sin confirmar
```sh
$ git checkout .
```
### Quiero descartar todos mis archivos sin seguimiento
Cuando desees deshacerse de todos sus archivos sin seguimiento
```sh
$ git clean -f
```
## Ramas
### Quiero enumerar todas las ramas
Enumerar ramas locales
```sh
$ git branch
```
Enumerar ramas remotas
```sh
$ git branch -r
```
Listar todas las ramas (tanto locales como remotas)
```sh
$ git branch -a
```
### Crear una rama desde una confirmación
```sh
$ git checkout -b <branch> <SHA1_OF_COMMIT>
```
### Hice pull de / en la rama incorrecta
Esta es otra oportunidad de usar `git reflog` para ver dónde apuntó el HEAD antes del mal tirón.
```sh
(main) $ git reflog
ab7555f HEAD @ {0}: pull-wrong-branch: Fast-forward
c5bc55a HEAD @ {1}: checkout: checkout message goes here
```
Simplemente restablece tu rama al commit deseado:
```sh
$ git reset --hard c5bc55a
```
Hecho.
### Quiero descartar confirmaciones locales para que mi rama sea la misma que la del servidor
Confirma que no ha enviado sus cambios al servidor.
`git status` debe mostrar cuántos commits tienes adelantado al origin:
```sh
(my-branch)$ git status
# On branch my-branch
# Your branch is ahead of 'origin/my-branch' by 2 commits.
# (use "git push" to publish your local commits)
#
```
Una forma de reiniciar para hacer coincidir el origin (tener lo mismo que lo que está en el control remoto) es hacer esto:
```sh
(my-branch) $ git reset --hard origin/my-branch
```
### Hice commit a main en lugar de una nueva rama
Crea la nueva rama mientras permaneces en main:
```sh
(main) $ git branch my-branch
```
Restablece la rama main al commit anterior:
```sh
(main) $ git reset --hard HEAD ^
```
`HEAD ^` es la abreviatura de `HEAD ^ 1`. Esto representa el primer padre de `HEAD`, del mismo modo` HEAD ^ 2` representa el segundo padre del commit (las fusiones pueden tener 2 padres).
Ten en cuenta que `HEAD ^ 2` ** no ** es lo mismo que` HEAD ~ 2` (vea [este enlace] (http://www.paulboxley.com/blog/2011/06/git-caret-and-tilde) para más información).
Alternativamente, si no quieres usar `HEAD ^`, averigüe a qué hash de confirmación quieres establecer su rama principal (`git log` debería ser el truco). Luego reinicia a ese hash. `git push` se asegurará de que este cambio se refleje en su control remoto.
Por ejemplo, si el hash del commit en el que se supone que está su rama principal es `a13b85e`:
```sh
(main) $ git reset --hard a13b85e
HEAD is now at a13b85e
```
Verifique la nueva rama para continuar trabajando:
```sh
(main) $ git checkout my-branch
```
### Quiero mantener todo el archivo de otro ref-ish
Supongamos que tienes un pico activo (ver nota), con cientos de cambios. Todo está funcionando. Ahora, te comprometes con otra rama para guardar ese trabajo:
```sh
(solución) $ git add -A && git commit -m "Agregando todos los cambios desde este pico en un gran compromiso."
```
Cuando desees colocarlo en una rama (tal vez función, tal vez `develop`), te interesa conservar archivos completos. Quieres dividir tu gran compromiso en otros más pequeños.
Digamos que tienes:
* branch `solution`, con la solución para tu spike. Uno por delante de `develop`.
* branch `develop`, donde desea agregar sus cambios.
Puedes resolverlo llevando los contenidos a tu rama:
```sh
(develop) $ git checkout solution - file1.txt
```
Esto obtendrá los contenidos de ese archivo en la 'solución' de la rama a su rama `develop`:
```sh
# On branch develop
# Your branch is up-to-date with 'origin/develop'.
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# modified: file1.txt
```
Entonces, haz un commit como de costumbre.
Nota: Las soluciones de Spike están hechas para analizar o resolver el problema. Estas soluciones se utilizan para la estimación y se descartan una vez que todos obtienen una visualización clara del problema. ~ [Wikipedia] (https://en.wikipedia.org/wiki/Extreme_programming_practices).
### Realicé varios commits en una sola rama que debería estar en diferentes ramas
Digamos que estás en tu rama principal. Al ejecutar `git log`, verás que ha realizado dos commits:
```sh
(main) $ git log
commit e3851e817c451cc36f2e6f3049db528415e3c114
Author: Alex Lee <alexlee@example.com>
Date: Tue Jul 22 15:39:27 2014 -0400
Bug #21 - Added CSRF protection
commit 5ea51731d150f7ddc4a365437931cd8be3bf3131
Author: Alex Lee <alexlee@example.com>
Date: Tue Jul 22 15:39:12 2014 -0400
Bug #14 - Fixed spacing on title
commit a13b85e984171c6e2a1729bb061994525f626d14
Author: Aki Rose <akirose@example.com>
Date: Tue Jul 21 01:12:48 2014 -0400
First commit
```
Toma nota de nuestros hashes de confirmación para cada error (`e3851e8` para # 21,` 5ea5173` para # 14).
Primero, restablece la rama principal al commit correcto (`a13b85e`):
```sh
(main)$ git reset --hard a13b85e
HEAD is now at a13b85e
```
Ahora, puedes crear una nueva rama para la rama bug # 21:
```sh
(main) $ git checkout -b 21
(21) $
```
Ahora, * selecciona con precisión * el commit para el error # 21 en la parte superior de la rama. Eso significa que aplicarás ese commit, y solo ese commit, directamente sobre el HEAD que estés.
```sh
(21) $ git cherry-pick e3851e8
```
En este punto, existe la posibilidad de que haya conflictos. Consulta la sección ** Hubo conflictos ** (# conflicto de fusión) en la [sección interactiva de rebase más arriba] (# interactive-rebase) para saber cómo resolver conflictos.
Ahora creamos una nueva rama para el error # 14, también basado en el main
```sh
(21) $ git checkout main
(main) $ git checkout -b 14
(14) $
```
Y finalmente, vamos a seleccionar el compromiso para el error # 14:
```sh
(14) $ git cherry-pick 5ea5173
```
### Quiero eliminar las ramas locales que se eliminaron en sentido ascendente
Una vez que fusiona una solicitud de extracción en GitHub, le da la opción de eliminar la rama fusionada en su fork. Si no tiene planeado seguir trabajando en la rama, es más limpio eliminar las copias locales de la rama para que no termine complicando su proceso de pago con muchas ramas obsoletas.
```sh
$ git fetch -p upstream
```
donde, 'ascendente' es el control remoto desde el que desea recuperar.
### Accidentalmente borré mi rama
Si empujas regularmente hacia el control remoto, deberías estar seguro la mayor parte del tiempo. Pero aún así a veces puede terminar borrando sus ramaes. Digamos que creamos una rama y creamos un nuevo archivo:
```sh
(main)$ git checkout -b my-branch
(my-branch)$ git branch
(my-branch)$ touch foo.txt
(my-branch)$ ls
README.md foo.txt
```
Vamos a agregarlo y hacer el commit.
```sh
(my-branch)$ git add .
(my-branch)$ git commit -m 'foo.txt added'
(my-branch)$ foo.txt added
1 files changed, 1 insertions(+)
create mode 100644 foo.txt
(my-branch)$ git log
commit 4e3cd85a670ced7cc17a2b5d8d3d809ac88d5012
Author: siemiatj <siemiatj@example.com>
Date: Wed Jul 30 00:34:10 2014 +0200
foo.txt added
commit 69204cdf0acbab201619d95ad8295928e7f411d5
Author: Kate Hudson <katehudson@example.com>
Date: Tue Jul 29 13:14:46 2014 -0400
Fixes #6: Force pushing after amending commits
```
Ahora estamos volviendo a "main" y "accidentalmente" eliminando nuestra rama.
```sh
(my-branch)$ git checkout main
Switched to branch 'main'
Your branch is up-to-date with 'origin/main'.
(main)$ git branch -D my-branch
Deleted branch my-branch (was 4e3cd85).
(main)$ echo oh noes, deleted my branch!
oh noes, deleted my branch!
```
En este punto, debe familiarizarse con 'reflog', un registrador actualizado. Almacena el historial de todas las acciones en el repositorio.
```
(main)$ git reflog
69204cd HEAD@{0}: checkout: moving from my-branch to main
4e3cd85 HEAD@{1}: commit: foo.txt added
69204cd HEAD@{2}: checkout: moving from main to my-branch
```
Como puede ver, hemos confirmado el hash de nuestra rama eliminada. Veamos si podemos restaurar nuestra rama eliminada.
```sh
(main)$ git checkout -b my-branch-help
Switched to a new branch 'my-branch-help'
(my-branch-help)$ git reset --hard 4e3cd85
HEAD is now at 4e3cd85 foo.txt added
(my-branch-help)$ ls
README.md foo.txt
```
Voila! Recuperamos nuestro archivo eliminado. `git reflog` también es útil cuando el rebase es terriblemente incorrecto.
### Quiero eliminar una rama
Para eliminar una rama remota:
```sh
(main) $ git push origin --delete my-branch
```
También puedes hacer:
```sh
(main) $ git push origin: my-branch
```
Para eliminar una rama local:
```sh
(main) $ git branch -d my-branch
```
Para eliminar una rama local que * no * se ha fusionado con la rama actual o una cadena ascendente:
```sh
(main) $ git branch -D my-branch
```
### Quiero eliminar varias ramas
Supongamos que quiere eliminar todas las ramas que comienzan con `fix /`:
```sh
(main) $ git rama | grep 'fix /' | xargs git branch -d
```
### Quiero cambiar el nombre de una rama
Para cambiar el nombre de la rama actual (local):
```sh
(main) $ git branch -m new-name
```
Para cambiar el nombre de una rama diferente (local):
```sh
(main) $ git branch -m old-name new-name
```
### Quiero hacer checkout en una rama remota en la que alguien más está trabajando
Primero, busca todas las ramas desde el control remoto:
```sh
(main)$ git fetch --all
```
Digamos que quieres hacer checkout a `daves` desde el repositorio remoto.
```sh
(main)$ git checkout --track origin/daves
Branch daves set up to track remote branch daves from origin.
Switched to a new branch 'daves'
```
(`--track` es la abreviatura de 'git checkout -b [branch] [remotename] / [branch]`)
Esto le dará una copia local de la rama `daves`, y cualquier actualización que se haya enviado también se mostrará de forma remota.
### Quiero crear una nueva rama remota desde la actual local
```sh
$ git push <remote>
```
Si también desea establecer esa rama remota como cadena arriba para la actual, use lo siguiente:
```sh
$ git push -u <remote>
```
Con el modo `upstream` y el modo `simple` (predeterminado en Git 2.0) de la configuración `push.default`, el siguiente comando empujará la bifurcación actual con respecto a la bifurcación remota que se ha registrado previamente con `-u `:
```sh
$ git push
```
El comportamiento de los otros modos de ```git push``` se describe en el documento de push.default.
### Quiero configurar una rama remota como upstream para una rama local
Puedes establecer una rama remota como ascendente para la sucursal local actual usando:
```sh
$ git branch --set-upstream-to [remotename]/[branch]
# or, using the shorthand:
$ git branch -u [remotename]/[branch]
```
Para establecer la rama remota ascendente para otra rama local:
```sh
$ git branch -u [remotename] / [branch] [local-branch]
```
### Quiero configurar mi HEAD para rastrear la rama remota predeterminada
Al verificar tus ramas remotas, puedes ver en qué rama remota está rastreando el HEAD. En algunos casos, esta no es la rama deseada.
```sh
$ git branch -r
origin/HEAD -> origin/gh-pages
origin/main
```
Cambiar `origin / HEAD` para rastrear` origin / main`, puedes ejecutar este comando:
```sh
$ git remote set-head origin --auto
origin/HEAD set to main
```
## Rebasing y Merging
### Quiero deshacer rebase/merge
Es posible que hayas fusionado o rediseñado tu rama actual con una rama incorrecta, o que no puedas resolverlo o finalizar el proceso de rebase/merge. Git guarda el puntero original HEAD en una variable llamada ORIG_HEAD antes de realizar operaciones peligrosas, por lo que es sencillo recuperar la rama en el estado anterior al rebase/merge.
```sh
(my-branch)$ git reset --hard ORIG_HEAD
```
### Hice rebase, pero no quiero forzar el push
Desafortunadamente, debes forzar el push, si deseas que esos cambios se reflejen en la rama remota. Esto se debe a que ha cambiado el historial. La rama remota no aceptará cambios a menos que fuerce la inserción. Esta es una de las principales razones por las que muchas personas usan un flujo de trabajo de merge, en lugar de un flujo de trabajo de reordenación: los equipos grandes pueden tener problemas con el impulso de los desarrolladores. Usa esto con precaución. Una forma más segura de utilizar rebase no es reflejar los cambios en la rama remota, sino hacer lo siguiente:
```sh
(main)$ git checkout my-branch
(my-branch)$ git rebase -i main
(my-branch)$ git checkout main
(main)$ git merge --ff-only my-branch
```
Para obtener más información, consulte [este thread SO] (https://stackoverflow.com/questions/11058312/how-can-i-use-git-rebase-without-requiring-a-forced-push).
### Necesito combinar commits
Supongamos que estás trabajando en una rama que es / se convertirá en un pull request contra main. En el caso más simple, cuando todo lo que quiere hacer es combinar todos los commits en uno solo y no le importa cometer timestamps, puedes restablecer y volver a hacer el commit. Asegúrate de que la rama principal esté actualizada y de que se hayan confirmado todos los cambios, luego:
```sh
(my-branch)$ git reset --soft main
(my-branch)$ git commit -am "New awesome feature"
```
Si deseas más control y también conservar las marcas de tiempo, debe hacer algo que se llame un rebase interactivo:
```sh
(my-branch)$ git rebase -i main
```
Si no estás trabajando contra otra rama tendrás que volver a establecer una base relativa a tu `HEAD`. Si quieres aplastar las últimas 2 confirmaciones, por ejemplo, tendrás que volver a calcular contra `HEAD ~ 2`. Para los últimos 3, `HEAD ~ 3`, etc.
```sh
(main)$ git rebase -i HEAD~2
```
Después de ejecutar el comando de rebase interactivo, verás algo como esto en tu editor de texto:
```vim
pick a9c8a1d Some refactoring
pick 01b2fd8 New awesome feature
pick b729ad5 fixup
pick e3851e8 another fix
# Rebase 8074d12..b729ad5 onto 8074d12
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out
```
Todas las líneas que comienzan con `#` son comentarios, no afectarán a tu rebase.
Reemplaza los comandos `pick` con cualquiera en la lista anterior, y también puedes eliminar commits eliminando las líneas correspondientes.
Por ejemplo, si deseas **dejar el commit más antiguo (el primero) solo y combinar todos los siguientes commits con el segundo más antiguo**, debes editar la letra junto a cada commit, excepto la primera y la segunda para decir `f` :
```vim
pick a9c8a1d Some refactoring
pick 01b2fd8 New awesome feature
f b729ad5 fixup
f e3851e8 another fix
```
Si deseas combinar estos commits **y cambiar el nombre del commit**, también debes agregar una `r` junto al segundo commit o simplemente usar` s` en lugar de `f`:
```vim
pick a9c8a1d Some refactoring
pick 01b2fd8 New awesome feature
s b729ad5 fixup
s e3851e8 another fix
```
A continuación, puedes cambiar el nombre del commit en el siguiente mensaje de texto que aparece.
```vim
Newer, awesomer features
# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
# rebase in progress; onto 8074d12
# You are currently editing a commit while rebasing branch 'main' on '8074d12'.
#
# Changes to be committed:
# modified: README.md
#
```
Si todo tiene éxito, deberías ver algo como esto:
```sh
(main)$ Successfully rebased and updated refs/heads/main.
```
#### Estrategia de merge segura
`--no-commit` realiza el merge, pero simula que la combinación falló y no se confirma automáticamente, lo que le da al usuario la oportunidad de inspeccionar y modificar aún más el resultado de la combinación antes de realizar la tarea. `no-ff` mantiene la evidencia de que alguna vez existió una rama de características, manteniendo la historia del proyecto consistente.
```sh
(main)$ git merge --no-ff --no-commit my-branch
```
#### Necesito fusionar una rama en un solo commit
```sh
(main)$ git merge --squash my-branch
```
#### Quiero combinar solo los commits sin haber hecho push
A veces tiene varios commits en progreso que deseas combinar antes de hacer push. No deseas combinar accidentalmente ningún commit que ya haya sido pusheado porque otra persona ya haya realizado commits que les hagan referencia.
```sh
(main)$ git rebase -i @{u}
```
Esto hará una base de datos interactiva que enumera solo los commits que aún no has enviado, por lo que será seguro reordenar / arreglar / aplastar cualquier elemento de la lista.
#### Necesito abortar el merge
A veces, la fusión puede producir problemas en ciertos archivos, en esos casos podemos usar la opción `abort` para abortar el proceso actual de resolución de conflictos, y tratar de reconstruir el estado previo a la fusión.
```sh
(my-branch)$ git merge --abort
```
Este comando está disponible desde la versión de Git> = 1.7.4
### Comprobar si se combinan todos los commits de un branch
Para comprobar si todos los commits de una rama se fusionan en otra, debe distinguir las cabeceras (o los commits) de esas ramas:
```sh
(main)$ git log --graph --left-right --cherry-pick --oneline HEAD...feature/120-on-scroll
```
Esto te dirá si hay commits en una pero no en la otra, y te dará una lista de las no compartidas entre las ramas. Otra opción es hacer esto:
```sh
(main)$ git log main ^feature/120-on-scroll --no-merges
```
### Posibles problemas con rebase interactivos
#### La pantalla de edición de rebase dice 'noop'
Si estás viendo esto:
```
noop
```
Eso significa que estás tratando de volver a establecer una base contra una rama que está en un commit idéntico, o está *delante* de tu rama actual. Puedes probar:
* asegurándote de que tu rama principal esté donde debería estar
* rebase contra `HEAD ~ 2` o anterior a su lugar
#### Hubo conflictos
Si no puedes completar correctamente el rebase, es posible que tengas que resolver conflictos.
Primero ejecuta `git status` para ver qué archivos tienen conflictos en ellos:
```sh
(my-branch)$ git status
On branch my-branch
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
both modified: README.md
```
En este ejemplo, `README.md` tiene conflictos. Abre ese archivo y busca lo siguiente:
```vim
<<<<<<< HEAD
some code
=========
some code
>>>>>>> new-commit
```
Tendrás que resolver las diferencias entre el código que se agregó en tu nuevo commit (en el ejemplo, todo desde la línea media hasta `new-commit ') y tu' HEAD '.
Si deseas conservar la versión del código de una rama, puedes usar `--us` o` --theirs`:
```sh
(main*)$ git checkout --ours README.md
```
- 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#Documentation/git-rebase.txt---merge).
Si las fusiones son más complicadas, puede usar un editor visual diff:
```sh
(main*)$ git mergetool -t opendiff
```
Después de haber resuelto todos los conflictos y probado el código, `git add` los archivos que has cambiado, y luego continúa el rebase con` git rebase --continue`
```sh
(my-branch)$ git add README.md
(my-branch)$ git rebase --continue
```
Si después de resolver todos los conflictos terminas con un árbol idéntico a lo que era antes del commit, necesitas `git rebase --skip` en su lugar.
Si en algún momento deseas detener todo el rebase y volver al estado original de tu rama, puedes hacer:
```sh
(my-branch)$ git rebase --abort
```
## Stash
### Usar stash en todos los cambios
Para esconder todas las ediciones de tu directorio de trabajo
```sh
$ git stash
```
Si también quiere esconder archivos sin seguimiento, use la opción `-u`.
```sh
$ git stash -u
```
### Usar stash para archivos específicos
Para esconder solo un archivo de tu directorio de trabajo
```sh
$ git stash push working-directory-path/filename.ext
```
Para esconder varios archivos de tu directorio de trabajo
```sh
$ git stash push working-directory-path/filename1.ext working-directory-path/filename2.ext
```
### Usar stash con un mensaje
```sh
$ git stash save <message>
```
### Aplicar un stash específico de la lista
Primero revisa la lista de stash con mensaje usando
```sh
$ git stash list
```
Luego selecciona un stash específico de la lista usando
```sh
$ git stash apply "stash@{n}"
```
Aquí, 'n' indica la posición del stash en la pila. El stash más alto será la posición 0.
## Búsqueda
### Quiero encontra un string en algún commit
Para encontrar un determinada string que se introdujo en cualquier commit, puedes usar la siguiente estructura:
```sh
$ git log -S "string to find"
```
Parámetros comunes:
* `--source` significa mostrar el nombre de la referencia dada en la línea de comando por la cual se llegó a cada commit.
* `--all` significa comenzar desde cada rama.
* `--reverse` imprime en orden inverso, significa que mostrará el primer commit que realizó el cambio.
### Quiero buscar por autor / committer
Para encontrar todos los commits por autor / committer, puedes usar:
```sh
$ git log --author=<name or email>
$ git log --committer=<name or email>
```
Ten en cuenta que autor y committer no son lo mismo. El `--autor` es la persona que originalmente escribió el código; por otro lado, el `--committer` es la persona que subió el código en nombre del autor original.
### Quiero enumerar commits que contienen archivos específicos
Para encontrar todos los commits que contienen un archivo específico, puedes usar:
```sh
$ git log -- <path to file>
```
Por lo general, debes especificar una ruta exacta, pero también puede usar comodines en la ruta y el nombre del archivo:
```sh
$ git log -- **/*.js
```
Al usar comodines, es útil informar `--name-status` para ver la lista de archivos comprometidos:
```sh
$ git log --name-status -- **/*.js
```
### Encontrar una etiqueta donde se hace referencia a un commit
Para encontrar todas las etiquetas que contienen un commit específico:
```sh
$ git tag --contains <commitid>
```
## Submódulos
### Clonar todos los submódulos
```sh
$ git clone --recursive git://github.com/foo/bar.git
```
Si ya fue clonado
```sh
$ git submodule update --init --recursive
```
### Remover un submódulo
Crear un submódulo es bastante simple, pero eliminarlos no. Los comandos que necesitas son:
```sh
$ git submodule deinit submodulename
$ git rm submodulename
$ git rm --cached submodulename
$ rm -rf .git/modules/submodulename
```
## Objetos diversos
### Restaurar un archivo eliminado
Primero encuentra el commit donde el archivo existió por última vez:
```sh
$ git rev-list -n 1 HEAD -- filename
```
Luego hazle checkout a ese archivo
```
git checkout deletingcommitid^ -- filename
```
### Eliminar una etiqueta
```sh
$ git tag -d <tag_name>
$ git push <remote> :refs/tags/<tag_name>
```
### Recuperar una etiqueta eliminada
Si deseas recuperar una etiqueta que ya fue eliminada, puede hacerlo siguiendo estos pasos: Primero, debe encontrar la etiqueta inalcanzable:
```sh
$ git fsck --unreachable | grep tag
```
Toma nota del hash de la etiqueta. Luego, restaura la etiqueta eliminada con la siguiente, haciendo uso de [`git update-ref`] (https://git-scm.com/docs/git-update-ref):
```sh
$ git update-ref refs/tags/<tag_name> <hash>
```
Tu etiqueta ahora debería haber sido restaurada.
### Patch eliminado
Si alguien envió un pull request en GitHub, pero luego eliminó el fork original, no podrá clonar su repositorio ni usar `git am` como [.diff, .patch] (https://github.com / blog / 967-github-secrets) las URL no están disponibles. Pero puedes verificar el PR utilizando las [referencias especiales de GitHub] (https://gist.github.com/piscisaureus/3342247). Para recuperar el contenido de PR # 1 en una nueva rama llamada pr_1:
```sh
$ git fetch origin refs/pull/1/head:pr_1
From github.com:foo/bar
* [new ref] refs/pull/1/head -> pr_1
```
### Exportar un repositorio como un archivo Zip
```sh
$ git archive --format zip --output /full/path/to/zipfile.zip main
```
## Seguimiento de archivos
### Quiero cambiar el uso de mayúsculas de un nombre de archivo, sin cambiar el contenido del archivo
```sh
(main)$ git mv --force myfile MyFile
```
### Quiero sobrescribir los archivos locales cuando hago un git pull
```sh
(main)$ git fetch --all
(main)$ git reset --hard origin/main
```
### Quiero eliminar un archivo de Git pero mantener el archivo
```sh
(main)$ git rm --cached log.txt
```
### Quiero revertir un archivo a una revisión específica
Suponiendo que el hash del commit que deseas es c5f567:
```sh
(main)$ git checkout c5f567 -- file1/to/restore file2/to/restore
```
Si desea volver a los cambios realizados solo 1 commit antes de c5f567, pase el hash de confirmación como c5f567 ~ 1:
```sh
(main)$ git checkout c5f567~1 -- file1/to/restore file2/to/restore
```
## Configuración
### Quiero agregar alias para algunos comandos de Git
En OS X y Linux, tu archivo de configuración de git se almacena en ```~ / .gitconfig```. He agregado algunos alias de ejemplo que uso como accesos directos (y algunos de mis errores comunes) en la sección `` `[alias]` `` como se muestra a continuación:
```vim
[alias]
a = add
amend = commit --amend
c = commit
ca = commit --amend
ci = commit -a
co = checkout
d = diff
dc = diff --changed
ds = diff --staged
f = fetch
loll = log --graph --decorate --pretty=oneline --abbrev-commit
m = merge
one = log --pretty=oneline
outstanding = rebase -i @{u}
s = status
unpushed = log @{u}
wc = whatchanged
wip = rebase -i @{u}
zap = fetch -p
```
### Quiero agregar un directorio vacío a mi repositorio
¡No puedes! Git no es compatible con esto, pero hay un truco. Puede crear un archivo .gitignore en el directorio con los siguientes contenidos:
```
# Ignore everything in this directory
*
# Except this file
!.gitignore
```
Otra convención común es crear un archivo vacío en la carpeta, titulado .gitkeep.
```sh
$ mkdir mydir
$ touch mydir/.gitkeep
```
También puedes nombrar el archivo como .keep, en cuyo caso la segunda línea de arriba sería ```touch mydir / .keep```
### Quiero guardar en caché un nombre de usuario y contraseña para un repositorio
Es posible que tengas un repositorio que requiera autenticación. En ese caso, puedes guardar en caché un nombre de usuario y contraseña para que no tenga que ingresarlos en cada push / pull. Credential helper puede hacer esto por ti.
```sh
$ git config --global credential.helper cache
# Set git to use the credential memory cache
```
```sh
$ git config --global credential.helper 'cache --timeout=3600'
# Set the cache to timeout after 1 hour (setting is in seconds)
```
### Quiero hacer que Git ignore los permisos y cambios en el modo de archivo
```sh
$ git config core.fileMode false
```
Si deseas que este sea el comportamiento predeterminado para los usuarios que han iniciado sesión, utilice:
```sh
$ git config --global core.fileMode false
```
## No tengo idea de lo que hice mal
Entonces, estás jodido, "reiniciaste" algo, o fusionaste la rama incorrecta, o forzaste empujar y ahora no puedes encontrar tus commits. Sabes, en algún momento, estabas bien y quieres volver a un estado en el que estabas.
Para esto está hecho `git reflog`. `reflog` realiza un seguimiento de los cambios en la punta de una rama, incluso si esa sugerencia no está referenciada por una rama o una etiqueta. Básicamente, cada vez que HEAD cambia, se agrega una nueva entrada al reflog. Esto solo funciona para los repositorios locales, lamentablemente, y solo rastrea los movimientos (no los cambios a un archivo que no fueron grabados en ninguna parte, por ejemplo).
```sh
(main)$ git reflog
0a2e358 HEAD@{0}: reset: moving to HEAD~2
0254ea7 HEAD@{1}: checkout: moving from 2.2 to main
c10f740 HEAD@{2}: checkout: moving from main to 2.2
```
El reflog anterior muestra una salida desde main a la rama 2.2 y viceversa. A partir de ahí, hay un restablecimiento completo de un commit más antiguo. La última actividad se representa en la parte superior con la etiqueta 'HEAD @ {0} `.
Si resulta que retrocedió accidentalmente, el reflog contendrá el main de un commit apuntado a (0254ea7) antes de que accidentalmente soltara 2 commits.
```sh
$ git reset --hard 0254ea7
```
Usando `git reset` es posible cambiar el main al commit que era antes. Esto proporciona una red de seguridad en caso de que la historia se haya cambiado accidentalmente.
(copiado y editado desde [Fuente] (https://www.atlassian.com/git/tutorials/rewriting-history/git-reflog)).
# Otros recursos
## Libros
* [Pro Git](https://git-scm.com/book/en/v2) - Excelente libro de Scott Chacon y Ben Straub sobre Git
* [Git Internals](https://github.com/pluralsight/git-internals-pdf) - Otro excelente libro de Scott Chacon sobre Git
## Tutoriales
* [Tutorial de Git de Atlassian](https://www.atlassian.com/git/tutorials) Obtenga Git a la derecha con tutoriales de principiante a avanzado.
* [Aprende la ramificación de Git](https://learngitbranching.js.org/) Tutorial interactivo de ramificación / fusión / rebase basado en la web
* [Obteniendo solidez en Git rebase vs. merge](https://medium.com/@porteneuve/getting-solid-at-git-rebase-vs-merge-4fa1a48c53aa)
* [git-workflow](https://github.com/asmeurer/git-workflow) - [Aaron Meurer](https://github.com/asmeurer) 'Howto sobre el uso de Git para contribuir a repositorios de código abierto
* [GitHub como flujo de trabajo](https://hugogiraudel.com/2015/08/13/github-as-a-workflow/) - Una interesante idea sobre el uso de GitHub como flujo de trabajo, particularmente con los PR vacíos
* [Githug](https://github.com/Gazler/githug) - Un juego para aprender más flujos de trabajo de Git
## Scripts y herramientas
* [firstaidgit.io](http://firstaidgit.io/) Una selección de búsqueda de las preguntas más frecuentes de Git
* [git-extra-commands](https://github.com/unixorn/git-extra-commands) - una colección de scripts extra útiles de Git
* [git-extras](https://github.com/tj/git-extras) - Utilidades de GIT - resumen de repo, repl, población de registro de cambios, porcentajes de confirmación de autor y más
* [git-fire](https://github.com/qw3rtman/git-fire) - git-fire es un plugin de Git que ayuda en caso de una emergencia al agregar todos los archivos actuales, comprometerse y empujar a un nuevo rama (para evitar conflictos de combinación).
* [git-tips](https://github.com/git-tips/tips) - Consejos pequeños de Git
* [git-town](https://github.com/Originate/git-town) - Soporte genérico de alto nivel de flujo de trabajo de Git! http://www.git-town.com
## Clientes GUI
* [GitKraken](https://www.gitkraken.com/) - El cliente francamente lujoso de Git, para Windows, Mac y Linux
* [git-cola](https://git-cola.github.io/) - otro cliente de Git para Windows y OS X
* [GitUp](https://github.com/git-up/GitUp) - Una interfaz gráfica de usuario nueva que tiene algunas formas muy dogmáticas de lidiar con las complicaciones de Git
* [gitx-dev](https://rowanj.github.io/gitx/) - otro cliente gráfico de Git para OS X
* [Sourcetree](https://www.sourcetreeapp.com/) - Simplicity se une a la potencia en una hermosa y gratuita GUI de Git. Para Windows y Mac.
* [Tower](https://www.git-tower.com/) - cliente gráfico de Git para OS X (pago)
* [tig](https://jonas.github.io/tig/) - interfaz de texto en modo terminal para Git
* [Magit](https://magit.vc/) - Interfaz para Git implementada como un paquete de Emacs.
* [GitExtensions](https://github.com/gitextensions/gitextensions): una extensión de shell, un plugin de Visual Studio 2010-2015 y una herramienta de repositorio de Git independiente.
* [Fork](https://git-fork.com/) - un cliente de Git rápido y amigable para Mac (beta)
* [gmaster](https://gmaster.io/) - un cliente de Git para Windows que tiene combinación de 3 vías, analizan refactores, diferencias semánticas y fusión (beta)
* [gitk](https://git-scm.com/docs/gitk) - un cliente de Git para Linux para permitir una vista simple del estado de repos.
================================================
FILE: README_fr.md
================================================
# Règles de vol pour Git
🌍
*[English](README.md) ∙ [Español](README_es.md) ∙ [Русский](README_ru.md) ∙ [繁體中文](README_zh-TW.md) ∙ [简体中文](README_zh-CN.md) ∙ [한국어](README_kr.md) ∙ [Tiếng Việt](README_vi.md) ∙ [Français](README_fr.md) ∙ [日本語](README_ja.md)*
#### C'est quoi des "règles de vol" ?
Un guide pour les astronautes (pour les développeur·euse·s utilisant Git, dans le cas présent) sur quoi faire quand les choses se passent mal.
> *Les règles de vol* représentent l'ensemble des connaissances durement acquises consignées dans des manuels répertoriant, étape par étape, la procédure à suivre si telle chose se produit et pourquoi. Il s'agit essentiellement de procédures d'exploitation standard extrêmement détaillées et spécifiques à chaque scénario. [...]
> La NASA a recueilli nos faux pas, nos désastres et nos solutions depuis le début des années 60, lorsque les équipes terrestres de l'ère Mercury ont commencé à rassembler les "leçons tirées" dans un recueil qui répertorie désormais des milliers de situations problématiques, des pannes de moteur aux poignées de trappes cassées en passant par les bugs informatiques, et leurs solutions.
— Chris Hadfield, *Guide d'un astronaute pour la vie sur Terre*.
#### Conventions pour ce document
Pour des raisons de clarté tous les exemples dans ce document utilisent une invite de commande bash personnalisée dans le but d'indiquer la branche actuelle et s'il y a des modifications indexées ou non. La branche se trouve entre parenthèses, et un `*` après le nom de la branche indique des modifications indexées.
Toutes les commandes devraient fonctionner pour les versions de Git au moins supérieures à la 2.13.0. Visitez le [site de Git](https://www.git-scm.com/) pour mettre à jour votre version de git locale.
[](https://gitter.im/k88hudson/git-flight-rules?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
**Table of Contents** *generated with [DocToc](https://github.com/thlorenz/doctoc)*
- [Dépôts](#d%C3%A9p%C3%B4ts)
- [Je veux initialiser un dépôt local](#je-veux-initialiser-un-d%C3%A9p%C3%B4t-local)
- [Je veux cloner un dépôt distant](#je-veux-cloner-un-d%C3%A9p%C3%B4t-distant)
- [Éditer des Commits](#%C3%89diter-des-commits)
- [Qu'est-ce que je viens de commiter ?](#quest-ce-que-je-viens-de-commiter-)
- [J'ai commis une erreur dans un message de commit](#jai-commis-une-erreur-dans-un-message-de-commit)
- [J'ai commit avec le mauvais nom et email dans les configurations](#jai-commit-avec-le-mauvais-nom-et-email-dans-les-configurations)
- [Je veux retirer un fichier du commit précédent](#je-veux-retirer-un-fichier-du-commit-pr%C3%A9c%C3%A9dent)
- [Je veux supprimer ou retirer mon dernier commit](#je-veux-supprimer-ou-retirer-mon-dernier-commit)
- [Supprimer/retirer un commit arbitraire](#supprimerretirer-un-commit-arbitraire)
- [J'ai essayé de pousser un commit modifié vers le dépôt distant, mais j'ai eu un message d'erreur](#jai-essay%C3%A9-de-pousser-un-commit-modifi%C3%A9-vers-le-d%C3%A9p%C3%B4t-distant-mais-jai-eu-un-message-derreur)
- [J'ai fait un hard reset par accident, et je veux retrouver mes changements](#jai-fait-un-hard-reset-par-accident-et-je-veux-retrouver-mes-changements)
- [J'ai commité et poussé une fusion par accident](#jai-commit%C3%A9-et-pouss%C3%A9-une-fusion-par-accident)
- [J'ai commité et poussé des fichiers contenant des données sensibles par accident](#jai-commit%C3%A9-et-pouss%C3%A9-des-fichiers-contenant-des-donn%C3%A9es-sensibles-par-accident)
- [Indexation](#indexation)
- [J'ai besoin d'ajouter des modifications indexées sur le commit précédent](#jai-besoin-dajouter-des-modifications-index%C3%A9es-sur-le-commit-pr%C3%A9c%C3%A9dent)
- [Je veux indexer une partie d'un fichier, mais pas tout le fichier](#je-veux-indexer-une-partie-dun-fichier-mais-pas-tout-le-fichier)
- [Je veux ajouter les changements d'un fichier dans deux commits différents](#je-veux-ajouter-les-changements-dun-fichier-dans-deux-commits-diff%C3%A9rents)
- [Je veux indexer mes modifications indexées, et désindexer mes modifications indexées](#je-veux-indexer-mes-modifications-index%C3%A9es-et-d%C3%A9sindexer-mes-modifications-index%C3%A9es)
- [Modifications non indexées](#modifications-non-index%C3%A9es)
- [Je veux déplacer mes modifications non indexées vers une nouvelle branche](#je-veux-d%C3%A9placer-mes-modifications-non-index%C3%A9es-vers-une-nouvelle-branche)
- [Je veux déplacer mes modifications non indexées vers une branche différente existante](#je-veux-d%C3%A9placer-mes-modifications-non-index%C3%A9es-vers-une-branche-diff%C3%A9rente-existante)
- [Je veux me débarrasser de mes modifications locales non commitées (indexées et non-indexées)](#je-veux-me-d%C3%A9barrasser-de-mes-modifications-locales-non-commit%C3%A9es-index%C3%A9es-et-non-index%C3%A9es)
- [Je veux me débarrasser de modifications non-indexées spécifiques](#je-veux-me-d%C3%A9barrasser-de-modifications-non-index%C3%A9es-sp%C3%A9cifiques)
- [Je veux me débarrasser de fichiers non-indexés spécifiques](#je-veux-me-d%C3%A9barrasser-de-fichiers-non-index%C3%A9s-sp%C3%A9cifiques)
- [Je veux me débarrasser de mes modifications locales non-indexées uniquement](#je-veux-me-d%C3%A9barrasser-de-mes-modifications-locales-non-index%C3%A9es-uniquement)
- [Je veux me débarrasser de tous mes fichiers non suivis](#je-veux-me-d%C3%A9barrasser-de-tous-mes-fichiers-non-suivis)
- [Je veux désindexer un fichier indexé spécifique](#je-veux-d%C3%A9sindexer-un-fichier-index%C3%A9-sp%C3%A9cifique)
- [Branches](#branches)
- [Je veux lister toutes les branches](#je-veux-lister-toutes-les-branches)
- [Créer une branche à partir d'un commit](#cr%C3%A9er-une-branche-%C3%A0-partir-dun-commit)
- [J'ai pull depuis/vers la mauvaise branche](#jai-pull-depuisvers-la-mauvaise-branche)
- [Je veux supprimer mes commits locaux afin que ma branche soit pareille à celle sur le serveur](#je-veux-supprimer-mes-commits-locaux-afin-que-ma-branche-soit-pareille-%C3%A0-celle-sur-le-serveur)
- [J'ai commité sur main au lieu d'une nouvelle branche](#jai-commit%C3%A9-sur-main-au-lieu-dune-nouvelle-branche)
- [Je veux séparer tout un fichier d'un autre ref-ish](#je-veux-s%C3%A9parer-tout-un-fichier-dun-autre-ref-ish)
- [J'ai fait plusieurs commits sur une même branche qui auraient dû être sur plusieurs branches](#jai-fait-plusieurs-commits-sur-une-m%C3%AAme-branche-qui-auraient-d%C3%BB-%C3%AAtre-sur-plusieurs-branches)
- [Je veux supprimer mes branches locales qui ont été supprimée sur le dépôt distant](#je-veux-supprimer-mes-branches-locales-qui-ont-%C3%A9t%C3%A9-supprim%C3%A9e-sur-le-d%C3%A9p%C3%B4t-distant)
- [J'ai supprimé ma branche par accident](#jai-supprim%C3%A9-ma-branche-par-accident)
- [Je veux supprimer une branche](#je-veux-supprimer-une-branche)
- [Je veux supprimer plusieurs branches](#je-veux-supprimer-plusieurs-branches)
- [Je veux renommer une branche](#je-veux-renommer-une-branche)
- [Je veux me déplacer sur une branche distante sur laquelle quelqu'un est en train de travailler](#je-veux-me-d%C3%A9placer-sur-une-branche-distante-sur-laquelle-quelquun-est-en-train-de-travailler)
- [Je veux créer une nouvelle branche distante à partir de celle en locale](#je-veux-cr%C3%A9er-une-nouvelle-branche-distante-%C3%A0-partir-de-celle-en-locale)
- [Je veux configurer une branche distante en tant qu'upstream pour une branche locale](#je-veux-configurer-une-branche-distante-en-tant-quupstream-pour-une-branche-locale)
- [Je veux configurer mon HEAD pour suivre la branche distante par défaut](#je-veux-configurer-mon-head-pour-suivre-la-branche-distante-par-d%C3%A9faut)
- [J'ai fait des modifications sur la mauvaise branche](#jai-fait-des-modifications-sur-la-mauvaise-branche)
- [Rebaser et fusionner](#rebaser-et-fusionner)
- [Je veux annuler un rebase/merge](#je-veux-annuler-un-rebasemerge)
- [J'ai rebase, mais je ne veux pas pousser de force](#jai-rebase-mais-je-ne-veux-pas-pousser-de-force)
- [J'ai besoin de combiner des commits](#jai-besoin-de-combiner-des-commits)
- [Stratégie de fusion sûre](#strat%C3%A9gie-de-fusion-s%C3%BBre)
- [J'ai besoin de fusionner deux branches en un seul commit](#jai-besoin-de-fusionner-deux-branches-en-un-seul-commit)
- [Je veux combiner les commits non poussés uniquement](#je-veux-combiner-les-commits-non-pouss%C3%A9s-uniquement)
- [J'ai besoin d'annuler la fusion](#jai-besoin-dannuler-la-fusion)
- [J'ai besoin de mettre à jour le commit parent de ma branche](#jai-besoin-de-mettre-%C3%A0-jour-le-commit-parent-de-ma-branche)
- [Vérifier si tous les commits d'une branche sont fusionnés](#v%C3%A9rifier-si-tous-les-commits-dune-branche-sont-fusionn%C3%A9s)
- [Problèmes possibles avec les rebase interactifs](#probl%C3%A8mes-possibles-avec-les-rebase-interactifs)
- [L'écran d'édition du rebase affiche 'noop'](#l%C3%A9cran-d%C3%A9dition-du-rebase-affiche-noop)
- [Il y a eu des conflits](#il-y-a-eu-des-conflits)
- [Remisage](#remisage)
- [Remiser toutes les modifications](#remiser-toutes-les-modifications)
- [Remiser des fichiers spécifiques](#remiser-des-fichiers-sp%C3%A9cifiques)
- [Remiser avec un message](#remiser-avec-un-message)
- [Appliquer un remisage spécifique de la liste](#appliquer-un-remisage-sp%C3%A9cifique-de-la-liste)
- [Rechercher](#rechercher)
- [Je veux rechercher une chaîne de caractères dans un commit](#je-veux-rechercher-une-cha%C3%AEne-de-caract%C3%A8res-dans-un-commit)
- [Je veux rechercher par auteur·trice/validateur·trice](#je-veux-rechercher-par-auteur%C2%B7tricevalidateur%C2%B7trice)
- [Je veux lister les commits ayant des fichiers spécifiques](#je-veux-lister-les-commits-ayant-des-fichiers-sp%C3%A9cifiques)
- [Trouver un tag où un commit est référencé](#trouver-un-tag-o%C3%B9-un-commit-est-r%C3%A9f%C3%A9renc%C3%A9)
- [Sous-modules](#sous-modules)
- [Cloner tous les sous-modules](#cloner-tous-les-sous-modules)
- [Retirer un sous-module](#retirer-un-sous-module)
- [Objets divers](#objets-divers)
- [Récupérer un fichier supprimé](#r%C3%A9cup%C3%A9rer-un-fichier-supprim%C3%A9)
- [Supprimer un tag](#supprimer-un-tag)
- [Récupérer un tag supprimé](#r%C3%A9cup%C3%A9rer-un-tag-supprim%C3%A9)
- [Patch supprimé](#patch-supprim%C3%A9)
- [Exporter un dépôt comme fichier Zip](#exporter-un-d%C3%A9p%C3%B4t-comme-fichier-zip)
- [Pousser une branche et un tag qui ont le même nom](#pousser-une-branche-et-un-tag-qui-ont-le-m%C3%AAme-nom)
- [Suivre des fichiers](#suivre-des-fichiers)
- [Je veux changer la capitalisation du nom d'un fichier, sans changer son contenu](#je-veux-changer-la-capitalisation-du-nom-dun-fichier-sans-changer-son-contenu)
- [Je veux écraser des fichiers locaux en faisant un git pull](#je-veux-%C3%A9craser-des-fichiers-locaux-en-faisant-un-git-pull)
- [Je veux retirer un fichier de Git mais garder le fichier](#je-veux-retirer-un-fichier-de-git-mais-garder-le-fichier)
- [Je veux rétablir un fichier à une version spécifique](#je-veux-r%C3%A9tablir-un-fichier-%C3%A0-une-version-sp%C3%A9cifique)
- [Je veux lister les changements d'un fichier spécifique entre deux commits ou branches](#je-veux-lister-les-changements-dun-fichier-sp%C3%A9cifique-entre-deux-commits-ou-branches)
- [Je veux que Git ignore les changements d'un fichier spécifique](#je-veux-que-git-ignore-les-changements-dun-fichier-sp%C3%A9cifique)
- [Paramétrage](#param%C3%A9trage)
- [Je veux ajouter des alias pour certaines commandes Git](#je-veux-ajouter-des-alias-pour-certaines-commandes-git)
- [Je veux ajouter un répertoire vide à mon dépôt](#je-veux-ajouter-un-r%C3%A9pertoire-vide-%C3%A0-mon-d%C3%A9p%C3%B4t)
- [Je veux mettre en cache un nom d'utilisateur et mot de passe pour un dépôt](#je-veux-mettre-en-cache-un-nom-dutilisateur-et-mot-de-passe-pour-un-d%C3%A9p%C3%B4t)
- [Je veux que Git ignore les changements de permissions et de filemode](#je-veux-que-git-ignore-les-changements-de-permissions-et-de-filemode)
- [Je veux définir un utilisateur global](#je-veux-d%C3%A9finir-un-utilisateur-global)
- [Je n'ai aucune idée de ce que j'ai mal fait](#je-nai-aucune-id%C3%A9e-de-ce-que-jai-mal-fait)
- [Autres Ressources](#autres-ressources)
- [Livres](#livres)
- [Tutoriels](#tutoriels)
- [Scripts et Outils](#scripts-et-outils)
- [Clients graphiques](#clients-graphiques)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Dépôts
### Je veux initialiser un dépôt local
Pour initialiser un répertoire existant comme dépôt Git :
```sh
(mon-dossier) $ git init
```
### Je veux cloner un dépôt distant
Pour cloner (copier) un dépôt distant, copiez l'url de ce dernier, et lancez :
```sh
$ git clone [url]
```
Ceci le sauvegardera dans un dossier nommé d'après le nom du dépôt. Assurez-vous d'avoir une connexion avec le serveur distant que vous essayez de cloner (dans la plupart des cas ceci revient à s'assurer d'être connecté·e à Internet).
Pour le cloner vers un dossier ayant un nom différent de celui du dépôt distant :
```sh
$ git clone [url] nom-du-nouveau-dossier
```
## Éditer des Commits
<a name="diff-last"></a>
### Qu'est-ce que je viens de commiter ?
Imaginons que vous venez tout juste d'enregistrer des changements à l'aveugle avec {code0}git commit -a{/code0} et que vous n'êtes pas sûr·e du contenu réel du commit que vous venez d'effectuer. Vous pouvez visualiser le dernier commit sur votre HEAD actuel avec :
```sh
(main)$ git show
```
Ou :
```sh
$ git log -n1 -p
```
Si vous voulez voir un fichier à un commit spécifique, vous pouvez aussi faire (où `<commitid>` est le commit qui vous intéresse).
```sh
$ git show <commitid>:nomdufichier
```
<a name="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 :
```sh
$ git commit --amend --only
```
Cela ouvrira votre éditeur de texte par défaut, où vous pourrez éditer le message. Vous pouvez également effectuer la même chose en une seule commande :
```sh
$ git commit --amend --only -m 'xxxxxxx'
```
Si vous avez déjà poussé le message, vous pouvez modifier le commit et pousser de force, mais cela n'est pas recommandé.
<a name="commit-wrong-author"></a>
### J'ai commit avec le mauvais nom et email dans les configurations
Si c'est un commit unique, modifiez-le :
```sh
$ git commit --amend --no-edit --author "Nouvel Auteur·trice <emaildelauteurice@mondomaine.com>"
```
Une alternative est de configurer correctement vos paramètres d'auteur·trice avec `git config --global author.(name|email)` puis de lancer :
```sh
$ git commit --amend --reset-author --no-edit
```
Si vous avez besoin de changer tout l'historique, veuillez vous référer à la page man pour `git filter-branch`.
### Je veux retirer un fichier du commit précédent
Pour retirer les changements effectués sur un fichier lors du précédent commit, faites la chose suivante :
```sh
$ git checkout HEAD^ monfichier
$ git add monfichier
$ git commit --amend --no-edit
```
Dans le cas où le fichier fut introduit dans le commit et que vous voulez le retirer (de Git seul), faites :
```sh
$ git rm --cached monfichier
$ git commit --amend --no-edit
```
Cela est particulièrement utile quand vous avez un patch d'ouvert et que vous avez commité un fichier non nécessaire, et que vous avez besoin de pousser de force pour mettre à jour le patch sur le dépôt distant. L'option `--no-edit` est utilisée pour garder le message de commit existant.
<a name="delete-pushed-commit"></a>
### Je veux supprimer ou retirer mon dernier commit
Si vous avez besoin de supprimer des commits poussés, vous pouvez utiliser la commande suivante. Cependant, cela modifiera votre historique de manière irreversible, et mettra la pagaille dans l'historique de quiconque ayant déjà récupéré des changements depuis le dépôt distant. Pour faire court, si vous n'êtes pas sûr·e, vous ne devriez pas faire ça, jamais.
```sh
$ git reset HEAD^ --hard
$ git push --force-with-lease [remote] [branche]
```
Si vous n'avez pas poussé, pour réinitialiser Git vers l'état dans lequel il était avant que vous ne fassiez votre dernier commit (tout en gardant vos changements) :
```
(ma-branche)$ git reset --soft HEAD^
```
Cela ne marchera que si vous n'avez pas poussé. Si vous avez poussé, la seule vraie chose sécurisée à faire est `git revert SHAduMauvaisCommit`. Cela créera un nouveau commit qui annule tous les changements du commit en question. Ou, si la branche vers laquelle vous avez poussé est "rebase-safe" (en d'autres termes, les autres développeur·euse·s ne la récupéreront pas), vous pouvez juste lancer `git push --force-with-lease`. Pour plus d'informations, jetez un œil [à la section ci-dessus](#je-veux-supprimer-ou-retirer-mon-dernier-commit).
<a name="delete-any-commit"></a>
### Supprimer/retirer un commit arbitraire
Le même avertissement que ci-dessus s'applique. Ne faites jamais cela si possible.
```sh
$ git rebase --onto SHA1_DU_MAUVAIS_COMMIT^ SHA1_DU_MAUVAIS_COMMIT
$ git push --force-with-lease [remote] [branche]
```
Ou faites un [rebase interactif](#interactive-rebase) et retirez les lignes correspondantes au(x) commit(s) que vous souhaitez supprimer.
<a name="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
To https://github.com/votrenomdutilisateur/repo.git
! [rejected] ma-branche -> ma-branche (non-fast-forward)
error: failed to push some refs to 'https://github.com/tanay1337/webmaker.org.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
```
Notez que, tout comme avec un rebase (voir ci-dessous), le fait de modifier **remplace l'ancien commit avec un nouveau**, donc vous devez pousser de force (`--force-with-lease`) vos changements si vous avez déjà poussé le commit vers votre dépôt distant avant sa modification. Soyez prudent·e quand vous faites cela : Assurez vous de *toujours* spécifier une branche !
```sh
(ma-branche)$ git push origin ma-branche --force-with-lease
```
En règle générale, **évitez de pousser de force**. Il est préférable de créer et pousser un nouveau commit plutôt que de pousser de force un commit modifié car cela causera des conflits dans l'historique pour n'importe quel développeur·euse ayant déjà intéragit avec la branche en question ou quelque branche fille. `--force-with-lease` échouera toujours, si quelqu'un d'autre était déjà en train de travailler sur la même branche que vous et que votre push réécrirait par-dessus ces modifications.
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.
<a name="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.
À noter : Cela n'est valide que si votre travail est sauvegardé, c'est à dire dans un commit ou un remisage. `git reset --hard` *supprimera* les modifications non commitées, donc utilisez cela avec précaution (une option plus sûre est `git reset --keep`).
```sh
(main)$ git reflog
```
Vous verrez une liste de vos précédents commits, et un commit pour la réinitialisation. Choisissez le SHA du commit vers lequel vous souhaitez retourner, et réinitialisez à nouveau :
```sh
(main)$ git reset --hard SHA1234
```
Et cela devrait faire l'affaire.
<a name="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).
Utilisez cette commande :
```sh
(feature-branch)$ git revert -m 1 <commit>
```
où l'option `-m 1` demande de sélectionner le parent numéro 1 (la branche vers laquelle la fusion a été faite) comme parent vers lequel annuler la fusion.
À 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.
<a name="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.
Si vous souhaitez modifier le fichier et supprimer les données sensibles, lancez :
```sh
(feature-branch)$ git add fichier_modifié
(feature-branch)$ git commit --amend --no-edit
(feature-branch)$ git push --force-with-lease origin [branche]
```
Si vous souhaitez supprimer tout un fichier (mais le garder en local), lancez :
```sh
(feature-branch)$ git rm --cached fichier_sensible
echo fichier_sensible >> .gitignore
(feature-branch)$ git add .gitignore
(feature-branch)$ git commit --amend --no-edit
(feature-branch)$ git push --force-with-lease origin [branche]
```
Alternativement, stockez vos données sensibles dans des variables d'environnement locales.
Si vous souhaitez supprimer tout un fichier (et ne pas le garder en local), lancez :
```sh
(feature-branch)$ git rm fichier_sensible
(feature-branch)$ git commit --amend --no-edit
(feature-branch)$ git push --force-with-lease origin [branche]
```
Si vous avez créé d'autres commits pendant ce temps (c'est à dire que les données sensibles sont dans un commit avant le commit précédent), vous devrez utiliser la fonction `rebase`.
## Indexation
<a name="add-staged-changes-to-previous-commit"></a>
### J'ai besoin d'ajouter des modifications indexées sur le commit précédent
```sh
(ma-branche*)$ git commit --amend
```
Si vous savez déjà que vous ne souhaitez pas modifier le message du commit, vous pouvez dire à Git de réutiliser ce dernier :
```sh
(ma-branche*)$ git commit --amend -C HEAD
```
<a name="commit-partial-new-file"></a>
### Je veux indexer une partie d'un fichier, mais pas tout le fichier
Normalement, quand vous souhaitez modifier une partie d'un fichier, il faut lancer ceci :
```sh
$ git add --patch nomdufichier.x
```
`-p` fonctionnera comme raccourci. Cela ouvrira le mode interactif. Vous serez en mesure d'utiliser l'option `s` pour séparer le commit. Cependant, si le fichier est nouveau, vous n'aurez pas cette option. Pour ajouter un nouveau fichier, faites comme ceci :
```sh
$ 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.
<a name="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.
<a name="unstaging-edits-and-staging-the-unstaged"></a>
### 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 :
```sh
$ git stash -k
$ git reset --hard
$ git stash pop
$ git add -A
```
## Modifications non indexées
<a name="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
```
<a name="move-unstaged-edits-to-old-branch"></a>
### Je veux déplacer mes modifications non indexées vers une branche différente existante
```sh
$ git stash
$ git checkout ma-branche
$ git stash pop
```
<a name="discard-local-uncommitted-changes"></a>
### Je veux me débarrasser de mes modifications locales non commitées (indexées et non-indexées)
Si vous voulez vous débarrasser de toutes vos modifications locales indexées et non-indexées, vous pouvez faire ceci :
```sh
(ma-branche)$ git reset --hard
# ou
(main)$ git checkout -f
```
Cette commande désindexera tous les fichiers que vous avez pu indexer avec `git add` :
```sh
$ git reset
```
Cette commande annulera toutes les modifications locales non commitées (elle devrait être exécutée à la racine du dépôt) :
```sh
$ git checkout .
```
Vous pouvez également annuler les changements non commités d'un fichier ou d'un dossier en particulier :
```sh
$ git checkout [un_dossier|fichier.txt]
```
Il existe également une autre façon d'annuler toutes vos modifications non commitées (plus longue à taper, mais fonctionne depuis n'importe quel sous-dossier) :
```sh
$ git reset --hard HEAD
```
Cette commande supprimera tous les fichiers locaux non indexés, afin que seuls les fichiers suivis par Git ne restent :
```sh
$ git clean -fd
```
`-x` supprimera également tous les fichiers ignorés.
### Je veux me débarrasser de modifications non-indexées spécifiques
Quand vous souhaitez vous débarrasser de quelques modifications dans votre copie de travail, mais pas toutes, faites un `checkout` sur les modifications non désirées, et gardez les bonnes :
```sh
$ git checkout -p
# Répondez y à tous les bouts de code que vous souhaitez jeter
```
Une autre stratégie implique d'utiliser `stash`. Remisez toutes les bonnes modifications, réinitialisez votre copie locale, et réappliquez les bonnes modifications :
```sh
$ git stash -p
# Sélectionnez tous les bouts de code que vous souhaitez garder
$ git reset --hard
$ git stash pop
```
Alternativement, remisez vos changements non désirés, puis jetez le stash :
```sh
$ git stash -p
# Sélectionnez tous les bouts de code que vous ne souhaitez pas sauvegarder
$ git stash drop
```
### Je veux me débarrasser de fichiers non-indexés spécifiques
Quand vous souhaitez vous débarrasser d'un fichier en particulier de votre copie de travail :
```sh
$ git checkout monFichier
```
Alternativement, pour vous débarrasser de plusieurs fichiers dans votre copie locale, listez chacun d'entre eux :
```sh
$ git checkout monPremierFichier monDeuxiemeFichier
```
### Je veux me débarrasser de mes modifications locales non-indexées uniquement
Quand vous souhaitez vous débarrasser de toutes vos modifications locales non commitées :
```sh
$ git checkout .
```
<a name="discard-all-untracked-files"></a>
### Je veux me débarrasser de tous mes fichiers non suivis
Quand vous souhaitez vous débarrasser de tous vos fichiers non suivis :
```sh
$ git clean -f
```
<a name="unstage-specific-staged-file"></a>
### 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 :
```sh
$ git reset -- <nomdufichier>
```
Cela entraînera la désindexation du fichier et le remettra à son état non suivi.
## Branches
### Je veux lister toutes les branches
Pour lister les branches locales :
```sh
$ git branch
```
Pour lister les branches distantes :
```sh
$ git branch -r
```
Pour lister toutes les branches (à la fois locales et distantes) :
```sh
$ git branch -a
```
<a name="create-branch-from-commit"></a>
### Créer une branche à partir d'un commit
```sh
$ git checkout -b <branche> <SHA1_DU_COMMIT>
```
<a name="pull-wrong-branch"></a>
### J'ai pull depuis/vers la mauvaise branche
C'est une autre occasion d'utiliser `git reflog` afin de voir où votre HEAD pointait avant le mauvais `pull` :
```sh
(main)$ git reflog
ab7555f HEAD@{0}: pull origin wrong-branch: Fast-forward
c5bc55a HEAD@{1}: checkout: checkout message goes here
```
Réinitialisez simplement votre branche vers le commit désiré :
```sh
$ git reset --hard c5bc55a
```
Et voilà.
<a name="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.
`git status` devrait vous indiquer combien de commits en avance vous êtes par rapport à origin :
```sh
(ma-branche)$ git status
# On branch ma-branche
# Your branch is ahead of 'origin/my-branch' by 2 commits.
# (use "git push" to publish your local commits)
#
```
Une des façons de faire pour réinitialiser votre branche afin qu'elle corresponde à origin (afin d'avoir la même chose que le dépôt distant) est de lancer ceci :
```sh
(ma-branche)$ git reset --hard origin/ma-branche
```
<a name="commit-wrong-branch"></a>
### J'ai commité sur main au lieu d'une nouvelle branche
Créez la nouvelle branche tout en restant sur main :
```sh
(main)$ git branch ma-branche
```
Réinitialisez la branche main vers le commit précédent :
```sh
(main)$ git reset --hard HEAD^
```
`HEAD^` est un raccourci pour `HEAD^1`. Cela indique le premier parent de `HEAD`, de la même façon que `HEAD^2` indique le second parent du commit (des fusions peuvent avoir deux parents).
Notez que `HEAD^2` ne signifie **pas** la même chose que `HEAD~2` (visitez [ce lien](http://www.paulboxley.com/blog/2011/06/git-caret-and-tilde) pour plus d'informations).
Alternativement, si vous ne souhaitez pas utiliser `HEAD^`, retrouvez le hash du commit vers lequel vous souhaitez remettre votre branche main (`git log` devrait faire l'affaire). Puis réinitialisez vers ce hash. `git push` s'assurera que la modification est reflétée sur le serveur distant.
Par exemple, si le hash du commit sur lequel votre branche main est supposée être est `a13b85e` :
```sh
(main)$ git reset --hard a13b85e
HEAD is now at a13b85e
```
Déplacez-vous vers la nouvelle branche pour continuer de travailler :
```sh
(main)$ git checkout ma-branche
```
<a name="keep-whole-file"></a>
### Je veux séparer tout un fichier d'un autre ref-ish
Admettons que vous avez un pic de travail (voir la note), avec des centaines de changements. Tout fonctionne bien. Maintenant, vous commitez vers une autre branche pour sauvegarder ce travail :
```sh
(solution)$ git add -A && git commit -m "Ajout de tous les changements de ce pic vers un gros commit."
```
Quand vous souhaitez mettre tout cela vers une branche (d'une fonctionnalité ou `develop`), ce qui vous intéresse est de garder les fichiers dans leur entièreté. Vous voudriez également séparer votre gros commit en plusieurs petits commits.
Admettons que vous ayez :
* La branche `solution`, avec la solution à votre pic. En avance d'un commit par rapport à `develop`.
* La branche `develop`, où vous souhaitez ajouter vos modifications.
Vous pouvez résoudre cela en ramenant les contenus vers votre branche :
```sh
(develop)$ git checkout solution -- fichier1.txt
```
Cela ramènera le contenu de ce fichier dans la branche `solution` vers votre branche `develop` :
```sh
# On branch develop
# Your branch is up-to-date with 'origin/develop'.
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# modified: fichier1.txt
```
Puis, commitez comme d'habitude.
Note: Les pics de solutions servent à analyser ou résoudre un problème. Ces solutions sont ensuite utilisées afin d'avoir une estimation puis jetées une fois que tout le monde a une vision claire du problème. ~ [Wikipedia](https://en.wikipedia.org/wiki/Extreme_programming_practices).
<a name="cherry-pick"></a>
### J'ai fait plusieurs commits sur une même branche qui auraient dû être sur plusieurs branches
Admettons que vous êtes sur votre branche main. En lançant `git log`, vous remarquez que vous avez fait deux commits :
```sh
(main)$ git log
commit e3851e817c451cc36f2e6f3049db528415e3c114
Author: Alex Lee <alexlee@example.com>
Date: Tue Jul 22 15:39:27 2014 -0400
Bug #21 - Ajout de la protection CSRF
commit 5ea51731d150f7ddc4a365437931cd8be3bf3131
Author: Alex Lee <alexlee@example.com>
Date: Tue Jul 22 15:39:12 2014 -0400
Bug #14 - Correction de l'espacement du titre
commit a13b85e984171c6e2a1729bb061994525f626d14
Author: Aki Rose <akirose@example.com>
Date: Tue Jul 21 01:12:48 2014 -0400
Premier commit
```
Notons dans un coin les hashes des commits pour chaque bug (`e3851e8` pour le #21, `5ea5173` pour le #14).
Pour commencer, réinitialisons notre branche main sur le bon commit (`a13b85e`) :
```sh
(main)$ git reset --hard a13b85e
HEAD is now at a13b85e
```
Maintenant, nous pouvons créer une nouvelle branche pour le bug #21 :
```sh
(main)$ git checkout -b 21
(21)$
```
Maintenant, faisons un `cherry-pick` du commit pour le bug #21 par-dessus notre branche. Cela signifie que nous appliquerons ce commit, et seulement ce commit, directement au-dessus de ce qui se trouve sur notre HEAD :
```sh
(21)$ git cherry-pick e3851e8
```
Lors de cette étape, il est possible qu'il y ait des conflits. Regardez la section [**Il y a eu des conflits**](#merge-conflict) dans la section [faire un rebase interactif](#interactive-rebase) ci-dessus pour savoir comment résoudre ces conflits.
Maintenant, créons une nouvelle branche pour le bug #14, aussi basée sur main :
```sh
(21)$ git checkout main
(main)$ git checkout -b 14
(14)$
```
Et pour finir, faisons un `cherry-pick` du commit pour le bug #14 :
```sh
(14)$ git cherry-pick 5ea5173
```
<a name="delete-stale-local-branches"></a>
### Je veux supprimer mes branches locales qui ont été supprimée sur le dépôt distant
Une fois que vous avez accepté une Pull Request sur GitHub, vous avez l'option de supprimer la branche fusionnée dans votre fork. Si vous ne prévoyez pas de continuer à travailler sur la branche, cela est plus propre de supprimer les copies locales de la branche afin de ne pas encombrer votre copie de travail avec un tas de branches obsolètes.
```sh
$ git fetch -p upstream
```
où `upstream` est le dépôt distant depuis lequel vous voulez mettre à jour.
<a name="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 :
```sh
(main)$ git checkout -b ma-branche
(ma-branceh)$ git branch
(ma-branche)$ touch foo.txt
(ma-branche)$ ls
README.md foo.txt
```
Ajoutons cela et commitons :
```sh
(ma-branche)$ git add .
(ma-branche)$ git commit -m 'ajout de foo.txt'
(ma-branche)$ ajout de foo.txt
1 files changed, 1 insertions(+)
create mode 100644 foo.txt
(ma-branche)$ git log
commit 4e3cd85a670ced7cc17a2b5d8d3d809ac88d5012
Author: siemiatj <siemiatj@example.com>
Date: Wed Jul 30 00:34:10 2014 +0200
ajout de foo.txt
commit 69204cdf0acbab201619d95ad8295928e7f411d5
Author: Kate Hudson <katehudson@example.com>
Date: Tue Jul 29 13:14:46 2014 -0400
Correction #6: Push de force après avoir édité les commits
```
Maintenant, revenons sur main et supprimons notre branche "par accident" :
```sh
(ma-branche)$ git checkout main
Switched to branch 'main'
Your branch is up-to-date with 'origin/main'.
(main)$ git branch -D my-branch
Deleted branch ma-branche (was 4e3cd85).
(main)$ echo oh non, j'ai supprimé ma branche !
oh non, j'ai supprimé ma branche !
```
À cette étape, vous devriez devenir familier avec `reflog`, un logueur amélioré. Il stocke l'historique de toutes les actions dans le dépôt :
```
(main)$ git reflog
69204cd HEAD@{0}: checkout: moving from ma-branche to main
4e3cd85 HEAD@{1}: commit: ajout de foo.txt
69204cd HEAD@{2}: checkout: moving from main to ma-branche
```
Comme vous pouvez le remarquer, nous avons le hash du commit de notre branche supprimée. Voyons voir si nous pouvons restaurer notre branche supprimée.
```sh
(main)$ git checkout -b ma-branche-help
Switched to a new branch 'ma-branche-help'
(ma-branche-help)$ git reset --hard 4e3cd85
HEAD is now at 4e3cd85 ajout de foo.txt
(ma-branche-help)$ ls
README.md foo.txt
```
Voilà ! Nous avons récupéré notre fichier supprimé. `git reflog` est aussi utile quand un rebase se passe terriblement mal.
### Je veux supprimer une branche
Pour supprimer une branche distante :
```sh
(main)$ git push origin --delete ma-branche
```
Vous pouvez aussi faire :
```sh
(main)$ git push origin :ma-branche
```
Pour supprimer une branche locale :
```sh
(main)$ git branch -d ma-branche
```
Pour supprimer une branche locale qui *n'a pas* été fusionnée vers la branche actuelle ou une branche distante :
```sh
(main)$ git branch -D ma-branche
```
### Je veux supprimer plusieurs branches
Admettons que vous voulez supprimer toutes les branches qui commencent par `fix/` :
```sh
(main)$ git branch | grep 'fix/' | xargs git branch -d
```
### Je veux renommer une branche
Je veux renommer la branche actuelle (locale) :
```sh
(main)$ git branch -m nouveau-nom
```
Pour renommer une autre branche (locale) :
```sh
(main)$ git branch -m ancien-nom nouveau-nom
```
<a name="working-on-checkout-remote-branch"></a>
### 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 :
```sh
(main)$ git fetch --all
```
Admettons que vous souhaitez vous déplacer sur `daves` depuis le dépôt distant :
```sh
(main)$ git checkout --track origin/daves
Branch daves set up to track remote branch daves from origin.
Switched to a new branch 'daves'
```
(`--track` est un raccourci pour `git checkout -b [branch] [remotename]/[branch]`)
Cela vous donnera une copie locale de la branche `daves`, et n'importe quelle mise à jour qui y sera poussée sera aussi visible sur le dépôt distant.
### Je veux créer une nouvelle branche distante à partir de celle en locale
```sh
$ git push <remote> HEAD
```
Si vous voulez configurer cette branche distante en tant qu'upstream pour la branche actuelle, lancez la commande suivante à la place :
```sh
$ git push -u <remote> HEAD
```
Avec le mode `upstream` et le mode `simple` (défaut dans Git 2.0) de la configuration de `push.default`, la commande suivante poussera la branche actuelle par rapport à la branche distante qui a été précédemment enregistrée avec `-u` :
```sh
$ 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#Documentation/git-config.txt-pushdefault).
### Je veux configurer une branche distante en tant qu'upstream pour une branche locale
Vous pouvez configurer une branche distante en tant qu'upstream pour la branche locale actuelle en utilisant :
```sh
$ git branch --set-upstream-to [nomduremote]/[branche]
# ou, en utilisant le raccourci :
$ git branch -u [nomduremote]/[branche]
```
Pour configurer la branche distante en tant qu'upstream pour une autre branche locale :
```sh
$ git branch -u [nomduremote]/[branche] [branche-locale]
```
<a name="head-to-track-remote-branch"></a>
### 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 s
gitextract_i6mlkrch/ ├── .gitignore ├── .travis.yml ├── CONTRIBUTE.md ├── LICENSE ├── README.md ├── README_es.md ├── README_fr.md ├── README_ja.md ├── README_kr.md ├── README_ru.md ├── README_vi.md ├── README_zh-CN.md ├── README_zh-TW.md └── package.json
Condensed preview — 14 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (630K chars).
[
{
"path": ".gitignore",
"chars": 34,
"preview": "node_modules/\r\npackage-lock.json\r\n"
},
{
"path": ".travis.yml",
"chars": 258,
"preview": "language: ruby\nrvm:\n - 2.2\nbefore_script:\n - gem install awesome_bot\n - npm install\nscript:\n- awesome_bot README.md -"
},
{
"path": "CONTRIBUTE.md",
"chars": 2535,
"preview": "# Contributing\n\nThis is a community built document. Dive in and help out!\n\n### Issues\n\n- Please jump in and help us out "
},
{
"path": "LICENSE",
"chars": 20127,
"preview": "Attribution-ShareAlike 4.0 International\n\n=======================================================================\n\nCreat"
},
{
"path": "README.md",
"chars": 80438,
"preview": "# Flight rules for Git\n\n🌍\n*[English](README.md) ∙ [Español](README_es.md) ∙ [Русский](README_ru.md) ∙ [繁體中文](README_zh"
},
{
"path": "README_es.md",
"chars": 54772,
"preview": "# Reglas de vuelo para git\n\n🌍\n*[English](README.md) ∙ [Español](README_es.md) ∙ [Русский](README_ru.md) ∙ [繁體中文](READM"
},
{
"path": "README_fr.md",
"chars": 69181,
"preview": "# Règles de vol pour Git\n\n🌍\n*[English](README.md) ∙ [Español](README_es.md) ∙ [Русский](README_ru.md) ∙ [繁體中文](README_"
},
{
"path": "README_ja.md",
"chars": 69293,
"preview": "# Git フライトルール\n\n🌍\n*[English](README.md) ∙ [Español](README_es.md) ∙ [Русский](README_ru.md) ∙ [繁體中文](README_zh-TW.md) ∙"
},
{
"path": "README_kr.md",
"chars": 46409,
"preview": "# 깃을 위한 flight rules\n\n🌍\n*[English](README.md) ∙ [Español](README_es.md) ∙ [Русский](README_ru.md) ∙ [繁體中文](README_zh-T"
},
{
"path": "README_ru.md",
"chars": 98044,
"preview": "# Правила полета на Git\n\n🌍\n*[English](README.md) ∙ [Español](README_es.md) ∙ [Русский](README_ru.md) ∙ [繁體中文](README_z"
},
{
"path": "README_vi.md",
"chars": 88196,
"preview": "# Flight rules cho Git\n\n🌍\n*[English](README.md) ∙ [Español](README_es.md) ∙ [Русский](README_ru.md) ∙ [繁體中文](README_zh"
},
{
"path": "README_zh-CN.md",
"chars": 32668,
"preview": "# Git飞行规则(Flight Rules)\n\n🌍\n*[English](README.md) ∙ [Español](README_es.md) ∙ [Русский](README_ru.md) ∙ [繁體中文](README_z"
},
{
"path": "README_zh-TW.md",
"chars": 49660,
"preview": "# Git 飛行規則(Flight Rules)\n\n🌍\n*[English](README.md) ∙ [Español](README_es.md) ∙ [Русский](README_ru.md) ∙ [繁體中文](README_"
},
{
"path": "package.json",
"chars": 401,
"preview": "{\n \"private\": true,\n \"name\": \"git-flight-rules\",\n \"version\": \"1.0.0\",\n \"description\": \"Flight rules for git\",\n \"scr"
}
]
About this extraction
This page contains the full source code of the k88hudson/git-flight-rules GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 14 files (597.7 KB), approximately 230.6k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.