Git cheat sheet

基本操作

github で repository つくったら手順がでてくる

mkdir hoge
cd hoge
git init
touch README.md
git add README.md
git commit -m 'first commit'
git remote add origin git@github.com:fuga/hoge.git
git push -u origin master

編集後

git add README.md
git commit -m 'message here'
git push

rename

git mv README.md README
git commit -m 'message here'
git push

fork して放置したリポジトリを元のリポジトリと合わせる

git pull 元のリポジトリ master
git push

ブランチを切る

git checkout -b my_new_branch

ブランチを push

git push origin my_new_branch

規定値もろもろ

git config --global user.email foo@bar
git config --global user.name "John Doe"
git config --global core.editor emacs

プルリクエストのパターン

github上でfork
そいつを git clone

現在のブランチを確認すること

git checkout master
git checkout -b 作業内容がよく分かるブランチ名

変更を加えてコミット・Signed-off-by 付ける(openwrtとかは)

git commit -s -m '完結な説明'
git push origin 作業内容がよく分かるブランチ名
github上でプルリクエスト

無事マージされたら作業ブランチを消す

git branch -d 作業内容がよく分かるブランチ名

マージされなっかった作業ブランチを消す

git branch -D 作業内容がよく分かるブランチ名

githubの該当ブランチを消す

git push origin :作業内容がよく分かるブランチ名


元のリポジトリのコミットを追いかける

git remote add upstream 元のリポジトリ
git checkout master
git pull upstream master

元のリポジトリの新ブランチを追っかける

git fetch upstream
git checkout 新ブランチ
git push origin 新ブランチ


git checkout 作業ブランチ
git rebase master 作業ブランチ

実用編

commit コメントメッセージ間違ったので直前の commit 取り消したい

git log
git reset --hard HEAD^
git log

直前のコミットをやり直し。というかcommitメッセージの書き換え。

git commit --amend

git diff に新規追加ファイルを含める

# 新規ファイル作る
git add -N 新規ファイルフルパス
git diff

squash と言われた場合

git log --oneline
git rebase -i HEAD~X (X = number of commits to edit)
# 先頭行以外 pick -> squash
# セーブ
# コメントを編集
# セーブ
git push -f
# こちらが安全なのかな git push --force-with-lease

過去の commitメッセージの書き換え。

git log
# 書き換えるcommitの直下のhash
git rebase -i 直下のhash
# 先頭を pick -> edit
# セーブ
git commit --amend 
# コメントを編集
# セーブ
git rebase --continue
git push -f
# こちらが安全なのかな git push --force-with-lease

PR送信してマージされた後の開発ブランチをマスターに同期

git checkout master
git pull
git checkout my-dev
git rebase master
git push

PR送信したあとマージされる前で、アップストリーム・マスターの自分のPR以外の更新を取り込む。

git checkout master
git pull upstream master
git push
git checkout my-dev
git rebase master
git push --force-with-lease


upstream に新しいブランチが切られた際に、それをフォークに反映

git fetch upstream
git checkout -b new_branch upstream/new_branch
git push -u origin new_branch

いわゆる backport

git checkout 対象ブランチ
git checkout -b 修正用ブランチ名
git cherry-pick -x <commit_hash>
git push -u origin 修正用ブランチ名
# そして PR

複数のcherrypick。注意点は開始点の指定が一つ前になるので直感的でなく、そのために"^"をつける癖をつけたほうがよい。

git log --oneline
git cherry-pick -x {COMMIT-A}^..{COMMIT-Z}

作業ミスして upstream と強制同期

git fetch upstream 
git reset --hard upstream/master

タグ名でブランチ作成

git tag
git checkout -b 新ブランチ名 refs/tags/タグ名