仅当包版本与 Git 的主分支上的标签匹配时才推送 nuget 包

Push nuget package only if the package version matches the Tag on Git's master branch

在我们的开发环境中,我们搭建了一个NuGet本地服务器(BaGet)。我们采用了 Git 流的想法。当一个库准备在 Baget 上发布时,开发者应该首先在 master 分支上增加 Tag(需要先通过 pull-request 批准),然后将库推送到 Baget。我们这样做是为了使 GitNuget 的版本保持同步。

保持版本同步(Git 标签和 NuGet 版本)的过程由开发人员手动控制,有时一些团队成员忘记定义 Git 版本标签而只是推送库到 Baget。

如果script能够在推送库到Baget服务器之前检查当前Git标签,并且只推送如果 TagVersion 相同。这可以防止在 git.

上推送不匹配标签的版本

我们使用这个脚本推送到 Baget:

#!/bin/bash
clear

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd $DIR
ostype=`uname`

KEY=$NUGET_KEY
SOURCE=$NUGET_URL

while :
do
        clear
        echo "Input your package version: "
        read version
        Common="Dayan.Common/bin/Debug/Dayan.Common."$version".nupkg"        
        dotnet nuget push $Common -s $SOURCE -k $KEY
        echo "press enter to continue ..."
        read
done

我能否以某种方式检查 bash 中的使用 git 命令以获取项目主分支上最后一次提交的标签,并与用户输入的版本一起检查它?

进行该检查的一种方法是使用 git 命令 rev-list

此命令将输出最近提交的提交 SHA:

$ git rev-list -n 1 HEAD
dfe4a9989b33e97f25645d79fd62900cc3209ec7

虽然此命令将输出标签的提交 SHA 3.1.5:

$ git rev-list -n 1 "3.1.5"
a35117a201290b63b53ba6372dbf8bbfc68f28b9

以下示例脚本应该可以帮助您入门:

#!/bin/bash

echo "Input your package version: "
read version

last_commit=$(git rev-list -n 1 HEAD 2>/dev/null)
last_commit_result=$?
if [ "$last_commit_result" != "0" ]; then
    echo "Failed to get the SHA of the most recent commit"
    exit 1
fi

version_commit=$(git rev-list -n 1 "$version" 2>/dev/null)
version_commit_result=$?
if [ "$version_commit_result" != "0" ]; then
    echo "There is no commit with the tag: $version"
    exit 1
fi

if [ "$last_commit" = "$version_commit" ]; then
    echo "The most recent commit has the tag: $version"
else
    echo "The most recent commit does NOT have the tag: $version"
fi

如果您还想确保脚本只是来自 master 的 运行,那么在脚本的开始附近添加:

active_branch=$(git branch --show-current 2>/dev/null)
active_branch_result=$?
if [ "$active_branch_result" != "0" ]; then
    echo "Failed to get the active branch"
    exit 1
elif [ "$active_branch" != "master" ]; then
    echo "The active branch is not master"
    exit 1
fi