如何让“git”忘记所有以前的提交?

6

我需要启动一个新项目,基于我的另一个项目的一个小部分,其存储库位于github上。

我在新项目文件夹中进行了git克隆...很好。

我删除了所有不需要的内容,摆脱了旧的迁移等...很好。

现在它在本地运行良好,但是'git log'显示了所有旧的提交。

我想告诉git“忘记所有之前的提交,这是一个新项目,所以从现在开始忘记以前的一切,从现在开始作为第一次提交”

我阅读了关于git rebase的文章,但不清楚是否是正确的命令,如果是,如何将其用于此非常简单的目的。

4个回答

13

删除.git文件夹,运行git initgit add


2
+1,但如果您有任何特定于仓库的内容,例如远程连接,则必须将其添加回去。 - vcsjones
1
@vcsjones:或者在删除其他内容之前,您可以复制出.git/config - Cascabel
1
存在添加应该被忽略的文件的风险。忽略列表位于4个(或更多?)不同的位置,包括在.git/下。因此,在执行rm -rf .git操作之前,我会先执行git clean -dfx . - sehe
1
值得注意的是,如果在错误的目录中调用,不正确地使用git clean -dfx可能会造成非常糟糕的后果,因此请始终首先使用干运行选项git clean -fdxn。 - jpw

9
这里的接受答案真的让我很担心——删除你的.git目录是一件极端的事情,而且这里并不需要。这个脚本采用了更安全的方法——它创建了一个名为old-master的分支,记录了你在开始压缩提交之前的位置,然后使用git reset --soft $ROOT_COMMITgit commit --amend将整个分支压缩到一个提交中。你也可以从这个GitHub gist下载脚本。
#!/bin/bash

# A script that squashes your entire current branch down to a single commit,
# if this repository has a single root commit.  This will change the object
# name of the root commit.

if [ -n "$(git status --porcelain)" ]
then
    echo "git status wasn't clean - refusing to run..."
    exit 1
fi

# From: https://dev59.com/tnNA5IYBdhLWcg3wVcJx
root_commits () {
   git rev-list --parents HEAD | egrep "^[a-f0-9]{40}$"
}

NUMBER_OF_ROOT_COMMITS=$(root_commits|wc -l)

if (( "$NUMBER_OF_ROOT_COMMITS" > 1 ))
then
    echo "This script won't work when you have multiple root commits"
    exit 1
fi

ROOT_COMMIT=$(root_commits)

if [ -z "$ROOT_COMMIT" ]
then
    echo "No root commit was found!"
    exit 1
fi

set -e
set -x

# Create a branch based on the current HEAD for safety:
git branch old-master

# Reset the branch to the root commit, leaving the previous
# state of the tree staged:
git reset --soft $ROOT_COMMIT

# Now amend the root commit with the state of the index:
git commit --amend -m "The branch restarted"

0

1
那么...这让你做到了git rebasegit filter-branch已经能够做到的事情?(而且,对于OP想要的东西来说,这也有些过度杀伐了。)不过这是一个有趣的想法。 - Cascabel

0
为什么不将该目录复制到一个全新的git存储库中并在那里提交呢?

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接