我已经找到了这个答案:在git的分支上提交的数量 但这假设分支是从master创建的。

我如何在不依赖于这个假设的情况下计算沿着分支提交的数量呢?

在SVN中,这是微不足道的,但由于某种原因,在git中很难解决。


当前回答

你可以在git bash/unix上使用awk命令来获取提交的数量。

    git shortlog -s -n | awk '/Author/ { print $1 }'

其他回答

它可能需要一个相对较新的Git版本,但这对我来说很好:

git rev-list --count develop..HEAD

这为我提供了当前分支中以master为基础的提交的确切计数。

Peter回答中的命令,git rev-list——count HEAD ^develop包含了更多的提交,在我当前的项目中是678 vs 97。

在这个分支上,我的提交历史是线性的,所以是YMMV,但它给了我想要的确切答案,即“到目前为止,我在这个特性分支上添加了多少次提交?”

因为OP引用了git中分支上的提交数量,我想补充的是,这里给出的答案也适用于任何其他分支,至少从git 2.17.1版本开始(似乎比Peter van der Does的答案更可靠):

正常工作:

git checkout current-development-branch
git rev-list --no-merges --count master..
62
git checkout -b testbranch_2
git rev-list --no-merges --count current-development-branch..
0

最后一个命令像预期的那样给出零提交,因为我刚刚创建了分支。前面的命令给出了开发分支上的实际提交数减去合并提交数

工作不正常:

git checkout current-development-branch
git rev-list --no-merges --count HEAD
361
git checkout -b testbranch_1
git rev-list --no-merges --count HEAD
361

在这两种情况下,我都得到了开发分支和master中所有提交的数量。

如果您使用的是UNIX系统,则可以这样做

git log|grep "Author"|wc -l

一种方法是列出分支的日志并计算行数。

git log <branch_name> --oneline | wc -l

好吧,如果您从不特定的分支(即不是master或develop)中派生出分支,那么所选的答案将不起作用。

在这里,我提供了另一种方法,我使用在我的预推git挂钩。

# Run production build before push
echo "[INFO] run .git/hooks/pre-push"

echo "[INFO] Check if only one commit"

# file .git/hooks/pre-push
currentBranch=$(git symbolic-ref HEAD | sed -e 's,.*/\(.*\),\1,')

gitLog=$(git log --graph --abbrev-commit --decorate  --first-parent HEAD)

commitCountOfCurrentBranch=0
startCountCommit=""
baseBranch=""

while read -r line; do

    # if git log line started with something like "* commit aaface7 (origin/BRANCH_NAME)" or "commit ae4f131 (HEAD -> BRANCH_NAME)"
    # that means it's on our branch BRANCH_NAME

    matchedCommitSubstring="$( [[ $line =~ \*[[:space:]]commit[[:space:]].*\((.*)\) ]] && echo ${BASH_REMATCH[1]} )"

    if [[ ! -z ${matchedCommitSubstring} ]];then

      if [[  $line =~ $currentBranch ]];then
        startCountCommit="true"
      else
        startCountCommit=""

        if [[ -z ${baseBranch} ]];then
          baseBranch=$( [[ ${matchedCommitSubstring} =~ (.*)\, ]] && echo ${BASH_REMATCH[1]} || echo ${matchedCommitSubstring} )

        fi

      fi

    fi


    if [[ ! -z ${startCountCommit} && $line =~ ^\*[[:space:]]commit[[:space:]] ]];then
      ((commitCountOfCurrentBranch++))
    fi


done <<< "$gitLog"

if [[ -z ${baseBranch} ]];then

  baseBranch="origin/master"

else

  baseBranch=$( [[ ${baseBranch} =~ ^(.*)\, ]] && echo ${BASH_REMATCH[1]} || echo ${baseBranch} )

fi


echo "[INFO] Current commit count of the branch ${currentBranch}:  ${commitCountOfCurrentBranch}"

if [[ ${commitCountOfCurrentBranch} -gt 1 ]];then
  echo "[ERROR] Only a commit per branch is allowed. Try run 'git rebase -i ${baseBranch}'"
  exit 1
fi

欲了解更多分析,请访问我的博客