在 Git 中删除分支后可以恢复吗?

发布于 2024-09-17 12:26:14 字数 63 浏览 6 评论 0原文

如果我运行 gitbranch -d XYZ ,有没有办法恢复分支?有没有办法像我没有运行删除分支命令一样返回?

If I run git branch -d XYZ, is there a way to recover the branch? Is there a way to go back as if I didn't run the delete branch command?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(26

深海夜未眠 2024-09-24 12:26:15

首先

git reflog

在终端中输入。

之后,获取HEAD@{**number**}(例如HEAD@{12})。

现在输入:

git checkout -b 'branch_name' 'HEAD@{22}'

First type

git reflog

in the terminal.

After that, get the HEAD@{**number**} (e.g. HEAD@{12}).

Now enter:

git checkout -b 'branch_name' 'HEAD@{22}'
缱倦旧时光 2024-09-24 12:26:15

添加到 tfe答案:还有 git-resurrect.sh contrib/ Git 源代码区域(在 git.git 存储库中),这可能会对您有所帮助。

git-resurrect 尝试查找分支尖端的痕迹
称为,并尝试复活它。目前,重新记录是
搜索结帐消息,并使用 -r 还合并消息。和
-m-t,扫描所有引用的历史记录以查找 Merge进入
other
/合并进入 (分别)提交主题,其中
虽然很慢但是可以让你复活别人的话题
分支。

Adding to tfe answer: there is also the git-resurrect.sh script in the contrib/ area of the Git sources (in git.git repository), which might help you.

git-resurrect <name> attempts to find traces of a branch tip
called <name>, and tries to resurrect it. Currently, the reflog is
searched for checkout messages, and with -r also merge messages. With
-m and -t, the history of all refs is scanned for Merge <name> into
other
/Merge <other> into <name> (respectively) commit subjects, which
is rather slow but allows you to resurrect other people's topic
branches.

征﹌骨岁月お 2024-09-24 12:26:15

我使用以下命令来查找并检索已删除的分支。第一步来自 gcb 的描述。

$ git fsck --full --no-reflogs --unreachable --lost-found > lost
$ cat lost | cut -d\  -f3 > commits
$ cat commits | xargs -n 1 git log -n 1 --pretty=oneline

现在根据提交注释查找 git 提交 ID (GIT-SHA) 并在下面的命令中使用它。使用之前找到的 GIT-SHA 检查一个名为 NEW-BRANCH 的新分支:

$ git checkout -b NEW-BRANCH GIT-SHA

I used the following commands to find and retrieve my deleted branch. The first steps are from gcb's description.

$ git fsck --full --no-reflogs --unreachable --lost-found > lost
$ cat lost | cut -d\  -f3 > commits
$ cat commits | xargs -n 1 git log -n 1 --pretty=oneline

Now look for the git commit id (GIT-SHA) based on the commit comments and use it in the command below. Checkout a new branch called NEW-BRANCH with the previously found GIT-SHA:

$ git checkout -b NEW-BRANCH GIT-SHA
梦里南柯 2024-09-24 12:26:15

谢谢大家。

我的问题是我删除了 GitLab(远程)和 GIT(本地)上的分支。

但不知怎的,我像这样拿回了我的提交:

  1. 首先我得到了最后一次提交(SHA),
git log --graph --decorate $(git rev-list -g --all)

  1. 然后
git checkout <SHA>
  1. 我通过输入创建了一个全新的分支(根据您的喜好命名)
git switch -c <branch-name> 

然后我拿回了我的提交我推送了分支感谢

上帝。

ps:不知何故(SHA)是提交代码

Thanks for all of you.

My problem was that i deleted my branch on GitLab (remotely) as well as on GIT (locally).

but somehow i got my commits back like so:

  1. first i got the last commit (SHA) with
git log --graph --decorate $(git rev-list -g --all)

  1. i checkout last SHA simply
git checkout <SHA>
  1. then i created a brand new branch (named as you prefer) by typing
git switch -c <branch-name> 

Then i got my commits back i pushed the branch all over again

Thank god.

ps: Somehow (SHA) is a commit code

策马西风 2024-09-24 12:26:15

如果您没有重新记录,例如。因为您正在一个未启用引用日志的裸存储库中工作,并且您要恢复的提交是最近创建的,所以另一个选择是查找最近创建的提交对象并查看它们。

.git/objects 目录中运行:

find . -ctime -12h -type f | sed 's/[./]//g' | git cat-file --batch-check | grep commit

这会查找过去 12 小时内创建的所有对象(提交、文件、标签等)并过滤它们以仅显示提交。检查这些是一个快速的过程。

不过,我会首先尝试Jakub的答案中提到的 git-ressurect.sh 脚本。

If you don't have a reflog, eg. because you're working in a bare repository which does not have the reflog enabled and the commit you want to recover was created recently, another option is to find recently created commit objects and look through them.

From inside the .git/objects directory run:

find . -ctime -12h -type f | sed 's/[./]//g' | git cat-file --batch-check | grep commit

This finds all objects (commits, files, tags etc.) created in the last 12 hours and filters them to show only commits. Checking these is then a quick process.

I'd try the git-ressurect.sh script mentioned in Jakub's answer first though.

×纯※雪 2024-09-24 12:26:15

据我了解,如果要删除的分支可以被另一个分支访问,您可以使用安全地删除它

git branch -d [branch]

,并且您的工作不会丢失。请记住,分支不是快照,而是指向快照的指针。因此,当您删除分支时,您也会删除一个指针。

如果您删除另一个分支无法访问的分支,您甚至不会丢失工作。当然,这不像检查提交哈希那么容易,但您仍然可以做到。这就是为什么 Git 无法删除使用 -d 无法到达的分支。相反,你必须使用

git branch -D [branch]

这是 Scott Chacon 的有关 Git 的必看视频的一部分。查看 58:00 分钟,他谈论分支以及如何删除它们。

GitHub 的 Scott Chacon 介绍 Git

From my understanding if the branch to be deleted can be reached by another branch, you can delete it safely using

git branch -d [branch]

and your work is not lost. Remember that a branch is not a snapshot, but a pointer to one. So when you delete a branch you delete a pointer.

You won't even lose work if you delete a branch which cannot be reached by another one. Of course it won't be as easy as checking out the commit hash, but you can still do it. That's why Git is unable to delete a branch which cannot be reached by using -d. Instead you have to use

git branch -D [branch]

This is part of a must watch video from Scott Chacon about Git. Check minute 58:00 when he talks about branches and how delete them.

Introduction to Git with Scott Chacon of GitHub

草莓酥 2024-09-24 12:26:15

对于未安装 Git 的 GitHub 用户:

如果您想从<恢复它a href="https://github.com/Maxim-Mazurok" rel="nofollow noreferrer">GitHub 网站,您可以使用他们的 API 获取与 repo 相关的列表事件:

首先

  • 找到那些 SHA(提交哈希值):

    curl -i https://api.github.com/repos/PublicUser/PublicRepo/events

    ...或私人仓库:

    curl -su YourUserName https://api.github.com/repos/YourUserName/YourProject/events

    (将提示输入 GitHub 密码)

    • (如果存储库需要双因素身份验证,请参阅下面对此答案的评论。)

下一步

  • 转到 GitHub 并创建一个新的临时分支,该分支将永久删除(最好使用 Chrome)。

    • 转至分支并删除该分支。

    • 在同一页面上,无需重新加载,打开 DevTools、网络面板。现在准备...

   • 单击恢复。您会注意到一条新的“线”。右键单击它并选择“复制为 cURL”并将此文本保存在某个编辑器中。

    • 附加到复制的代码行的末尾,这一个:-H "Cookie="

您现在应该得到类似的结果:

    curl 'https://github.com/UserName/ProjectName/branches?branch=BranchSHA&name=BranchName' -H 'Cookie:' -H 'Origin: https://github.com' -H 'Accept-Encoding: gzip, deflate, br' -H 'Accept-Language: en-US' -H 'User-Agent: User-Agent' -H 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8' -H 'Accept: */*' -H 'Referer: https://github.com/UserName/ProjectName/branches' -H 'X-Requested-With: XMLHttpRequest' -H 'Connection: keep-alive' --data 'utf8=%E2%9C%93&authenticity_token=token' --compressed

最后一步

  • 将“BranchSHA”替换为您的 SHA 哈希值,并将 BranchName 替换为所需的名称(顺便说一句,从网络重命名分支是一个很棒的技巧)。如果你不是太慢的话,无论如何你都需要提出这个请求。例如,只需复制粘贴到终端即可。

PS

我意识到这可能不是“最简单的解决方案”或“正确的”解决方案,但提供它是为了以防万一有人发现它有用。

For GitHub users without Git installed:

If you want to restore it from GitHub website, you can use their API to get a list of repo-related events:

First

  • find those SHAs (commit hashes):

    curl -i https://api.github.com/repos/PublicUser/PublicRepo/events

    ... or for private repos:

    curl -su YourUserName https://api.github.com/repos/YourUserName/YourProject/events

    (will be prompted for GitHub password)

    • (If the repo rquires two-factor auth, see the comments on this answer below.)

Next

  • go to GitHub and create a new temporary branch which will be deleted for ever (Chrome is preferable).

   •  Go to branches and delete that one.

   •  On the same page, without reloading, open DevTools, Network panel. Now prepare...

   •  Click restore. You will notice a new "line". Right-click on it and select "Copy as cURL" and save this text in some editor.

   •  Append to the end of the copied line of code, this one: -H "Cookie=".

You should now get something like:

    curl 'https://github.com/UserName/ProjectName/branches?branch=BranchSHA&name=BranchName' -H 'Cookie:' -H 'Origin: https://github.com' -H 'Accept-Encoding: gzip, deflate, br' -H 'Accept-Language: en-US' -H 'User-Agent: User-Agent' -H 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8' -H 'Accept: */*' -H 'Referer: https://github.com/UserName/ProjectName/branches' -H 'X-Requested-With: XMLHttpRequest' -H 'Connection: keep-alive' --data 'utf8=%E2%9C%93&authenticity_token=token' --compressed

Final step

  • replace "BranchSHA" with your SHA-hash and BranchName with desired name (BTW, it is great hack to rename branch from web). If you were not too slow, you need to make this request anyhow. For example, just copy-paste to a terminal.

P.S.

I realize this may not be the "simplest solution" or the "right" solution, but it is offered in case someone finds it useful.

離殇 2024-09-24 12:26:15

确保在本地执行所有这些操作,并在推送到 Bitbucket Cloud 之前确认您的存储库处于您想要的状态。克隆当前存储库并首先测试这些解决方案也可能是个好主意。

  1. 如果您刚刚删除了分支,您将在终端中看到类似以下内容:
    Deleted branch <your-branch> (was <sha>)

2.要恢复分支,请使用:

    git checkout -b <branch> <sha>

如果您不知道“sha”,您可以:

  1. 在已删除分支的顶端查找提交的“sha”:
    git reflog
  1. 要恢复分支,请使用:
    git checkout -b <branch> <sha>

如果您的提交不在引用日志中:

  1. 您可以尝试恢复分支通过使用以下命令将分支重置为找到的提交的 sha:
    git fsck --full --no-reflogs --unreachable --lost-found | grep commit | cut -d\  -f3 | xargs -n 1 git log -n 1 --pretty=oneline > .git/lost-found.txt

2.然后,您可以使用以下命令之一显示每个提交:

    git log -p <commit>
    git cat-file -p <commit>

Make sure to perform all of this locally, and confirm your repo is in the state you desire before pushing to Bitbucket Cloud. It may also be a good idea to clone your current repo, and test these solutions out first.

  1. If you just deleted the branch, you'll see something like this in your terminal:
    Deleted branch <your-branch> (was <sha>)

2.To restore the branch, use:

    git checkout -b <branch> <sha>

If you don't know the 'sha' off the top of your head, you can:

  1. Find the 'sha' for the commit at the tip of your deleted branch using:
    git reflog
  1. To restore the branch, use:
    git checkout -b <branch> <sha>

If your commits are not in your reflog:

  1. You can try recovering a branch by reseting your branch to the sha of the commit found using a command like:
    git fsck --full --no-reflogs --unreachable --lost-found | grep commit | cut -d\  -f3 | xargs -n 1 git log -n 1 --pretty=oneline > .git/lost-found.txt

2.You can then display each commit using one of these:

    git log -p <commit>
    git cat-file -p <commit>
╰ゝ天使的微笑 2024-09-24 12:26:15

要恢复已删除的分支,首先要查看引用日志历史记录,

git reflog -n 60

其中 n 指的是最后 n 次提交。然后找到合适的头并用该头创建一个分支。

git branch testbranch HEAD@{30}

For recovering a deleted branch, First go through the reflog history,

git reflog -n 60

Where n refers to the last n commits. Then find the proper head and create a branch with that head.

git branch testbranch HEAD@{30}
微凉徒眸意 2024-09-24 12:26:15

我从远程重新建立了一个分支,尝试清除一些我不想要的提交,并打算挑选我想要的正确的提交。当然,我写的 SHA 是错误的...

这是我找到它们的方法(主要是这里答案中的一个更简单的界面/交互):

首先,在日志中生成松散提交的列表。尽快执行此操作并停止工作,因为这些可能会被垃圾收集器倾倒。

git fsck --full --no-reflogs --unreachable --lost-found > lost

这将创建一个 lost 文件,其中包含您必须查看的所有提交。为了简化我们的生活,让我们只从中删除 SHA:

cat lost | cut -d\  -f3 > commits

现在您有一个 commits 文件,其中包含您必须查看的所有提交。

假设您使用的是 Bash,最后一步:

for c in `cat commits`; do  git show $c; read; done

这将向您显示每个文件的差异和提交信息。然后等待您按 Enter。现在写下您想要的所有内容,然后将它们挑选出来。完成后,只需按 Ctrl-C 即可。

I rebased a branch from remote to try to clear a few commits I didn't want and was going to cherrypick the right ones that I wanted. Of course I wrote the SHAs wrong...

Here is how I found them (mostly an easier interface/interaction from things on answers here):

First, generate a list of loose commits in your log. Do this as soon as possible and stop working, as those may be dumped by the garbage collector.

git fsck --full --no-reflogs --unreachable --lost-found > lost

This creates a lost file with all the commits you will have to look at. To simplify our life, let's cut only the SHA from it:

cat lost | cut -d\  -f3 > commits

Now you have a commits file with all the commits you have to look.

Assuming you are using Bash, the final step:

for c in `cat commits`; do  git show $c; read; done

This will show you the diff and commit information for each of them. And wait for you to press Enter. Now write down all the ones you want, and then cherry-pick them in. After you are done, just Ctrl-C it.

叶落知秋 2024-09-24 12:26:15

恢复已删除分支的一般问题的一个非常常见的子问题是在合并后恢复功能分支,然后将其删除 - 这是常见的做法。

正如这篇 SO post 所涵盖的那样,您始终可以恢复已删除的分支,如果它已经合并成功。这是因为分支只是指向提交的奇特指针,并且因为您已经合并,所以提交仍然存在。合并提交将列出两个(或更多)合并分支的头提交的哈希值。例如:

        git show master
        commit 849675951d41497e7b07d34096ebf36dc713221 (HEAD -> master)
        Merge: fc1c9ce 97f8a60
        Author: Me
        Date:   Sun Jan 9 16:14:24 2022 +0100

            Merge branch 'feature'

因此您可以通过执行 git checkout -b feature 97f8a60 来恢复删除的“feature”分支 - 不需要任何引用日志内容。

A very common sub problem of the general problem of recovering deleted branches is recovering a feature branch after merging and then deleting it - as is common practice.

As this SO post covers you can always recover a deleted branch if it has been merged successfully. This is because a branch is just a fancy pointer to a commit and because you've merged, the commit is still there. A merge commit will list the hash of the head commits of the two (or more) branches merged. For example:

        git show master
        commit 849675951d41497e7b07d34096ebf36dc713221 (HEAD -> master)
        Merge: fc1c9ce 97f8a60
        Author: Me
        Date:   Sun Jan 9 16:14:24 2022 +0100

            Merge branch 'feature'

So you can recover the delete 'feature' branch by doing git checkout -b feature 97f8a60 - no need for any reflog stuff.

笛声青案梦长安 2024-09-24 12:26:15

我在删除分支的计算机上执行了此操作:

git reflog

响应:

74b2383 (develope) HEAD@{1}: checkout: moving from master to develope
40ef328 (HEAD -> master, origin/master, origin/HEAD) HEAD@{2}: checkout: moving from develope to master
74b2383 (develope) HEAD@{3}: checkout: moving from master to develope
40ef328 (HEAD -> master, origin/master, origin/HEAD) HEAD@{4}: reset: moving to HEAD
40ef328 (HEAD -> master, origin/master, origin/HEAD) HEAD@{5}: clone: from http://LOCALGITSERVER/myBigProject/Android.git

并使用以下命令检索分支:

git checkout -b newBranchName 74b2383

I did this on the computer which i delete the branch:

git reflog

response:

74b2383 (develope) HEAD@{1}: checkout: moving from master to develope
40ef328 (HEAD -> master, origin/master, origin/HEAD) HEAD@{2}: checkout: moving from develope to master
74b2383 (develope) HEAD@{3}: checkout: moving from master to develope
40ef328 (HEAD -> master, origin/master, origin/HEAD) HEAD@{4}: reset: moving to HEAD
40ef328 (HEAD -> master, origin/master, origin/HEAD) HEAD@{5}: clone: from http://LOCALGITSERVER/myBigProject/Android.git

and i retrieve the branch with this command:

git checkout -b newBranchName 74b2383

剪不断理还乱 2024-09-24 12:26:15

如果您正在使用 GitHub(我假设这里的绝大多数读者都是如此),那么您可以按照以下三个步骤操作,不需要命令行访问:

  1. 单击 活动

突出显示活动链接的示例 GitHub 存储库

  1. 选择所有活动下拉列表,然后单击分支删除

GitHub 存储库的活动页面,其中包含“所有活动”下拉菜单中突出显示“分支删除”选项。

  1. 单击三点菜单以选择恢复分支

GitHub 存储库活动页面,其中从三点菜单中选择了“恢复分支”选项。

If you're using GitHub (which I'm assuming the vast majority of readers here are), then you can follow these three steps that doesn't require command-line access:

  1. Click on Activity:

A sample GitHub repository with the Activity link highlighted

  1. Select the All activity dropdown and click Branch deletions:

The activity page of a GitHub repo with the Branch Deletions option highlighted in the All Activity dropdown menu.

  1. Click the triple dots menu to the select Restore Branch:

A GitHub repository activity page with the Restore Branch option selected from the triple dot menu.

多情出卖 2024-09-24 12:26:15

BIG YES

如果你使用 GIT
按照这些简单的步骤操作
https://confluence.atlassian .com/bbkb/how-to-restore-a-deleted-branch-765757540.html

如果您正在使用 smartgit 并已经推送该分支
转到原点,找到该分支并右键单击然后结帐

BIG YES

if you are using GIT
follow these simple steps
https://confluence.atlassian.com/bbkb/how-to-restore-a-deleted-branch-765757540.html

if you are using smartgit and already push that branch
go to origin, find that branch and right click then checkout

魔法少女 2024-09-24 12:26:15

如果您正在使用 Git 扩展

虽然很旧,但当您在 ​​google 上搜索恢复已删除的分支时,此线程位于列表的顶部。我使用 git 扩展而不是命令行,所以不熟悉这些命令,但是 reflog 命令给了我一个线索,所以我在这里发布我的 git 扩展解决方案,供其他使用 git 扩展的人使用读这个。

  1. 转到工具栏上的“查看”下拉菜单,
  2. 选择“显示引用日志引用”

您删除的分支现在应该可以查看和选择,只需单击它并查看即可。

If you are using Git Extensions

Although old, this thread is the top of the list when you google recovering deleted branches. I use git extensions rather than the command line and so am unfamiliar with the commands but the reflog command gave me a clue so I'm posting my git extensions solution here for others that are using git extensions who may read this.

  1. Go to the view dropdown on the tool bar
  2. Select Show reflog references

Your deleted branch should now be viewable and selectable, simply click on it and check it out.

山田美奈子 2024-09-24 12:26:15

首先转到 git 批处理移动到您的项目,如下所示:

cd android studio project
cd Myproject
then type :
git reflog

您都有一个更改列表,并且参考号采用参考号,然后从 android studio 或 git betcha 结帐。
另一个解决方案是获取参考号并转到 android studio,单击 git 分支,然后单击结帐标签或修订版参考号,然后哈哈,您就拥有了分支。

First go to git batch the move to your project like :

cd android studio project
cd Myproject
then type :
git reflog

You all have a list of the changes and the reference number take the ref number then checkout
from android studio or from the git betcha.
another solution take the ref number and go to android studio click on git branches down then click on checkout tag or revision past the reference number then lol you have the branches.

等风来 2024-09-24 12:26:15

添加到 tfe 的答案中,您可以使用提到的此过程进行恢复,除非它的提交未被垃圾收集。 Git 分支只是指向提交树中特定提交的指针。但是,如果您删除指针,并且该分支上的提交未合并到其他现有分支中,则 git 会将其视为悬空提交,并在垃圾收集期间删除它们,垃圾收集可能会定期自动运行。

如果您的分支没有合并到现有分支,并且它被垃圾收集,那么您将丢失所有提交,直到分支从现有分支分叉的点为止。

Adding to tfe's answer, you can recover with this process mentioned, unless it's commits are not garbage collected. Git branch is simply a pointer to a particular commit in the commit tree. But if you delete the pointer, and the commits on that branch are not merged into other existing branch, then git treats it as dangling commits and removes them during garbage collection, which it may run automatically periodically.

If your branch wasn't merged to an existing branch, and if it was garbage collected, then you will loose all commits up until the point from where branch was forked from an existing branch.

溺深海 2024-09-24 12:26:15

仅使用 git reflog 并没有为我返回 sha 。
只有commit id(8个字符长,sha更长)

所以我使用
git reflog --no-abbrev

然后执行与上面相同的操作:
git checkout -b <分支>

Just using git reflog did not return the sha for me.
Only the commit id (which is 8 chars long and a sha is way longer)

So I used
git reflog --no-abbrev

And then do the same as mentioned above:
git checkout -b <branch> <sha>

千寻… 2024-09-24 12:26:15

如果您使用 VSCode...并且您在删除分支之前的某个时刻将分支与服务器同步...

请注意,gitbranchdelete 仅删除本地副本,而不是服务器上的副本。首先,在 Git 面板(左侧工具栏上的 git 图标)中,查看分支并查看您的分支是否仍在“origin/your_branch_name”下。如果是这样,只需选择它,您就应该取回代码(建议您立即将其复制/粘贴/保存在本地其他位置)。

如果您没有看到“origin/your_branch_name”,请安装 GitLens 扩展。这使您可以直观地浏览服务器存储库并找到同步到服务器的副本。如果您有多个存储库,请注意,可能需要从所需存储库中至少打开一个文件才能使该存储库出现在 GitLens 中。然后:

  1. 打开 GitLens 面板

  2. 展开存储库

  3. 您应该看到类别列表:分支/贡献者/远程/存储/等

您应该在“分支”下或可能在“远程 -> 起源”下找到 YourLostTreasure。希望您会看到一个具有所需名称的分支 - 如果展开它,您应该会看到您在该分支中更改的文件。双击文件名将其打开,并立即备份该代码。

如果您没有立即看到丢失的分支,请四处查看,如果发现有希望的内容,请立即打开它并获取代码。我不得不四处寻找,直到找到 TheGoldenBranch,即使这样,代码也丢失了最后一两次保存(可能是因为我在尝试分支合并之前未能同步到服务器,但意外地单击了 -分支删除)。我的搜索不必要地延长了,因为当我第一次找到该分支时,我并不完全确定该名称是否正确,因此一直在寻找,并且花了一些时间才重新找到第一个分支。 (因此,Carpe Carpum 和 然后 继续寻找。)

IF you are using VSCode... and you synced your branch with the server at some point before deleting it...

Note that git branch delete only deletes the local copy, not the copy on the server. First, in the Git panel (git icon on left toolbar), look through the branches and see if your branch is still there under "origin/your_branch_name". If so, just select that and you should get your code back (suggest that you immediately copy/paste/save it locally somewhere else).

If you didn't see an "origin/your_branch_name", Install the GitLens extension. This allows you to visually poke around in the server repositories and locate the copy you synced to the server. If you have multiple repositories, note that it might be necessary to have at least one file opened from the desired repository in order to make the repository appear in GitLens. Then:

  1. Open the GitLens panel

  2. Expand the repository

  3. You should see a list of categories: Branches / Contributors / Remotes / Stashes / etc

You should find YourLostTreasure under "Branches" or possibly under "Remotes -> Origins". Hopefully, you will see a branch with the desired name - if you expand it, you should see the files you changed in that branch. Double-click the file names to open them, and immediately back up that code.

If you don't immediately see your lost branch, poke around and if you find something promising, immediately open it and grab the code. I had to poke around quite a bit until I found TheGoldenBranch, and even then the code was missing the last one or two saves (possibly because I failed to sync to server before attempting-a-Branch-Merge-but-accidentally-clicking-Branch-Delete). My search was unnecessarily lengthened because when I first found the branch I wasn't completely sure the name was correct so kept looking, and it took some time to re-find that first branch. (Thus, Carpe Carpum and then keep looking.)

御弟哥哥 2024-09-24 12:26:15

如果您已经将分支推送到远程服务器,请尝试使用 git checkout,git 将尝试从本地计算机中的最后一个原始镜像进行克隆。

If you already push branch to remote server then try to use git checkout <branch> and git will try to clone from you're last origin mirror in your local machine.

一梦浮鱼 2024-09-24 12:26:15

您可以像下面一样在 ADO 中搜索,然后单击“恢复”
输入图片此处描述

You can search in ADO like below and click on 'restore'
enter image description here

还不是爱你 2024-09-24 12:26:14

是的,您应该能够执行 git reflog --no-abbrev 并在已删除分支的顶部找到提交的 SHA1,然后只需 git checkout [sha] 。一旦您完成该提交,您只需 git checkout -b [branchname] 即可从那里重新创建分支。


感谢@Cascabel提供了这个压缩/单行版本,感谢@Snowcrash了解了如何获取sha。

如果您刚刚删除了分支,您将在终端中看到类似的内容已删除分支(是。然后只需在这段代码中使用 即可:

git checkout -b <your-branch> <sha>

Yes, you should be able to do git reflog --no-abbrev and find the SHA1 for the commit at the tip of your deleted branch, then just git checkout [sha]. And once you're at that commit, you can just git checkout -b [branchname] to recreate the branch from there.


Credit to @Cascabel for this condensed/one-liner version and @Snowcrash for how to obtain the sha.

If you've just deleted the branch you'll see something like this in your terminal Deleted branch <your-branch> (was <sha>). Then just use that <sha> in this one-liner:

git checkout -b <your-branch> <sha>
帅的被狗咬 2024-09-24 12:26:14

(重新)创建分支一旦获得提交哈希,

您将使用此命令在指定的提交哈希上创建新分支:

git branch <my-new-branch-name> <commit-hash>

但是最难的部分是找到提交哈希,您将有 2下面解释了选项:


使用命令行查找提交哈希

当提交哈希位于 reflog

时 大多数情况下,无法访问的提交位于 reflog 中(跟踪大量 git 更改)。因此,首先要尝试的是使用命令 git reflog 查看引用日志(该命令显示 HEAD 的引用日志)。

如果提交是特定且仍然存在的分支的一部分,也许更简单的方法是使用命令 git reflog name-of-my-branch 。它也可以与远程一起使用,例如,如果您强制推送(尽管应该使用 git push --force-with-lease 来代替,这样可以防止错误并且更容易恢复)。


当提交哈希不在reflog中时

如果您的提交不在您的reflog中(可能它们被不写入reflog的第三方工具删除),您可以先尝试此命令创建一个包含所有悬空提交的文件

git fsck --full --no-reflogs --unreachable --lost-found | grep commit | cut -d\  -f3 | xargs -n 1 git log -n 1 --pretty=oneline > .git/lost-found.txt

,然后读取丢失提交的 SHA 并将您的分支重置到它。

频繁的用户可能会使用创建别名 git saving

git config --global alias.rescue '!git fsck --full --no-reflogs --unreachable --lost-found | grep commit | cut -d\  -f3 | xargs -n 1 git log -n 1 --pretty=oneline > .git/lost-found.txt'

以下是一些示例,展示如何分析找到的提交

显示提交元数据(作者、创建日期和提交消息):

git cat-file -p 48540dfa438ad8e442b18e57a5a255c0ecad0560

另请参阅差异:

git log -p 48540dfa438ad8e442b18e57a5a255c0ecad0560

在找到的内容上创建分支提交:

git branch commit_rescued 48540dfa438ad8e442b18e57a5a255c0ecad0560

在 Windows 上使用 GitExtensions GUI

与从命令行执行的操作类似,您可以进行提交来自引用日志或悬挂提交的哈希:

来自引用日志(要尝试的第一件事)

您有 2 个选项:

  • 在修订网格中显示悬挂提交(也许是最简单的):在菜单中查看 => 显示引用日志引用,您现在应该能够看到引用日志中的悬空提交(灰色分支,尖端没有分支/引用标签:复制提交哈希)

    修订网格中显示的引用日志

  • 访问 HEAD 或其他分支的引用日志内容:在菜单 Commands => 中显示引用日志...
    reflogs

从引用日志中查找不可用丢失的提交

您可以通过菜单 Repository => 恢复丢失的提交(以及未提交的暂存文件!) Git 维护 => 恢复丢失的对象...。对于按日期排序的每个提交,您将获得哈希值、提交消息,并且能够轻松显示提交差异。
恢复丢失的提交

相关:轻松恢复之前已暂存但未提交的已删除/丢失的文件

(Re)Creating the branch ONCE you've got the commit hash

You will do it use this command to create the new branch on the specified commit hash:

git branch <my-new-branch-name> <commit-hash>

But the hardest part is to find the commit hash and you will have 2 options explained just below:


Finding the commit hash with the command line

When the commit hash is in the reflog

Most of the time unreachable commits are in the reflog (that keeps track of a lot of git changes). So, the first thing to try is to look at the reflog using the command git reflog (which displays the reflog for HEAD).

Perhaps something easier is to use the command git reflog name-of-my-branch if the commit was part of a specific and still existing branch. It also works with a remote e.g. if you had force pushed (though one should use git push --force-with-lease instead which prevents mistakes and is more recoverable).


When the commit hash is NOT in the reflog

If your commits are not in your reflog (perhaps they were deleted by a 3rd party tool that doesn't write to the reflog), you may try this command first to create a file with all the dangling commits

git fsck --full --no-reflogs --unreachable --lost-found | grep commit | cut -d\  -f3 | xargs -n 1 git log -n 1 --pretty=oneline > .git/lost-found.txt

then read the SHA of the missing commit and reset your branch to it.

Frequent users may create the alias git rescue using

git config --global alias.rescue '!git fsck --full --no-reflogs --unreachable --lost-found | grep commit | cut -d\  -f3 | xargs -n 1 git log -n 1 --pretty=oneline > .git/lost-found.txt'

Here are some examples showing how to analyze the found commits

Display commit metadata (author, creation date and commit message):

git cat-file -p 48540dfa438ad8e442b18e57a5a255c0ecad0560

Also see diffs:

git log -p 48540dfa438ad8e442b18e57a5a255c0ecad0560

Create a branch on the found commit:

git branch commit_rescued 48540dfa438ad8e442b18e57a5a255c0ecad0560

Using GitExtensions GUI on Windows

Similarly to what you can do from the command line, you can take the commit hash from the reflog or from dangling commits:

From the reflog (1st thing to try)

You have 2 options:

  • Display dangling commits in the revision grid (maybe the easiest): In the menu View => Show reflog references and you should now be able to see the dangling commits from the reflogs (the branch in grey with no branch/reference label at the tip: copy the commit hash)

    Reflog displayed in revision grid

  • Access to reflog content for HEAD or another branch: In the menu Commands => Show reflogs...
    reflogs

Finding a lost commit not available from the reflog

You can recover lost commits ( and also uncommitted staged files!) with via the menu Repository => Git maintenance => Recover lost objects.... For each commit, sorted by date, you will have the hash, the commit message and will be able to display easily the commit diff.
Recover lost commits

Related: Easily recover deleted/lost files that have been staged previously but not committed

天煞孤星 2024-09-24 12:26:14

如果您喜欢使用 GUI,则可以使用 gitk 执行整个操作。

gitk --reflog

这将允许您查看分支的提交历史记录,就像分支尚未被删除一样。现在,只需右键单击分支的最新提交,然后选择菜单选项创建新分支

If you like to use a GUI, you can perform the entire operation with gitk.

gitk --reflog

This will allow you to see the branch's commit history as if the branch hadn't been deleted. Now simply right click on the most recent commit to the branch and select the menu option Create new branch.

梦回旧景 2024-09-24 12:26:14

投票最高的解决方案实际上比要求的要多:

git checkout <sha>
git checkout -b <branch>

或者

git checkout -b <branch> <sha>

将您连同您可能忘记提交的所有最近更改一起移至新分支。这可能不是您的意图,尤其是在丢失分支后处于“恐慌模式”时。

一个更干净(更简单)的解决方案似乎是一句简单的话(在您使用git reflog找到之后):

git branch <branch> <sha>

现在您当前的分支和未提交的更改都不会受到影响。相反,只会创建一个新分支,一直到

如果不是提示,它仍然可以工作,并且您会得到一个较短的分支,然后您可以使用新的 和新的分支名称重试,直到正确为止。

最后,您可以将成功恢复的分支重命名为它原来的名称或其他任何名称:

git branch -m <restored branch> <final branch>

不用说,成功的关键是找到正确的提交 ,因此请明智地命名您的提交:)

The top voted solution does actually more than requested:

git checkout <sha>
git checkout -b <branch>

or

git checkout -b <branch> <sha>

move you to the new branch together with all recent changes you might have forgot to commit. This may not be your intention, especially when in the "panic mode" after losing the branch.

A cleaner (and simpler) solution seems to be the one-liner (after you found the <sha> with git reflog):

git branch <branch> <sha>

Now neither your current branch nor uncommited changes are affected. Instead only a new branch will be created all the way up to the <sha>.

If it is not the tip, it'll still work and you get a shorter branch, then you can retry with new <sha> and new branch name until you get it right.

Finally you can rename the successfully restored branch into what it was named or anything else:

git branch -m <restored branch> <final branch>

Needless to say, the key to success was to find the right commit <sha>, so name your commits wisely :)

旧人哭 2024-09-24 12:26:14

如果您删除了分支并忘记了其提交 ID,您可以执行以下命令:

git log --graph --decorate $(git rev-list -g --all)

此后,您将能够看到所有提交。
然后,您可以对此 id 执行 git checkout 并在此提交下创建一个新分支。

If you removed the branch and forgot its commit id, you can do this command:

git log --graph --decorate $(git rev-list -g --all)

After this, you'll be able to see all commits.
Then, you can do git checkout to this id and under this commit create a new branch.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文