我如何将最后的N承诺集成到一个承诺中?


当前回答

让我们说 n 真的很大. 你不想处理每一个承诺. 你只是想要一个名为 new_feature_branch 的新分支,其中有 1 承诺和所有旧_feature_branch 的变化。

git checkout main 

# will contain changes all changes from old_feature_branch 
git checkout -b new_feature_branch 

# get all changes from old_feature_branch and stage them
for f in $(git --no-pager diff --name-only old_feature_branch ) ; do git checkout fencing -- $f ; done

git commit -m "one commit message"

其他回答

簡單的單線,總是工作,因為你現在在你想要的分支,主是它起源的分支,最新的承諾包含承諾訊息和作者你想使用:

git reset --soft $(git merge-base HEAD master) && git commit --reuse-message=HEAD@{1}

只需将此 bash 函数添加到.zshrc 文件的 bash。

# Squash last X commits with a Commit message.
# Usage: squash X 'COMMIT_MSG'
# where X= Number of last commits.
# where COMMIT_MSG= New commit msg.
function squash() {
    if [ -z "${1}" -o -z "${2}" ]; then
        echo "Usage: \`squash X COMMIT_MSG\`"
        echo "X= Number of last commits."
        echo "COMMIT_MSG= New commit msg."
        return 1
    fi

    git reset --soft HEAD~"$1"
    git add . && git ci -m "$2" # With 100 emoji
    git push --force
}

然后跑

squash X 'New Commit Message'

你已经完成了。

基于这篇文章,我发现这个方法对我的使用更容易。

我的“dev”分支在“起源/dev”前面有96个承诺(因此这些承诺尚未推到远程)。

我宁愿将分支重新设置为“起源/dev”状态(这将使96个分支的所有变更无效),然后立即进行变更:

git reset origin/dev
git add --all
git commit -m 'my commit message'

许多答案是基于Git Rebase命令,但在我的经验中,它对Git初学者来说有点复杂和先进。

假设你想排除最后3个命令,然后以下是步骤:

下载现行承诺ID: 使用 git log -1 --online 并记住当前状态的承诺ID(仅在您与 git reset 做错事的情况下) 返回 3 个承诺: 使用 git reset --soft HEAD~3 您将返回 3 个承诺(并忘记您以前做过这三个承诺) 做一个新的承诺: 现在简单地做 git commit -m <NEW_SINGLE_MESSAGE> 将自动结合 t

如果与 git reset 发生错误,您可以通过 git reset --soft <ORIGINAL_COMMIT> 返回原始状态。

如果您不关心承诺信息的承诺之间,您可以使用

git reset --mixed <commit-hash-into-which-you-want-to-squash>
git commit -a --amend