0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

複雑な状況でない場合の誤ってGitHubにプッシュしてしまった場合の対処法

Last updated at Posted at 2024-08-04

概要

  • 時々やらかして、いろいろ調べることになるので簡単にまとめる

複雑でない状況とは

  1. 誰も誤ってプッシュしてしまったブランチを利用していない

対処法

危険な操作もあるため、バックアップを取ってから実行することをお勧めします

間違ってプッシュしたコミットを元のブランチから変更を戻す

git checkout original-branch-name
# 変更維持した状態で戻す
git reset --mixed HEAD^

HEAD^は直前のコミットを指すので、複数のコミットを戻す場合は、HEAD~nを使用するとよい(nは戻したいコミット数)。

ローカルで新しいブランチを作成する

git checkout -b new-branch-name

新しいブランチに変更をコミットしてプッシュする

git checkout new-branch-name
git add .  # 全ての変更をステージングエリアに追加
git commit -m "新しいブランチでの変更内容の説明"
git push -u origin new-branch-name

元のブランチをローカルの状態で強制上書きする

git push --force の操作は危険が伴うため、十分に注意してください

より安全な方法をより安全な方法で強制上書きで書いておきます

git checkout original-branch-name
git push --force origin original-branch-name

より安全な強制上書き

@YuneKichiさんから教えていただきました!ありがとうございます!

git push --forceよりはgit push --force-with-lease、さらにはgit push --force-with-lease --force-if-includesを使うと、より安全になります。

とのことで、オプションをつけることでより安全になるようです!

簡単にどのようなオプションであるかを調べてみると、

--force-with-lease オプションを指定すると、ローカルの ref とリモートの ref を比較しローカルが最新か判定。最新なら push し、そうでなければが失敗してくれるので、誤って古いファイルで上書きといった悲惨な状態を回避できるようになる。

--force-if-includes オプションは、reflog に remotes/origin/main (I) が含まれていることをチェックし、直前fetch状態なら拒否してくる仕組み。

--force-with-lease オプションだけでは、直前にfetchしていると push が成功してしまうので、
--force-if-includes オプションを併用すると更に安全に行えるというのがポイント。

とのことでした。なので次のようになります

git checkout original-branch-name
git push --force-with-lease --force-if-includes origin original-branch-name

エイリアスの設定もしておくとよいとのことです

0
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?