1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Git のブランチを削除したいが、後で復元できるようにしたい

Last updated at Posted at 2025-02-13

やりたいこと

Git のブランチを削除したいが、後で復元できるようにしたい。つまりブランチをアーカイブするようなことがしたいです。

「main ブランチにマージできないブランチがたくさん溜まっているので、それらを整理するために削除したい。でもこれまでの変更はなかったことにしたくない」と思うことがあり、何か方法がないか調べてみました。

方法

git update-ref コマンドでアーカイブ専用の参照 (refs)1 を作成します。以下のコマンドで feature/cat ブランチの最新のコミットを指す refs/archive/feature/cat という新しい参照を作成します。

$ git update-ref refs/archive/feature/cat feature/cat

作成した参照の一覧は git for-each-ref コマンドで取得できます。

$ git for-each-ref refs/archive # refs/archive/* の一覧を取得する
9650b007b7b5a1d3302556b9ecbb80a96c777218 commit	refs/archive/feature/cat
9650b007b7b5a1d3302556b9ecbb80a96c777218 commit	refs/archive/feature/dog

このように参照を作成しておくと、feature/cat ブランチを削除した後でも refs/archive/feature/cat という参照からブランチを復元することができます。

$ git -d feature/cat # feature/cat ブランチを削除する
$ git branch feature/cat refs/archive/feature/cat # 参照からブランチを復元する
$ git update-ref -d refs/archive/feature/cat # 参照を削除する

おまけ

Git の設定ファイル (~/.gitconfig) に以下の alias を定義すると便利です。

[alias]
  archive-branch = "!sh -c 'git update-ref refs/archive/$1 $1 && git branch -D $1' -"
  show-archive = "!sh -c 'git for-each-ref refs/archive' -"
  restore-branch-from-archive = "!sh -c 'git branch $1 refs/archive/$1 && git update-ref -d refs/archive/$1' -"

バージョン情報

$ git --version
git version 2.39.5 (Apple Git-154)

参考

  1. 「そもそも参照 (refs) って何?」という方は Git - Git の参照 を読んでみてください。

1
3
0

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
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?