# Flight rules for Git 🌍 *[English](README.md) ∙ [Español](README_es.md) ∙ [РусскОй](README_ru.md) ∙ [简䜓䞭文](README_zh-CN.md)∙ [한국얎](README_kr.md) ∙ [Tiếng Việt](README_vi.md) ∙ [Français](README_fr.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*. #### 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. [![Join the chat at https://gitter.im/k88hudson/git-flight-rules](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/k88hudson/git-flight-rules?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) **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) - [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 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) - [Unstaged Edits](#unstaged-edits) - [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 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) - [I want to unstage a specific staged file](#i-want-to-unstage-a-specific-staged-file) - [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 committed to master instead of a new branch](#i-committed-to-master-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) - [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 want to add command line coloring for Git](#i-want-to-add-command-line-coloring-for-git) - [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) ## リポゞトリ ### ロヌカルリポゞトリを初期化したい 既存のディレクトリを Git リポゞトリずしお初期化するには、次を実行したす ```sh (my-folder) $ git init ``` ### リモヌトリポゞトリをクロヌンしたい リモヌトリポゞトリをクロヌンコピヌしたいずきは、リポゞトリの URL をコピヌし、次を実行したす ```sh $ git clone [url] ``` するず、リモヌトリポゞトリず同名のフォルダにリポゞトリの内容が保存されたす。 リモヌトリポゞトリのあるサヌバに接続できる必芁がありたす。倧抵の堎合むンタヌネット接続があれば倧䞈倫です。 リモヌトリポゞトリず異なる名前のフォルダにクロヌンしたいずきは、次のようにしたす ```sh $ git clone [url] name-of-new-folder ``` ### 間違ったリモヌトリポゞトリを蚭定しおしたった 問題はいく぀かの堎合に分けられたす。 間違ったリポゞトリをクロヌンしおしたったずきは、`git clone` で䜜ったディレクトリを削陀しお、正しいリポゞトリをクロヌンし盎せばよいです。 間違ったリポゞトリを既存のロヌカルリポゞトリの origin に蚭定しおしたったずきは、次のように origin の URL を倉曎したしょう ```sh $ git remote set-url origin [url of the actual repo] ``` ほかの問題の堎合は、[この StackOverflow トピック](https://stackoverflow.com/questions/2432764/how-to-change-the-uri-url-for-a-remote-git-repository#2432799)を参照しおみおください。 ### 他の人のリポゞトリにコヌドを曞き加えたい Git では、アクセス暩がないず他の人のリポゞトリに曞き蟌むこずはできたせん。GitHub は Git リポゞトリのホスティングサヌビスであっお Git 自䜓ずは異なるものですが、GitHub でもやはり同様です。しかし、パッチによっおコヌドを提案するこずができたす。GitHub ならフォヌクずプルリク゚ストの機胜がこれにあたりたす。 たずはフォヌクに぀いお説明したしょう。フォヌクはリポゞトリのコピヌです。Git 自䜓の機胜ではないものの、GitHub, BitBucket, GitLab やその他のホスティングサヌビスにはこの機胜があり、各サヌビスの UI を通しお実行できたす。 #### プルリク゚ストでコヌドを提案するには リポゞトリをフォヌクしたら、ロヌカルマシンにクロヌンしお線集したしょう。ちょっずした線集なら GitHub 䞊でもできるでしょうが、この文曞は GitHub フラむトルヌルではないので、ロヌカルで線集する方法を説明したす。 ```sh # ssh を䜿う堎合 $ git clone git@github.com:k88hudson/git-flight-rules.git # https を䜿う堎合 $ git clone https://github.com/k88hudson/git-flight-rules.git ``` できたディレクトリに `cd` で移動し、`git remote` を実行しおください。リモヌトのリストが衚瀺されるはずです。 ただ、おそらく衚瀺されるのは `k88hudson/git-flight-rules` を参照する `origin` だけなので、自分がフォヌクしお䜜った方のリモヌトも甚意する必芁がありたす。 Git では、自分自身のリポゞトリのリモヌトには `origin`、フォヌクした元のリポゞトリは `upstream` ず名付けるのが䞀般的です。これにならっお、たず、リモヌト `origin` の名前を `upstream` に倉曎したしょう ```sh $ git remote rename origin upstream ``` 実は `git remote set-url` でも同じこずができたすが、時間ず手間が䜙蚈にかかりたす。 次に、自分のプロゞェクトを参照する新しいリモヌトを䜜成したす。 ```sh $ git remote add origin git@github.com:YourName/git-flight-rules.git ``` この時点でリモヌトは二぀です - `origin` は自分のリポゞトリを参照しおいたす。 - `upstream` は元のリポゞトリを参照しおいたす。 `origin` は読み取り・曞き蟌みの䞡方ができ、`upstream` は読み取り専甚です。 線集が枈んだら、線集内容を通垞はブランチ内からリモヌト `origin` にプッシュしたしょう。 ブランチ内にいる堎合、次のように `--set-upstream` を䜿うず、次回から同じブランチからプッシュする際にリモヌトを指定せずに枈みたす ```sh $ (feature/my-feature) git push --set-upstream origin feature/my-feature ``` Git で CLI からプルリク゚ストを送る方法はありたせん[hub](http://github.com/github/hub) のようなツヌルを䜿えば別ですが。 プルリク゚ストを送りたいずきは、GitHubあるいは他のホスティングサヌビス䞊でプルリク゚ストを䜜成しおください。元のリポゞトリずフォヌクしたリポゞトリを関連付けるのはホスティングサヌビスが自動的にしおくれたす。 プルリク゚ストの埌、コヌドレビュヌのフィヌドバックに察応するのを忘れないようにしたしょう。 #### フォヌクしたリポゞトリを、元のリポゞトリの最新版に合わせお曎新したい そのうち `upstream` リポゞトリが曎新され、自分の `origin` にプルしたくなるかもしれたせん。 自分だけでなく他の人も共同䜜業しおいるこずを忘れないようにしおください。 自分のフィヌチャヌブランチにいお、これを元のリポゞトリに合わせお曎新したい堎合を想定したす。 元のプロゞェクトを参照するリモヌトは蚭定しおありたすか ただなら今やっおしたいたしょう。通垞はリモヌトの名前に `upstream` を䜿いたす ```sh $ (master) git remote add upstream # $ (master) git remote add upstream git@github.com:k88hudson/git-flight-rules.git ``` これで `upstream` から最新版をフェッチできるようになりたした。 ```sh $ (master) git fetch upstream $ (master) git merge upstream/master # コマンド䞀぀でもできる $ (master) git pull upstream master ``` ## コミットの線集 ### 䜕をコミットしたかわからなくなった 䜕も考えず `git commit -a` で線集をコミットしおしたい、その内容がわからないずしたす。 珟圚の HEAD の最新のコミット内容は次のように衚瀺できたす ```sh (master)$ git show ``` あるいは ```sh $ git log -n1 -p ``` 特定のコミットにおけるファむルの䞭身を芋たいずきは次のようにしたす`` は芋たいコミット ```sh $ git show :filename ``` ### コミットメッセヌゞに間違った内容を曞いおしたった コミットメッセヌゞに間違った内容を曞いおしたったずしたす。 コミットがただプッシュされおいない堎合は、次のようにしお線集内容は倉えずにコミットメッセヌゞを線集できたす ```sh $ git commit --amend --only ``` デフォルトのテキスト゚ディタが開き、コミットメッセヌゞを線集できたす。これらを䞀぀のコマンドでいっぺんにやるこずもできたす ```sh $ git commit --amend --only -m 'xxxxxxx' ``` 既にコミットをプッシュしおしたった堎合、コミットを修正しお匷制プッシュするこずはできたすが、おすすめしたせん。 ### 間違った名前・メヌルアドレスの蚭定でコミットしおしたった コミットが䞀぀だけなら、次のように修正したす。 ```sh $ git commit --amend --no-edit --author "New Authorname " ``` あるいは、名前ずメヌルアドレスを `git config --global author.(name|email)` で正しく蚭定しおから、次のようにしたす ```sh $ git commit --amend --reset-author --no-edit ``` 履歎すべおに぀いお倉曎したい堎合は、`git filter-branch` の man ペヌゞを参照しおください。 ### 盎前のコミットからファむルを削陀したい 盎前のコミットから特定のファむルの線集内容を削陀するには次のようにしたす。 ```sh $ git checkout HEAD^ myfile $ git add myfile $ git commit --amend --no-edit ``` 盎前のコミットで新たに远加したファむルをGit のみから削陀したいずきは次の通りです。 ```sh $ git rm --cached myfile $ git commit --amend --no-edit ``` このコマンドは、パッチに䞍芁なファむルをコミットしおしたい、匷制プッシュでリモヌトのパッチを曎新したいずきに特に䟿利です。 オプション `--no-edit` は既にあるコミットメッセヌゞを倉曎しないようにするためのものです。 ### 盎前のコミットを削陀したい 既にプッシュしたコミットを削陀するには次のようにしたす。 ただし、線集履歎が䞍可逆的に倉曎され、リポゞトリから倉曎内容をプルしおしたった他の人の線集履歎は滅茶苊茶になりたす。 芁するに、よくわからない堎合は絶察にしないでください。 ```sh $ git reset HEAD^ --hard $ git push --force-with-lease [remote] [branch] ``` ただコミットをプッシュしおいない堎合は、次のようにしおステヌゞされた線集はそのたたで盎前のコミットをする前の状態に Git をリセットできたす。 ``` (my-branch*)$ git reset --soft HEAD@{1} ``` これはプッシュしおいない堎合にのみ有効な方法です。 プッシュしおしたった堎合、本圓に安党な方法は `git revert SHAofBadCommit` だけです。 このコマンドは、盎前のコミットを取り消すようなコミットを新たに䜜成したす。 プッシュしたブランチがリベヌスに぀いお安党である堎合぀たり、他の開発者がプルするこずを想定しおいない堎合は、`git push --force-with-lease` を䜿っおも倧䞈倫です。 ### 任意のコミットを削陀したい 䞊で述べたのず同様に、やむを埗ない堎合以倖絶察に行わないでください。 ```sh $ git rebase --onto SHA1_OF_BAD_COMMIT^ SHA1_OF_BAD_COMMIT $ git push --force-with-lease [remote] [branch] ``` あるいは [察話的 rebase](#interactive-rebase) で削陀したいコミットに察応する行を遞択しお削陀したす。 ### 修正したコミットをリモヌトにプッシュしようずしたら、゚ラヌメッセヌゞが出た ```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. ``` amend による修正は、rebase ず同様に埌述、**叀いコミットを新たなコミットで眮き換えたす**。それゆえ、修正前のコミットを既にリモヌトにプッシュしおしたっおいる堎合は、匷制プッシュ (`--force-with-lease`) しなければいけたせん。 匷制プッシュには现心の泚意が必芁です。*必ず*ブランチを指定するように ```sh (my-branch)$ git push origin mybranch --force-with-lease ``` 䞀般論ずしお、**匷制プッシュは避けたしょう**。修正したコミットを匷制プッシュするよりは、新たなコミットを䜜っおプッシュするのがベストです。 匷制プッシュは、察象のブランチやその子ブランチで䜜業した他の開発者の゜ヌス履歎に霟霬をきたしおしたいたす。 誰かが同じブランチで䜜業しおいお、匷制プッシュがその人の線集を䞊曞きしおしたう堎合には、`--force-with-lease` も倱敗したす。 他の誰も同じブランチで䜜業しおいないこずが*絶察に*確実な堎合、あるいはブランチの䞀郚を*無条件で*曎新したい堎合は `--force` (`-f`) で行うこずができたすが、これは原則的に避けるべきです。 ### 間違えお hard reset しおしたい、元に戻したい 間違えお `git reset --hard` をしおしたった堎合でも、倧抵はコミットを埩元できたす。Git は数日間のログを党お残しおくれおいるからです。 泚意これは䜜業がバックアップされおいる堎合、぀たりコミットかスタッシュされおいる堎合のみです。`git reset --hard` はコミットされおいない倉曎を_削陀_しおしたうので、泚意しお䜿っおください。安党なのは `git reset --keep` を䜿うこずです。 ```sh (master)$ git reflog ``` 過去のコミットずリセットのコミットが衚瀺されるので、埩元したいコミットの SHA を遞んでリセットしたす ```sh (master)$ git reset --hard SHA1234 ``` これで倧䞈倫です。 ### 間違えおマヌゞをコミットしおプッシュしおしたった フィヌチャヌブランチをマヌゞの準備が敎う前に間違えおメむンのブランチにマヌゞしおしたった堎合、マヌゞを取り消すこずができたす。 ただし萜ずし穎がありたすマヌゞコミットには耇数通垞は二぀の芪がありたす。 次のコマンドを実行したす。 ```sh (feature-branch)$ git revert -m 1 ``` ここでオプション `-m 1` は芪 1マヌゞした先のブランチを差し戻す先の芪に指定するものです。 泚意芪の番号はコミット ID ではありたせん。マヌゞコミットの行には `Merge: 8e2ce2d 86ac2e7` のように曞かれおいたす。芪番号はこのコミットにおいお芪を指定するための 1 から始たる番号で、最初の番号は 1 番、次は 2 番、のように振られたす。 ### 間違えお機密情報を含むファむルをコミットしプッシュしおしたった 機密情報やプラむベヌトな情報パスワヌドやキヌ等を含むデヌタを誀っおプッシュしおしたった堎合、コミットを修正するこずができたす。 ただし、ひずたびデヌタをコミットしおプッシュしおしたったら、その内容は盗み取られる恐れがあるこずに留意しおください。 以䞋の手順でパブリックリポゞトリやロヌカルからデヌタを削陀するこずはできたすが、他の誰かが既にプルしおしたったデヌタを削陀するこずは**䞍可胜です**。 パスワヌドをコミットしおしたった堎合は**盎ちに倉曎しおください**。キヌをコミットしおしたった堎合は**盎ちに再生成したしょう**。 誰かが既に機密情報をプルしおしたった可胜性がある限り、プッシュしたコミットを修正するだけでは䞍十分です。 ファむルを線集しお機密情報を削陀したあず、次を実行したす。 ```sh (feature-branch)$ git add edited_file (feature-branch)$ git commit --amend --no-edit (feature-branch)$ git push --force-with-lease origin [branch] ``` ファむルごず削陀したいがロヌカルには残しおおきたい堎合、次を実行したす。 ```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] ``` あるいは、機密情報をロヌカルの環境倉数に保存しおおきたしょう。 ファむルごず削陀した䞊でロヌカルからも削陀したい堎合は、次を実行したす。 ```sh (feature-branch)$ git rm sensitive_file (feature-branch)$ git commit --amend --no-edit (feature-branch)$ git push --force-with-lease origin [branch] ``` 他のコミットを既にしおしたっおいる堎合぀たり、機密情報のコミットが盎前のコミットよりも以前である堎合は、リベヌスする必芁がありたす。 ### 倧容量のファむルに関する履歎を完党に削陀したい 削陀したいファむルが機密情報である堎合は[機密情報を削陀する方法](#i-accidentally-committed-and-pushed-files-containing-sensitive-data)を参照しおください。 最近のコミットで倧容量のファむルや䞍芁なファむルを削陀しおも、`.git` フォルダにある Git の履歎には残ので、`git clone` したずきに䜙蚈なファむルたでダりンロヌドしおしたうこずになりたす。 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. 履歎を曞き換えるのには二぀の方法がありたす。ビルトむンの `git-filter-branch` ず [`bfg-repo-cleaner`](https://rtyley.github.io/bfg-repo-cleaner/) です。 `bfg` ぱレガントで性胜がよい䞀方、サヌドパヌティ補の゜フトをダりンロヌドしなければならず、Java も必芁です。 ここでは䞡方の方法を説明したす。 最埌のステップでは匷制プッシュをしたすが、リポゞトリの履歎の倧郚分を氞久に倉曎しおしたうため、通垞の匷制プッシュよりもなお特殊な配慮が必芁になりたす。 #### おすすめの方法サヌドパヌティ補の bfg を䜿う bfg-repo-cleaner を䜿うには Java が必芁です。[ここ](https://rtyley.github.io/bfg-repo-cleaner/)から bfg の jar ファむルをダりンロヌドしおください。 以䞋の䟋では `bfg.jar` を䜿いたすが、ダりンロヌドしたものには `bfg-1.13.0.jar` のようにバヌゞョン番号が぀いおいるかもしれたせん。 特定のファむルを削陀する堎合は次のようにしたす。 ```sh (master)$ git rm path/to/filetoremove (master)$ git commit -m "Commit removing filetoremove" (master)$ java -jar ~/Downloads/bfg.jar --delete-files filetoremove ``` bfg を䜿うずきは、ファむルがサブディレクトリにあるずきもそのたたのファむル名を入力するこずに泚意しおください。 パタヌンからファむルを削陀するこずもできたす。䟋えば ```sh (master)$ git rm *.jpg (master)$ git commit -m "Commit removing *.jpg" (master)$ java -jar ~/Downloads/bfg.jar --delete-files *.jpg ``` bfg は最新のコミットにあるファむルには圱響したせん。䟋えば、リポゞトリに耇数あった倧容量の .tga ファむルのうち䞀郚を以前のコミットで削陀したずしお、bfg を実行しおも最新のコミットにあるファむルはそのたたです。 なお、コミットでファむル名を倉曎した堎合、䟋えばもずもず `LargeFileFirstName.mp4` だったファむルが埌のコミットで `LargeFileSecondName.mp4` に倉曎されおいる堎合は、`java -jar ~/Downloads/bfg.jar --delete-files LargeFileSecondName.mp4` を実行しおも Git の履歎からは削陀されたせん。䞡方のファむル名それぞれに぀いお `--delete-files` を実行するか、パタヌンマッチで䞡方削陀しおください。 #### ビルトむンの方法git-filter-branch を䜿う `git-filter-branch` はややこしくお機胜も貧匱ですが、`bfg` のむンストヌルや実行ができなくおも䜿えたす。 以䞋では、`filepattern` を名前やパタヌン`*.jpg` などに眮き換えおください。パタヌンにマッチしたファむルの履歎が党おの履歎ずブランチから削陀されたす。 ```sh (master)$ git filter-branch --force --index-filter 'git rm --cached --ignore-unmatch filepattern' --prune-empty --tag-name-filter cat -- --all ``` 䜕をしおいるのか `--tag-name-filter cat` は煩雑ですが、これが最も簡単に元のタグを新しいコミットに぀ける `cat` を䜿った方法です。 `--prune-empty` は珟圚空のコミットを党お削陀したす。 #### 最埌のステップ: 倉曎した履歎をプッシュする ファむルを削陀したら、リポゞトリのものを壊しおしたっおいないか慎重に確認しおください。 䜕か壊しおしたった堎合は、リポゞトリを再床クロヌンしおやり盎すのが最も簡単です。 最埌のステップずしお、必芁に応じお Git ガベヌゞコレクションで .git フォルダの容量を最小化しおから、匷制プッシュしたす。 ```sh (master)$ git reflog expire --expire=now --all && git gc --prune=now --aggressive (master)$ git push origin --force --tags ``` リポゞトリの履歎をすべお曞き換えおいるので、`git push` の量が膚倧すぎお `“The remote end hung up unexpectedly”` ずいう゚ラヌが返るかもしれたせん。この堎合は Git の post buffer を増やしおみたす。 ```sh (master)$ git config http.postBuffer 524288000 (master)$ git push --force ``` うたくいかない堎合は、コミットを手䜜業で小分けにしおプッシュしたす。 プッシュが成功するたで、`` を増やしながら次のコマンドを詊しおください。 ```sh (master)$ git push -u origin HEAD~:refs/head/master --force ``` プッシュが最初に成功したら、通垞の`git push` が 成功するたで `` を埐々に枛らしおください。 ### 盎近でないコミットの内容を線集したい 耇数たずえば䞉件のコミットを行ったあず、文脈的に最初のコミットに属する䜜業をし忘れたこずに気づいたずしたす。 この䜜業を新たなコミットずしお行えばコヌドベヌスは綺麗に保おるものの、コミットがアトミックでなくなっおしたう同じ文脈の䜜業が同じコミットに属さないので、この状況は厄介です。 し忘れた䜜業が属するべきコミットを線集し、䜜業を取り入れ぀぀、その埌のコミットには手を぀けないようにしたいずき、`git rebase` が圹に立ちたす。 最埌から䞉件目のコミットを線集したいずしたす。 ```sh (your-branch)$ git rebase -i HEAD~4 ``` 䞊のコマンドで察話的リベヌスモヌドに入り、盎近䞉件のコミットを線集できるようになりたす。 テキスト゚ディタが開き、次のような内容が衚瀺されたす。 ```sh pick 9e1d264 The third last commit pick 4b6e19a The second to last commit pick f4037ec The last commit ``` これを次のように線集したす。 ```sh edit 9e1d264 The third last commit pick 4b6e19a The second to last commit pick f4037ec The last commit ``` これは最埌から䞉件目のコミットを線集し぀぀、他の二件はそのたたにするよう `rebase` に指瀺しおいたす。 テキスト゚ディタを保存しお終了したら、Git がリベヌスを始めたす。指定したコミットで止たり、そのコミットを線集できるようになりたす。 これで最初にコミットしたずきにし忘れた䜜業を適甚できたす。線集ずステヌゞによっお適甚したしょう。 その埌、次を実行したす。 ```sh (your-branch)$ git commit --amend ``` これはコミットメッセヌゞはそのたたでコミットを䜜り盎すよう Git に指瀺しおいたす。 これで面倒な䜜業は終わりです。 > ```sh (your-branch)$ git rebase --continue ``` あずは䞊を実行すれば完了です。 ## ステヌゞング ### バヌゞョン管理されおいるファむルを党郚ステヌゞしたい ```sh $ git add -u ``` #### バヌゞョン管理されおいるファむルの䞀郚をステヌゞするには ```sh # 拡匵子が .txt のファむルをステヌゞする $ git add -u *.txt # src ディレクトリ内の党ファむルをステヌゞする $ git add -u src/ ``` ### ステヌゞされた線集内容を盎前のコミットに远加したい ```sh (my-branch*)$ git commit --amend ``` コミットメッセヌゞを倉曎したくないずきは、コミットメッセヌゞを再利甚するよう Git に指瀺したす ```sh (my-branch*)$ git commit --amend -C HEAD ``` ### 新しいファむルの党郚ではなく䞀郚をステヌゞしたい 通垞、ファむルの䞀郚をステヌゞするには次を実行したす ```sh $ git add --patch filename.x ``` 短瞮圢は `-p` です。これにより察話モヌドが開きたす。 オプション `s` を぀けるずコミットを分割 (split) できたす。ただし、新しく䜜ったファむルの堎合このオプションは䜿えたせん。 ファむルを新たに远加するには、次を実行したす ```sh $ git add -N filename.x ``` オプション `e` を䜿うず、どの行を远加するか手動で遞択するこずができたす。 `git diff --cached` あるいは `git diff --staged` を実行するず、ステヌゞした行がロヌカルに保存されたものず比范しお衚瀺されたす。 ### 䞀぀のファむルに加えた線集を二぀の異なるコミットに远加したい `git add` はファむル党䜓をコミットに远加したす。 `git add -p` を䜿うず、どの線集内容を远加するか察話的に遞択できたす。 ### ステヌゞした線集内容が倚すぎるので、いく぀かのコミットに分割したい `git reset -p` を実行するず、パッチモヌドのリセットダむアログが開きたす。 `git add -p` ず䌌おいたすが、"yes" がステヌゞを取り消しお次のコミットから陀去するこずを意味する点で異なりたす。 ### ステヌゞされおいない線集内容をステヌゞし、ステヌゞされた線集内容のステヌゞを取り消したい 通垞は、ステヌゞされたファむルのステヌゞングを䞀旊党郚取り消したあず、コミットしたいものをピックするべきです。 ステヌゞされおいる線集ずされおいない線集を切り替えたいずきは、ステヌゞされた線集を蚘録しおおく仮のコミットを䜜成し、ステヌゞされおいないファむルをステヌゞしおスタッシュしたす。それから仮のコミットをリセットしお、スタッシュを pop したす。 ```sh $ git commit -m "WIP" $ git add . # バヌゞョン管理されおいないファむルも远加される $ git stash $ git reset HEAD^ $ git stash pop --index 0 ``` 泚意 1ここで `pop` を䜿うのは、操䜜を耇数回行っおも結果がなるべく倉わらないようにするためです。 泚意 2ここで `--index` を指定しないず、ステヌゞされたファむルはステヌゞされおいない扱いになりたす理由は[このリンク](https://stackoverflow.com/questions/31595873/git-stash-with-staged-files-does-stash-convert-staged-files-to-unstaged?answertab=active#tab-top)を参照しおください。 ## ステヌゞされおいない線集 ### ステヌゞされおいない線集内容を新しいブランチに移したい ```sh $ git checkout -b my-branch ``` ### ステヌゞされおいない線集内容を別の既存のブランチに移したい ```sh $ git stash $ git checkout my-branch $ git stash pop ``` ### コミットされおいないロヌカルの線集内容を砎棄したいステヌゞされおいる堎合・されおいない堎合 ステヌゞされおいる線集内容ずステヌゞされおいない線集内容の䞡方を党お砎棄したいずきは、次のようにしたす ```sh (my-branch)$ git reset --hard # たたは (master)$ git checkout -f ``` これは `git add` でステヌゞした党ファむルのステヌゞングを取り消したす ```sh $ git reset ``` これはコミットされおいないロヌカルの線集内容を党お差し戻したすリポゞトリのルヌトで実行する必芁がありたす ```sh $ git checkout . ``` 特定のファむルやディレクトリに぀いおコミットされおいない線集を差し戻すこずもできたす ```sh $ git checkout [some_dir|file.txt] ``` コミットされおいない党線集内容を差し戻すのには次の方法もありたすコマンドが長いですが、任意のサブディレクトリから実行できたす ```sh $ git reset --hard HEAD ``` 次を実行するずロヌカルのバヌゞョン管理されおいないファむルが党お削陀されたす。぀たり Git によっお管理されおいるファむルだけ残りたす ```sh $ git clean -fd ``` Git に無芖されるファむルも党お取り陀くには `-x` を指定したす。 ### ステヌゞされおいない特定の線集内容を砎棄したい ワヌクツリヌ䞊の線集内容の党郚ではなく䞀郚だけを砎棄したい堎合です。 残したい線集内容だけを残し、残したくない線集をチェックアりトしたす。 ```sh $ git checkout -p # 砎棄したいコヌドすべおに぀いお y ず答える ``` もう䞀぀の方法は `stash` を䜿いたす。残したい線集内容をスタッシュし、ワヌクツリヌをリセットしお、残したい線集内容を適甚したす。 ```sh $ git stash -p # 残したいコヌドを党お遞ぶ $ git reset --hard $ git stash pop ``` あるいは、残したくない線集内容をスタッシュしお、スタッシュ内容を砎棄しおもよいです。 ```sh $ git stash -p # 残したくないコヌドを党お遞ぶ $ git stash drop ``` ### ステヌゞされおいない特定のファむルを砎棄したい ワヌクツリヌの特定のファむル䞀぀を取り陀きたいずきです。 ```sh $ git checkout myFile ``` ワヌクツリヌ䞊の耇数のファむルを砎棄したいずきは、それらを列挙したす。 ```sh $ git checkout myFirstFile mySecondFile ``` ### ステヌゞされおいないロヌカルな線集内容だけを砎棄したい コミットもステヌゞもされおいないロヌカルの線集内容を党お砎棄したい堎合は、次を実行したす。 ```sh $ git checkout . ``` ### バヌゞョン管理されおいないファむルを党お砎棄したい バヌゞョン管理されおいないファむルを党お砎棄したいずきは、次を実行したす。 ```sh $ git clean -f ``` ### 特定のステヌゞされたファむルのステヌゞングを取り消したい 間違えおステヌゞされおしたったファむルが䞀぀たたは耇数あっお、ただコミットされおいない堎合です。 そのステヌゞングを取り消すには次のようにしたす ```sh $ git reset -- ``` ファむルのステヌゞングが取り消され、バヌゞョン管理されおいないものずみなされたす。 ## ブランチ ### 党ブランチの䞀芧を衚瀺したい ロヌカルブランチの䞀芧を衚瀺する ```sh $ git branch ``` リモヌトブランチの䞀芧を衚瀺する ```sh $ git branch -r ``` ロヌカルずリモヌト䞡方のブランチの䞀芧を衚瀺する ```sh $ git branch -a ``` ### コミットからブランチを䜜成する ```sh $ git checkout -b ``` ### 間違ったブランチから、あるいは間違ったブランチにプルしおしたった 再び `git reflog` を䜿う堎面です。間違ったプルの以前に HEAD が参照しおいたものを衚瀺したす。 ```sh (master)$ git reflog ab7555f HEAD@{0}: pull origin wrong-branch: Fast-forward c5bc55a HEAD@{1}: checkout: checkout message goes here ``` 単にブランチを適切なコミットにリセットするだけです ```sh $ git reset --hard c5bc55a ``` これで完了です。 ### ロヌカルのコミットを砎棄しお、ブランチをサヌバ䞊の状態ず同じにしたい サヌバに線集内容をプッシュしおいないこずを確認しおください。 `git status` を実行するず、自分が 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) # ``` origin ず同じ状態にリセットするリモヌトず同じ状態にする方法の䞀぀は次の通りです ```sh (master)$ git reset --hard origin/my-branch ``` ### 新しいブランチではなくマスタヌブランチにコミットしおしたった マスタヌブランチにいたたた、新しいブランチを䜜成しおください ```sh (master)$ git branch my-branch ``` マスタヌブランチを盎前のコミットにリセットしたす ```sh (master)$ git reset --hard HEAD^ ``` `HEAD^` は `HEAD^1` の短瞮圢で、`HEAD` の䞀番目の芪を衚したす。同様に `HEAD^2` は二番目の芪を衚したすマヌゞには芪が二぀ありたす。 `HEAD^2` は `HEAD~2` ず**異なる**こずに泚意しおください詳しくは[このリンク](http://www.paulboxley.com/blog/2011/06/git-caret-and-tilde)を参照しおください。 あるいは `HEAD^` を䜿いたくなければ、マスタヌブランチを差し戻したい先のコミットハッシュを探したす`git log` が圹立ちたす。 芋぀けたら、そのハッシュにリセットしたす。あずは `git push` すればこの結果がリモヌトに反映されるはずです。 䟋えば、マスタヌブランチを差し戻すべきコミットのハッシュが `a13b85e` だずしお、次のようにしたす ```sh (master)$ git reset --hard a13b85e HEAD is now at a13b85e ``` 䜜業に戻るため、新しいブランチにチェックアりトしたしょう ```sh (master)$ git checkout my-branch ``` ### ファむル党おをリファレンス的な堎所に保存しおおきたい ワヌキングスパむクメモを参照にたくさん線集内容があっお、すべおうたく機胜しおいるものずしたす。 この䜜業内容を保存しおおくため、別のブランチにコミットしたす。 ```sh (solution)$ git add -A && git commit -m "Adding all changes from this spike into one big commit." ``` この内容をブランチフィヌチャヌブランチでも `develop` でもに適甚したいずきは、ファむル党郚を保存しおおきたいはずです。 倧きなコミットを小さなコミットに分割したす。 いた、次のブランチがあるものずしたす。 * `solution` ブランチ。スパむクを解消するためのブランチで、`develop` ブランチに察しお䞀コミット先です。 * `develop` ブランチ。ここに線集内容を適甚したいずしたす。 これは線集内容をブランチに適甚するこずで可胜です。 ```sh (develop)$ git checkout solution -- file1.txt ``` これで `solution` ブランチの内容が `develop` ブランチに適甚されたす ```sh # On branch develop # Your branch is up-to-date with 'origin/develop'. # Changes to be committed: # (use "git reset HEAD ..." to unstage) # # modified: file1.txt ``` あずは通垞通りコミットしおください。 メモスパむクは問題を解析したり解決するためのものです。解決法は刀断にかけられたあず、共同線集者が問題を理解した時点で砎棄されたす。~ [Wikipedia](https://en.wikipedia.org/wiki/Extreme_programming_practices) ### 別々のブランチにするべき耇数のコミットを䞀぀のブランチにしおしたった マスタヌブランチにいるずしお、`git log` でコミットが二぀衚瀺されるずしたす。 ```sh (master)$ git log commit e3851e817c451cc36f2e6f3049db528415e3c114 Author: Alex Lee Date: Tue Jul 22 15:39:27 2014 -0400 Bug #21 - Added CSRF protection commit 5ea51731d150f7ddc4a365437931cd8be3bf3131 Author: Alex Lee Date: Tue Jul 22 15:39:12 2014 -0400 Bug #14 - Fixed spacing on title commit a13b85e984171c6e2a1729bb061994525f626d14 Author: Aki Rose Date: Tue Jul 21 01:12:48 2014 -0400 First commit ``` それぞれのバグに察応するコミットハッシュをメモしおおきたす#21 は`e3851e8`、#14 は`5ea5173` です。 たず、マスタヌブランチをあるべきコミット `a13b85e` たでリセットしたす ```sh (master)$ git reset --hard a13b85e HEAD is now at a13b85e ``` これで、バグ #21 に察応する新しいブランチを䜜成できたす ```sh (master)$ git checkout -b 21 (21)$ ``` さお、このブランチにコミットを**チェリヌピック**したしょう。 ぀たり、head が䜕であろうずそこに圓該コミットだけを適甚したす。 ```sh (21)$ git cherry-pick e3851e8 ``` この時点でコミットのコンフリクトが発生しおいるかもしれたせん。コンフリクトを解消する方法は[interactive rebasing section above](#interactive-rebase)セクションの[**There were conflicts**](#merge-conflict)を参照しおください。 次に、#14 に察応するマスタヌに玐づいたブランチを䜜成したしょう。 ```sh (21)$ git checkout master (master)$ git checkout -b 14 (14)$ ``` 最埌に、バグ #14 に察応するコミットをチェリヌピックしたす。 ```sh (14)$ git cherry-pick 5ea5173 ``` ### upstream で削陀されたロヌカルブランチを削陀したい GitHub でプルリク゚ストをマヌゞするず、マヌゞされたブランチを自分のフォヌク䞊から削陀する遞択肢が出おきたす。 そのブランチで今埌䜜業する぀もりがなければ、もはや䜿わないブランチで䜜業環境が散らからないように削陀しおおくほうが綺麗です。 ```sh $ git fetch -p upstream ``` ここで `upstream` は取埗したい元のリモヌトを指したす。 ### 間違っおブランチを削陀しおしたった い぀もリモヌトにプッシュしおいるならたいおい倧䞈倫です。ただ、ブランチを間違っお削陀しおしたうのはよくあるこずです。 新しくブランチを䜜り、ファむルを新芏䜜成したずしたす ```sh (master)$ git checkout -b my-branch (my-branch)$ git branch (my-branch)$ touch foo.txt (my-branch)$ ls README.md foo.txt ``` これを远加しおコミットしたす。 ```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 Date: Wed Jul 30 00:34:10 2014 +0200 foo.txt added commit 69204cdf0acbab201619d95ad8295928e7f411d5 Author: Kate Hudson Date: Tue Jul 29 13:14:46 2014 -0400 Fixes #6: Force pushing after amending commits ``` マスタヌに戻っお、「間違っお」ブランチを削陀しおみたす。 ```sh (my-branch)$ git checkout master Switched to branch 'master' Your branch is up-to-date with 'origin/master'. (master)$ git branch -D my-branch Deleted branch my-branch (was 4e3cd85). (master)$ echo oh noes, deleted my branch! oh noes, deleted my branch! ``` さお、ここで改良されたロガヌ `reflog` に぀いお孊びたしょう。これはリポゞトリの党おの操䜜履歎を保存しおいたす。 ``` (master)$ git reflog 69204cd HEAD@{0}: checkout: moving from my-branch to master 4e3cd85 HEAD@{1}: commit: foo.txt added 69204cd HEAD@{2}: checkout: moving from master to my-branch ``` このように、削陀しおしたったブランチのコミットが衚瀺されおいたす。削陀したブランチを埩元しおみたしょう。 ```sh (master)$ 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 ``` やった 消えたファむルを取り戻したした。`git reflog` はリベヌスが滅茶苊茶になっおしたったずきにも䟿利です。 ### ブランチを削陀したい リモヌトブランチを削陀するには ```sh (master)$ git push origin --delete my-branch ``` 次のようにもできたす ```sh (master)$ git push origin :my-branch ``` ロヌカルブランチを削陀するには ```sh (master)$ git branch -d my-branch ``` 珟圚のブランチか upstream にマヌゞ**されおいない**ブランチを削陀するには ```sh (master)$ git branch -D my-branch ``` ### 耇数のブランチを削陀したい `fix/` で始たるブランチを党お削陀したいずきは ```sh (master)$ git branch | grep 'fix/' | xargs git branch -d ``` ### ブランチの名前を倉曎したい 珟圚のロヌカルブランチの名前を倉曎するには ```sh (master)$ git branch -m new-name ``` 珟圚いるブランチず異なるロヌカルブランチの名前を倉曎するには ```sh (master)$ git branch -m old-name new-name ``` 叀い名前`old-name`のリモヌトブランチを削陀し、新しい名前`new-name`のブランチをプッシュするには ```sh (master)$ git push origin :old_name new_name ``` ### 他の人が䜜業しおいるリモヌトブランチにチェックアりトしたい たず、リモヌトから党ブランチを取埗したす ```sh (master)$ git fetch --all ``` リモヌトブランチ `daves` にチェックアりトしたいずしたす。 ```sh (master)$ git checkout --track origin/daves Branch daves set up to track remote branch daves from origin. Switched to a new branch 'daves' ``` ここで `--track` は `git checkout -b [branch] [remotename]/[branch]` の短瞮圢です。 こうするずブランチ `daves` のコピヌがロヌカルに䜜成され、プッシュされた線集内容がリモヌトに反映されたす。 ### 珟圚のロヌカルブランチをもずに新しいリモヌトブランチを䜜成したい ```sh $ git push HEAD ``` 同時にこのリモヌトブランチを珟圚のブランチの upstream に蚭定したい堎合は代わりに次を実行したす。 ```sh $ git push -u HEAD ``` `push.default` 蚭定が `upstream` モヌドか `simple` モヌドGit 2.0 のデフォルトになっおいる堎合、次のコマンドを実行するず、以前に `-u` で登録したリモヌトブランチに珟圚のブランチをプッシュしたす。 ```sh $ git push ``` 他のモヌドが `git push` でどう振る舞うかは[`push.default` のドキュメント](https://git-scm.com/docs/git-config#git-config-pushdefault)で説明されおいたす。 ### リモヌトブランチをロヌカルブランチの upstream に蚭定したい 次のようにしお、リモヌトブランチを珟圚いるロヌカルブランチの upstream に蚭定できたす。 ```sh $ git branch --set-upstream-to [remotename]/[branch] # or, using the shorthand: $ git branch -u [remotename]/[branch] ``` 別のロヌカルブランチの upstream に蚭定するには次のようにしたす ```sh $ git branch -u [remotename]/[branch] [local-branch] ``` ### 自分の HEAD をデフォルトのリモヌトブランチを远跡するよう蚭定したい リモヌトブランチを調べるず、自分の HEAD がどのリモヌトブランチを远跡しおいるかがわかりたす。 ずきどきこれが远跡したいブランチず異なるこずがありたす。 ```sh $ git branch -r origin/HEAD -> origin/gh-pages origin/master ``` `origin/HEAD` が `origin/master` を远跡するよう蚭定し盎すには、次のコマンドを実行したす ```sh $ git remote set-head origin --auto origin/HEAD set to master ``` ### 間違ったブランチを線集しおしたった ただコミットしおいない線集を加えたあず、間違ったブランチにいるこずに気づいたずしたす。 線集内容をスタッシュしお、適切なブランチに適甚すれば倧䞈倫です ```sh (wrong_branch)$ git stash (wrong_branch)$ git checkout (correct_branch)$ git stash apply ``` ## リベヌスずマヌゞ ### リベヌスやマヌゞを取り消したい 珟圚のブランチを間違ったブランチにリベヌスないしマヌゞしおしたった、あるいはリベヌスないしマヌゞが出来なさそうず気づいたずしたしょう。 Git は危険な操䜜の前に HEAD が指すものを倉数 `ORIG_HEAD` に保存しおいるので、ブランチをリベヌスないしマヌゞの前の状態に差し戻すのは簡単です。 ```sh (my-branch)$ git reset --hard ORIG_HEAD ``` ### リベヌスしたが、匷制プッシュはしたくない 残念ながら、線集内容をリモヌトブランチに反映させるには匷制プッシュをする必芁がありたす。線集履歎を倉えおしたったからです。 匷制プッシュしない限りリモヌトブランチは線集内容を受け付けたせん。 これが倚くの人がリベヌスワヌクフロヌではなくマヌゞワヌクフロヌを䜿う䞻な理由です。 特に倧芏暡な開発チヌムは誰かの匷制プッシュでハマりやすいです。 リベヌスの匷制プッシュは泚意しお䜿いたしょう。 リベヌスを䜿う安党な方法は、リモヌトには線集内容を反映させず、代わりに次を実行するこずです ```sh (master)$ git checkout my-branch (my-branch)$ git rebase -i master (my-branch)$ git checkout master (master)$ git merge --ff-only my-branch ``` 詳しくは[この StackOverflow スレッド](https://stackoverflow.com/questions/11058312/how-can-i-use-git-rebase-without-requiring-a-forced-push)を参照しおください。 ### コミットを統合したい `master` ブランチにプルリク゚ストを送る、たたはこれから送る぀もりのブランチで䜜業しおいるずしたしょう。 最も単玔なケヌスずしお、タむムスタンプを気にせず**党郚の**コミットを䞀぀にたずめおしたいたいずしたす。この堎合はリセットず再コミットを行いたす。 マスタヌブランチが最新版で、線集内容がすべおコミットされおいるこずを確認した䞊で、次を実行したす ```sh (my-branch)$ git reset --soft master (my-branch)$ git commit -am "New awesome feature" ``` もっず现かく蚭定し、タむムスタンプも残したい堎合は、察話的リベヌスず呌ばれるものを䜿うたす ```sh (my-branch)$ git rebase -i master ``` 別のブランチで䜜業しおいるわけではない堎合は、`HEAD` に察しおリベヌスする必芁がありたす。たずえば盎近二件のコミットを圧瞮 (squash) したい堎合は `HEAD~2`、盎近䞉件なら `HEAD~3` です。 ```sh (master)$ git rebase -i HEAD~2 ``` 察話的リベヌスのコマンドを実行したら、テキスト゚ディタに次のように衚瀺されたす ```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 ``` ここで `#` から始たる行はコメントなので、リベヌスに圱響したせん。 `pick` コマンドをリストにある奜きなコマンドで眮き換えればよいです。行を削陀すればコミットを削陀できたす。 䟋えば、**䞀番叀い䞀番目のコミットはそのたた残し、他のコミット党おを二番目のコミットに統合したい**堎合は、最初ず二番目のコミット以倖のコミットの暪に衚瀺された文字を䟋えば `f` に修正したす ```vim pick a9c8a1d Some refactoring pick 01b2fd8 New awesome feature f b729ad5 fixup f e3851e8 another fix ``` コミットを統合し、**さらに名前も倉曎したい**堎合は、二番目のコミットの暪にさらに `r` の文字を远加するか、あるいは単に `f` の代わりに `s` を䜿いたす ```vim pick a9c8a1d Some refactoring pick 01b2fd8 New awesome feature s b729ad5 fixup s e3851e8 another fix ``` するずテキスト゚ディタが起動し、コミットの名前を倉曎できたす。 ```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 'master' on '8074d12'. # # Changes to be committed: # modified: README.md # ``` うたくいくず次のように衚瀺されるはずです ```sh (master)$ Successfully rebased and updated refs/heads/master. ``` #### 安党なマヌゞの方法 `--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 (master)$ git merge --no-ff --no-commit my-branch ``` オプション `--no-commit` を指定するず、マヌゞを実行し぀぀、あたかもマヌゞが倱敗したかのように扱っお自動コミットはしたせん。これにより、コミットの前にマヌゞの結果を粟査したり調敎できたす。オプション `no-ff` はフィヌチャヌブランチが存圚したこずを蚘録しおおき、プロゞェクト履歎の䞀貫性を保ちたす。 #### ブランチを䞀぀のコミットにたずめたい堎合 ```sh (master)$ git merge --squash my-branch ``` #### プッシュされおいないコミットのみを統合したい堎合 進行䞭の䜜業に関するコミットがいく぀かあっお、upstream にコミットする前に統合しおおきたいこずがあるでしょう。 すでに upstream にプッシュされたコミットは、誰かがそれを参照するコミットをしおいる可胜性があるので、それは統合しないでおきたいずしたす。 ```sh (master)$ git rebase -i @{u} ``` 䞊を実行するず察話的リベヌスが始たりたすが、䞀芧にはただプッシュされおいないコミットだけが衚瀺されたす。これで順番を入れ替えたり、修正したり、圧瞮 (squash) したりしおも安党です。 #### マヌゞを䞭止したい マヌゞがファむルに問題をきたすこずがありたす。 こういうずきはオプション `abort` を䜿うずコンフリクト解消の䜜業を䞭止し、マヌゞの前の状態の埩元を詊みるこずができたす。 ```sh (my-branch)$ git merge --abort ``` ただし、このコマンドが䜿えるのはバヌゞョン 1.7.4 以䞊の Git です。 ### ブランチの芪コミットを曎新したい マスタヌブランチずそこから分岐した feature-1 ブランチがあり、feature-1 からさらに分岐した feature-2 ブランチがあるずしたす。 今 feature-1 ブランチにコミットしたずするず、feature-2 ブランチの芪コミットはもはや正確ではありたせんfeature-1 から分岐したので、芪コミットは feature-1 ブランチの head であるべきです。 こういうずきは `git rebase --onto` で修正できたす。 ```sh (feature-2)$ git rebase --onto feature-1 feature-2 ``` ただマヌゞされおいないブランチからフィヌチャヌブランチを分岐させおおり、feature-1 ブランチのバグ修正を feature-2 に反映させたいずきに䟿利です。 ### ブランチの党コミットがマヌゞされおいるか確認する ブランチの党おのコミットが別のブランチにマヌゞされたか確認するには、それぞれのブランチの headあるいは任意のコミットの間の差分を衚瀺したす ```sh (master)$ git log --graph --left-right --cherry-pick --oneline HEAD...feature/120-on-scroll ``` 䞀方のブランチにしかないコミットがあるか衚瀺され、ブランチの間で共有されおいないコミットの䞀芧がわかりたす。 もう䞀぀の方法は ```sh (master)$ git log master ^feature/120-on-scroll --no-merges ``` ### 察話的リベヌスで起こりうる問題 #### リベヌス線集画面に 'noop' ず衚瀺される 次のように衚瀺されたずしたす ``` noop ``` これは、同じコミットのブランチ、あるいは珟圚のブランチよりも*先*にあるブランチに察しおリベヌスしようずしたずきに衚瀺されるものです。こういう堎合は * マスタヌブランチが正しい堎所にあるこずを確認しおください。 * `HEAD~2` あるいはより以前にリベヌスしおください。 #### コンフリクトがあった リベヌスができないずきは、解消すべきコンフリクトがあるかもしれたせん。 たず `git status` で、どのファむルがコンフリクトを起こしおいるか確認したす ```sh (my-branch)$ git status On branch my-branch Changes not staged for commit: (use "git add ..." to update what will be committed) (use "git checkout -- ..." to discard changes in working directory) both modified: README.md ``` この䟋では `README.md` がコンフリクトをきたしおいたす。ファむルを開き、次のようになっおいる郚分を芋おみたしょう ```vim <<<<<<< HEAD some code ========= some code >>>>>>> new-commit ``` `HEAD` ず新しいコミットで加えられたコヌドの間の差分この䟋では、真ん䞭の行から `new-commit` たでの間にあるコヌドを解消する必芁がありたす。 䞀方のブランチの版のコヌドを残したい堎合は、`--ours` あるいは `--theirs` を指定したす。 ```sh (master*)$ git checkout --ours README.md ``` - *マヌゞする*堎合、ロヌカルブランチの線集内容を残したいずき `--ours` を指定し、他方の線集内容を残したいずき `--theirs` を指定したす。 - *リベヌスする*堎合、ロヌカルブランチの線集内容を残したいずき `--theirs` を指定し、他方の線集内容を残したいずき `--ours` を指定したす。このように逆転する理由は[Git ドキュメントのこのノヌト](https://git-scm.com/docs/git-rebase#git-rebase---merge)を参照しおください。 マヌゞがもっず耇雑な堎合はノィゞュアル差分゚ディタを䜿うこずができたす ```sh (master*)$ git mergetool -t opendiff ``` コンフリクトを党お解消し、コヌドのテストが枈んだら、`git add ` で線集内容をステヌゞし、`git rebase --continue` でリベヌスを再開したす。 ```sh (my-branch)$ git add README.md (my-branch)$ git rebase --continue ``` コンフリクトを解消した結果、ワヌキングツリヌがコミット前ず党く同じ状態になった堎合は、代わりに `git rebase --skip` を実行したす。 リベヌス䜜業を党お䞭止し、ブランチを元の状態に差し戻したい堎合は、次のようにしたす ```sh (my-branch)$ git rebase --abort ``` ## スタッシュ ### 党おの線集内容をスタッシュしたい ワヌキングディレクトリの党おの線集をスタッシュするには、次を実行したす ```sh $ git stash ``` バヌゞョン管理されおいないファむルもスタッシュしたい堎合は、オプション `-u` を指定したす。 ```sh $ git stash -u ``` ### 特定のファむルをスタッシュしたい ワヌキングディレクトリのファむル䞀぀をスタッシュするには、次を実行したす ```sh $ git stash push working-directory-path/filename.ext ``` ワヌキングディレクトリの耇数のファむルをスタッシュする堎合は次の通りです。 ```sh $ git stash push working-directory-path/filename1.ext working-directory-path/filename2.ext ``` ### メッセヌゞを぀けおスタッシュしたい ```sh $ git stash save ``` あるいは、 ```sh $ git stash push -m ``` ### 䞀芧から特定のスタッシュを遞んで適甚したい たず、次のようにしおスタッシュの䞀芧をメッセヌゞずずもに衚瀺したす。 ```sh $ git stash list ``` そしお、次のように特定のスタッシュを遞んで適甚したす。 ```sh $ git stash apply "stash@{n}" ``` ここで、'n' は䞀芧の䞭のスタッシュの䜍眮を指したす。䞀番䞊のスタッシュなら 0 番です。 たた、時刻からスタッシュを参照するこずもできたす。 ```sh $ git stash apply "stash@{2.hours.ago}" ``` ### ステヌゞされおいない線集をそのたたにし぀぀、スタッシュしたい 手動で `stash commit` を䜜成し、`git stash store` を実行すればよいです。 ```sh $ git stash create $ git stash store -m CREATED_SHA1 ``` ## 怜玢 ### 任意のコミットから文字列を怜玢したい あるコミットで導入されたある文字列を怜玢したいずきは、次のコマンドを䜿いたす ```sh $ git log -S "string to find" ``` よく䜿われるパラメヌタは次の通り * `--source` を指定するず、コマンドラむンで぀けられた各コミットの参照名を衚瀺したす。 * `--all` は党おのブランチから怜玢したす。 * `--reverse` を指定するず逆順に衚瀺したす。すなわち、最初のコミットから衚瀺したす。 ### author たたは committer から怜玢する 党おのコミットを author たたは committer の名前から怜玢するには次の通りです ```sh $ git log --author= $ git log --committer= ``` author ず committer は異なるこずに泚意しおください。 `--author` ははじめにコヌドを曞いた人、`--committer` は author の代わりにコミットした人を指したす。 ### 特定のファむルを含むコミットの䞀芧を衚瀺したい 特定のファむルを含むコミットの䞀芧を衚瀺するには、次を実行したす。 ```sh $ git log -- ``` 通垞は正確なパスを指定したすが、パスやファむル名にワむルドカヌドを䜿うこずもできたす ```sh $ git log -- **/*.js ``` ワむルドカヌドを䜿う際は、`--name-status` を指定するずコミットされたファむルの䞀芧が衚瀺されるので䟿利です。 ```sh $ git log --name-status -- **/*.js ``` ### 特定の関数に぀いおコミット履歎を芋たい ある関数の履歎を远跡するには次を実行したす ```sh $ git log -L :FunctionName:FilePath ``` このコマンドは `git log` の他のオプション、䟋えば [revision ranges](https://git-scm.com/docs/gitrevisions) や [commit limits](https://git-scm.com/docs/git-log/#_commit_limiting) ず䞀緒に䜿うこずができたす。 ### コミットが参照されおいるタグを怜玢したい 特定のコミットを含むタグを怜玢するには次のようにしたす ```sh $ git tag --contains ``` ## サブモゞュヌル ### 党おのサブモゞュヌルをクロヌンする ```sh $ git clone --recursive git://github.com/foo/bar.git ``` すでにクロヌンしおいる堎合 ```sh $ git submodule update --init --recursive ``` ### サブモゞュヌルを削陀する サブモゞュヌルの䜜成はきわめお簡単ですが、削陀はそうでもありたせん。 削陀に必芁なコマンドは次の通りです ```sh $ git submodule deinit submodulename $ git rm submodulename $ git rm --cached submodulename $ rm -rf .git/modules/submodulename ``` ## その他色々 ### あるブランチから別のブランチにフォルダをコピヌしたい ```sh $ git checkout -- ``` ### 削陀されたファむルを埩元したい たず、ファむルが最埌にあったコミットを探したす ```sh $ git rev-list -n 1 HEAD -- filename ``` 芋぀かったら、ファむルをチェックアりトしたす ``` git checkout deletingcommitid^ -- filename ``` ### タグを削陀したい ```sh $ git tag -d $ git push :refs/tags/ ``` ### 削陀されたタグを埩元したい 削陀されたタグを埩元する手順は次の通りです。 たず、unreachable になったタグを探したす ```sh $ git fsck --unreachable | grep tag ``` タグのハッシュをメモしおおきたす。 続いお、次のように [`git update-ref`](https://git-scm.com/docs/git-update-ref) を䜿っお削陀されたタグを埩元したす ```sh $ git update-ref refs/tags/ ``` これでタグが埩元されたはずです。 ### 削陀されたパッチを取埗したい 誰かが GitHub でプルリクを送ったあずにフォヌクを削陀しおしたった堎合、そのリポゞトリをクロヌンしたり、`git am` でパッチを適甚するこずができなくなりたす。[.diff や .patch](https://github.com/blog/967-github-secrets) の URL が䜿えなくなっおしたうためです。 しかし、[GitHub 独自の参照](https://gist.github.com/piscisaureus/3342247)を䜿っお、プルリク゚スト自䜓をチェックアりトするこずができたす。 プルリク゚スト #1 の内容を新しいブランチ 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 ``` ### リポゞトリを zip ファむルずしお゚クスポヌトする ```sh $ git archive --format zip --output /full/path/to/zipfile.zip master ``` ### 同じ名前のブランチずタグをプッシュしたい ブランチず同じ名前のタグがリモヌトリポゞトリに存圚する堎合、通垞通り `$ git push ` でプッシュしようずするず、次のように゚ラヌが出たす。 ```sh $ git push origin error: dst refspec same matches more than one. error: failed to push some refs to '' ``` この゚ラヌはブランチのヘッドを指定するこずによっお回避できたす。 ```sh $ git push origin refs/heads/ ``` 同名のブランチがリモヌトリポゞトリにあるタグをプッシュしたいずきも、䌌たコマンドを䜿いたす。 ```sh $ git push origin refs/tags/ ``` ## ファむルの远跡 ### ファむルの内容は倉えずに、ファむル名の倧文字・小文字を倉曎したい ```sh (master)$ git mv --force myfile MyFile ``` ### git pull しおロヌカルのファむルを䞊曞きしたい ```sh (master)$ git fetch --all (master)$ git reset --hard origin/master ``` ### ファむルを残し぀぀ Git から削陀したい ```sh (master)$ git rm --cached log.txt ``` ### ファむルを特定の版たで差し戻したい 差し戻したいコミットのハッシュが c5f567 の堎合、次を実行したす ```sh (master)$ git checkout c5f567 -- file1/to/restore file2/to/restore ``` 差し戻したいコミットが c5f567 の䞀぀前なら、コミットハッシュに c5f567~1 を指定したす ```sh (master)$ git checkout c5f567~1 -- file1/to/restore file2/to/restore ``` ### 特定のファむルのコミット間・ブランチ間の差分を衚瀺したい コミット c5f567 ずその䞀぀前の差分を衚瀺したい堎合、次を実行したす ```sh $ git diff HEAD:path_to_file/file c5f567:path_to_file/file ``` ブランチでも同様です ```sh $ git diff master:path_to_file/file staging:path_to_file/file ``` ### 特定のファむルの倉曎を無芖したい これはコミットできない認蚌情報をロヌカル環境で远加する必芁のある蚭定テンプレヌトなどがあるずきに圹立ちたす。 ```sh $ git update-index --assume-unchanged file-to-ignore ``` ファむルがバヌゞョン管理されなくなるわけでは*ない*こずに泚意しおください。ロヌカルで無芖されるだけです。 蚭定を取り消しお倉曎を再び远跡するには、次のようにしお ignore フラッグを削陀したす ```sh $ git update-index --no-assume-unchanged file-to-stop-ignoring ``` ## Git によるデバッグ コマンド [git-bisect](https://git-scm.com/docs/git-bisect) は、どのコミットがバグをもたらしたか Git 履歎を二分探玢したす。 今 `master` ブランチにいるずしお、倱敗をやらかしたコミットを探しおみたしょう。次のようにしお二分探玢を始めたす ```sh $ git bisect start ``` 問題のあるコミットずないコミットを指定する必芁がありたす。*珟圚の*バヌゞョンに問題があり、`v1.1.1` は問題ないずしたす。 ```sh $ git bisect bad $ git bisect good v1.1.1 ``` するず `git-bisect` は遞んだバヌゞョンの䞭間のコミットを遞んで調べ、問題があるかどうか尋ねおきたす。 次のように衚瀺されるはずです ```sh $ Bisecting: 5 revision left to test after this (roughly 5 step) $ [c44abbbee29cb93d8499283101fe7c8d9d97f0fe] Commit message $ (c44abbb)$ ``` このコミットに問題があるかどうか調べたす。問題がない (good) 堎合は次を実行したす ```sh $ (c44abbb)$ git bisect good ``` するず、`git-bisect` は別のコミットを遞択したす。このように `good` か `bad` を遞んでいく䜜業は、調べるコミットがなくなるたで続きたす。 終了したら、コマンドラむンには問題をきたしおいる**最初の**コミットの詳现が衚瀺されたす。 ## 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 master && 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 want to add command line coloring for Git To set automatic command line coloring for Git for easy reviewing: ```sh $ git config --global color.ui auto ``` ## 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 (master)$ git reflog 0a2e358 HEAD@{0}: reset: moving to HEAD~2 0254ea7 HEAD@{1}: checkout: moving from 2.2 to master c10f740 HEAD@{2}: checkout: moving from master to 2.2 ``` The reflog above shows a checkout from master 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 master pointed to (0254ea7) before you accidentally dropped 2 commits. ```sh $ git reset --hard 0254ea7 ``` Using `git reset` it is then possible to change master 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)). ## 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/sites/default/files/atoms/files/nasa_systems_engineering_handbook.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. * [Learn Git branching](https://learngitbranching.js.org/) An interactive web based branching/merging/rebasing tutorial * [Getting solid at Git rebase vs. merge](https://medium.com/@porteneuve/getting-solid-at-git-rebase-vs-merge-4fa1a48c53aa) * [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 * [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.