通过 Azure DevOps 服务 REST API 使用 Linux Shell 脚本创建拉取请求

Create Pull Request by Azure DevOps Service REST API with Linux Shell script

我尝试通过 Azure DevOps Services REST API 创建一个 Pull Request。我正在使用 PAT 来获取 WorkItems,例如:

#!/bin/bash
source ~/bin/variables.sh
id=
url="$(organization)/$(project)/_apis/wit/workitems/${id}?api-version=7.1-preview.3"
workItem=$(curl -s -u $(presenter):$(PAT) -X GET "${url}")

我创建了一个 Json 像:

{
     "sourceRefName": "refs/heads/U1367_My_Source_Branch",
     "targetRefName": "refs/heads/F231_My_Target_Branch",
     "title": "F231 Source bla foo. U1367 Target bla foo",
     "description": "Bla foo WorkItem: #2117",
     "isDraft": true
}

生成的Json没有换行符:

json='{"sourceRefName":"'${source}'","targetRefName":"'${target}'","title":"'${title}'","description":"'${description}'","isDraft":true}'

并发送以下内容:

 url="https://dev.azure.com/$(organizationName)/$(project)/_apis/git/repositories/${repo}/pullrequests?supportsIterations=true&api-version=7.1-preview.1"
 response=$(curl -s -u $(presenter):$(PAT) -X POST -H "Content-Type: application/json" -d '${json}' "${url}")

我收到这样的回复:

{
    "$id": "1",
    "innerException": null,
    "message": "TF400898: An Internal Error Occurred. Activity Id: 169c9863-5441-40a6-8e8d-4c826faf8308.",
    "typeName": "Newtonsoft.Json.JsonReaderException, Newtonsoft.Json",
    "typeKey": "JsonReaderException",
    "errorCode": 0,
    "eventId": 0
}

我检查了PAT的权限。我有权创建拉取请求。

关于通过 shell 脚本通过 API 创建工作拉取请求有什么建议吗?

扩展为完整答案:

在 shell 脚本中,我们使用引号(单引号或双引号)and/or 反斜杠来获取 shell 元字符以进入变量的设置。单引号用来引用双引号,双引号用来引用单引号;当我们遇到匹配的收盘价时,报价结束。例如:

DQ='"'

将变量 $DQ 设置为双引号,而:

SQ="'"

将变量 $SQ 设置为单引号(或撇号或任何你喜欢的称呼)符号。与此同时:

DONT='John yelled "don'"'"'t"'
#     ----------------  =  --

$DONT;内容部分是 single-quoted(用 - 下划线)和部分双引号(用 = 下划线)并且包含文字双引号和撇号 / single-quote,因此展开后,我们看到:

$ echo "$DONT"
John yelled "don't"

在这里,你有:

json='{"sourceRefName":"'${source}'","targetRefName":"'${target}\
'","title":"'${title}'","description":"'${description}'","isDraft":true}'

(但全部在一行中——我在这里拆分它只是为了 Whosebug 发布)其中,如果我们首先设置 sourcetarget 等等,然后 运行 它和然后 运行 echo "$json",表明它正确设置了变量 json)。不幸的是,你有:

response=$(curl -s -u $(presenter):$(PAT) -X POST \
-H "Content-Type: application/json" -d '${json}' "${url}")

(我再次拆分用于 Whosebug 发布)。

当我们希望shell扩展一些变量时,我们不能使用单引号。所以 -d '${json}' 是错误的:你想要 -d "${json}" 或者只是 -d "$json".

(在 POSIX 样式中 shell,${var} 仅当 $var 后跟可能被解释为变量的更多字母的内容时才需要大括号,或者如果我们想使用某些奇特的结构,如 ${var?error} 等。所以如果我们想打印变量 $v 的内容,后跟文字字符串 ariable,我们需要 ${v}ariable 这样它就不会被当作 ${variable} 而不是——但是如果我们想要 $v 后跟 $ariable 我们可以写成 $v$ariable,并且当使用双引号时 [=42] =] 结束双引号就足够了,所以我们可以写 "$v"ariable,例如。)

关于何时使用哪种引号的精确规则在某些特殊情况下可能会变得很麻烦,但记住这一点的简短方法是单引号比双引号更强大:

echo "$hello $world"

同时扩展了 $hello$world 但是:

echo '$hello $world'

两者都不展开。但是,将文字单引号变成单引号很丑陋:我们得到的结构类似于上面 DONT= 的结构。有时设置变量 DQ 和 SQ 并使用双引号会很好:

DQ='"'
SQ="'"
DONT="John yelled ${DQ}Don${SQ}t${DQ}"

之后:

echo "$DONT"

打印我们想要的,但变量设置是... 几乎可读。