使用GitHub API将releasenotes文本上传到GitHub有时会失败

时间:2015-09-17 19:59:16

标签: git github github-api

如果刚创建了代码(https://github.com/tschulte/gradle-semantic-release-plugin/issues/3),我在上传现有代码的发行说明时遇到问题。我的代码首先创建一个带注释的标签并将其推送。在此之后,它使用GitHub API来设置刚刚创建的版本的主体。如果存储库包含更多提交,则通常会失败 - 通常很少在提交很少的新存储库中失败。

我使用以下bash脚本重现此行为

#!/bin/bash

set -e

user=tschulte
repo=github-releasetest

version="$1"
tag="v$version"

git tag $tag -m "Release of $version"
git push origin "$tag"

curl -i -X POST -H "Accept: application/vnd.github.v3+json" -H "Authorization: token $GH_TOKEN" \
    "https://api.github.com/repos/$user/$repo/releases" \
    -d "{\"tag_name\": \"$tag\", \"body\": \"# Changelog of $version\"}"

我在循环中运行脚本

export GH_TOKEN=...
for v in {61..100}; do ./issue3 $v; done

结果是,并非所有上传的版本都已上传。无法上传的内容具有GitHub API返回的以下内容(HTTP状态代码422):

{
    "message":"Validation Failed",
    "errors":[
        {
            "resource":"Release",
            "code":"custom",
            "message":"Published releases must have a valid tag"
        }
    ],
    "documentation_url":"https://developer.github.com/v3/repos/releases/#create-a-release"
}

我知道我可以通过不使用git taggit push来修复我的代码,而是使用GitHub API来创建标记,而不仅仅是设置releasenotes文本。但是,上传发布说明是现有行为的补充,我不想改变。

还有什么我可以做的吗?或者这是API中的错误吗?

1 个答案:

答案 0 :(得分:1)

创建发行版的API确实支持多种用例:

  • 创建一个标签并发布(使用当前的主人或给定的承诺)并设置它的正文
  • 使用现有标记创建版本

但是使用的版本的转换只是标签是否已经存在。如果刚刚创建了标记,那么API可能还没有意识到这一点。确保在推送标记之后和创建发布之前,使用API​​检查标记是否存在。以下脚本可以正常工作

#!/bin/bash

set -e

user=tschulte
repo=github-releasetest

version="$1"
tag="v$version"

git tag $tag -m "Release of $version"
git push origin "$tag"

echo "checking existence of tag $tag using API"
while [ "$(curl -s -w "%{http_code}" -H "Authorization: token $GH_TOKEN" "https://api.github.com/repos/$user/$repo/git/refs/tags/$tag" -o /dev/null)" -ne "200" ]
do
    echo "API does not know tag -- retrying"
done
echo "API knows tag"

if [ "$(curl -s -w "%{http_code}" -X POST -H "Accept: application/vnd.github.v3+json" -H "Authorization: token $GH_TOKEN" \
    "https://api.github.com/repos/$user/$repo/releases" \
    -d "{\"tag_name\": \"$tag\", \"body\": \"# Changelog of $version\"}" -o /dev/null)" == "201" ]
then
    echo "Release uploaded successfully"
else
    echo "Release could not be uploaded"
    exit 1
fi

有趣的是,有时API似乎需要一些时间才能知道标签:

Counting objects: 1, done.
Writing objects: 100% (1/1), 171 bytes | 0 bytes/s, done.
Total 1 (delta 0), reused 0 (delta 0)
To git@github.com:tschulte/github-releasetest.git
 * [new tag]         v238 -> v238
checking existence of tag v238 using API
API does not know tag -- retrying
API does not know tag -- retrying
API does not know tag -- retrying
API does not know tag -- retrying
API does not know tag -- retrying
API knows tag
Release uploaded successfully