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

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

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


当前回答

git log——pretty=oneline | wc -l怎么样

这将从当前分支的角度计算所有提交。

其他回答

git log——pretty=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

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

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

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

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

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

你也可以 Git log | grep commit | wc -l

然后得到结果