You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Git仓库提交分歧:如何回退指定提交并恢复推送功能

问题描述

开发项目时,git add .、git commit -m "message"和git push突然无法正常执行。手动上传代码到GitHub仓库后,clone仓库继续开发,但git push仍失效,提示:

On branch main
Your branch and 'origin/main' have diverged,
and have 8 and 1 different commits each, respectively.
(use "git pull" to merge the remote branch into yours).

已尝试操作与核心诉求

  • 用git reset回退到历史提交ID后重新clone
  • 了解git rebase但误以为仅适用于多分支
  • 查阅Stack Overflow未找到有效方案

核心诉求:将仓库回退到提交ID为0ace80d(提交信息"Fixing Superuser")的版本,之后能正常执行git add .和git push。

当前额外问题

  1. 能否查看仓库提交历史的可视化示意图?
  2. 尝试git rebase时提示存在未暂存变更,执行git reset无法清除该变更。

当前git status输出

(base) andrewstribling@Andrews-MBP news % git status

On branch main
Your branch and 'origin/main' have diverged,
and have 10 and 1 different commits each, respectively.
(use "git pull" to merge the remote branch into yours)

Changes not staged for commit:
(use "git add/rm ..." to update what will be committed)
(use "git checkout -- ..." to discard changes in working directory)

deleted:    ../../../../../.gitignore
    deleted:    ../../../../../.vscode/settings.json
    modified:   ../../../../../README.MD
    # 其余大量删除文件省略

Untracked files:
(use "git add ..." to include in what will be committed)

../../../../../.CFUserTextEncoding
    ../../../../../.DS_Store
    # 其余大量未追踪文件省略

解决方案

第一步:清理混乱的工作区

从git status路径能看出,你当前不在仓库根目录执行命令,这是问题根源之一:

  1. 切换到clone下来的仓库根目录(比如django_news_app文件夹):
    cd /path/to/your/django_news_app
    
  2. 彻底清理本地变更:
    # 重置所有已修改/删除文件到仓库当前状态
    git reset --hard
    # 删除所有未追踪的文件和文件夹
    git clean -fd
    

第二步:回退到目标版本并强制推送

工作区清理完成后,执行以下命令覆盖远程仓库历史:

# 确保在main分支
git checkout main
# 本地分支强制重置到目标提交
git reset --hard 0ace80d
# 强制推送到远程,覆盖0ace80d之后的所有远程提交
git push origin main --force

额外问题解答

  1. 查看提交历史可视化示意图:

    • 命令行执行:git log --graph --oneline --all,会显示分支与提交的树形结构
    • GitHub仓库的提交历史页面自带分支可视化图,也可以用SourceTree、GitKraken等GUI工具查看
  2. git rebase提示未暂存变更、git reset无效:
    之前是因为你不在仓库根目录执行命令导致的,在根目录执行git reset --hard和git clean -fd即可彻底清除所有变更。

内容的提问来源于stack exchange,提问作者user17598401

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 14:06:06