如何最好地压制旧的提交

tim*_*one 14 git git-squash

最近离开的一位开发人员在几个月前的回购中留下了大量的提交,就像"更新"一样.理想情况下,我想将它们压缩成一个提交,但我只是为最近的提交做了这个.

我将如何做以下提交(假设从2个月前意味着有数百个)?

....从2个月前

aabbcc updated
aabbdd updated
aabbee updated
aabbff updated
Run Code Online (Sandbox Code Playgroud)

不想/需要任何花哨的东西,只是一个简单的解决方案.这些提交尚未公开分享(除了我今天以外),因此不会扰乱其他人的提交历史.

Cod*_*ard 6

为了做一个git南瓜,请遵循以下步骤:

// X is the number of commits you wish to squash
git rebase -i HEAD~X
Run Code Online (Sandbox Code Playgroud)

压缩提交后-选择sfor squash =它将把所有提交合并到一个提交中。

在此处输入图片说明


如果需要,您还具有--root标志

尝试: git rebase -i --root

- 根

Rebase all commits reachable from <branch>, instead of limiting them with
an <upstream>.

This allows you to rebase the root commit(s) on a branch.  
When used with --onto, it will skip changes already contained in `<newbase>`   
(instead of `<upstream>`) whereas without --onto it will operate on every 
change. When used together with both --onto and --preserve-merges, all root 
commits will be rewritten to have `<newbase>` as parent instead.`
Run Code Online (Sandbox Code Playgroud)


jxc*_*r0w 5

我知道这已经是一个古老的问题,但我需要一个解决方案。

长话短说,我的本地 git 存储库(在 NFS 上,没有上游)用作某些文件的备份,我希望它最多有 50 次提交。由于有很多文件并且备份经常被执行,我需要一些可以自动压缩历史的东西,所以我创建了一个既备份文件又压缩历史的脚本。

#!/bin/bash

# Max number of commits preserved
MAX_COMMITS=50

# First commit (HEAD~<number>) to be squashed
FIRST_SQUASH=$(echo "${MAX_COMMITS}-1"|bc)

# Number of commits until squash
SQUASH_LIMIT=60

# Date and time for commit message
DATE=$(date +'%F %R')

# Number of current commits
CURRENT_COMMITS=$(git log --oneline|wc -l)

if [ "${CURRENT_COMMITS}" -gt "${SQUASH_LIMIT}" ]; then

    # Checkout a new branch 'temp' with the first commit to be squashed
    git checkout -b temp HEAD~${FIRST_SQUASH}

    # Reset (soft) to the very first commit in history
    git reset $(git rev-list --max-parents=0 --abbrev-commit HEAD)

    # Add and commit (--amend) all the files
    git add -A
    git commit --amend -m "Automatic squash on ${DATE}"

    # Cherry pick all the non-squashed commits from 'master'
    git cherry-pick master~${FIRST_SQUASH}..master

    # Delete the 'master' branch and rename the 'temp' to 'master'
    git branch -D master
    git branch -m master

fi
Run Code Online (Sandbox Code Playgroud)

所以,脚本的主要作用是(我删除了备份部分):

  1. 如果提交超过 60 次,它会将所有从 50 到 60+ 的提交压缩为一个提交。
  2. 它根据提交创建并签出一个新分支
  3. Cherry 从主节点(#1 到 #49)中挑选剩余的提交到分支
  4. 删除主分支
  5. 将新分支重命名为 master。

  • `bc` 并不总是存在。您可以使用内置的 bash 算术来增加更多的可移植性:`FIRST_SQUASH=$(expr $MAX_COMMITS - 1)` (2认同)