使用REST和PowerShell创建Atlassian Stash仓库

3
我在尝试使用PowerShell自动创建新的Git仓库时遇到了难题。 据我所知,通过在URL上使用POST方法创建新的存储库。
/rest/api/1.0/projects/$ProjectKey/repos  

https://developer.atlassian.com/static/rest/stash/3.0.1/stash-rest.html#idp1178320

因为只有管理员才能修改我添加的内容,所以我在 webrequest 中添加了一个授权头字段。

$ByteArr      = [System.Text.Encoding]::UTF8.GetBytes('admin:pwd')
$Base64Creds  = [Convert]::ToBase64String($ByteArr)

$ProjectKey = 'SBOX'
$CreateRepoUri = "$BaseUri/rest/api/1.0/projects/$ProjectKey/repos/"
Invoke-RestMethod -Method Post `
              -Headers @{ Authorization="Basic $Base64Creds" } `
              -Uri $CreateRepoUri `
              -ContentType 'application/json' `
              -Body @{ slug='test'; name='RestCreatedRepo';}

但是执行时出现了内部服务器错误(500)。没有更多关于错误原因的详细信息或InnerExceptions。
使用GET检索存储库列表有效,因此身份验证有效(至少对于Get请求)。
根据此,这应该是一个正确的语句: 这个slug或scmId到底是什么(有人听说过吗)?
如果你们中的任何一个天才能指点我正确的方向,那就太好了,因为我刚刚开始使用web服务。
谢谢, 迈克尔
2个回答

2
REST API文档在这方面有些含糊,但是我认为您无法基于此部分设置仓库slug。两者都没有明确说明是否可以更改slug,但示例中使用名称和提示表明,如果名称更改,slug可能会更改。

仓库的slug源自其名称。如果名称更改,则slug也可能会更改。

例如,使用名称"My Repo"创建存储库,从而导致slug为"my-repo"。因此,我认为slug基本上是存储库名称的“规范化”版本。ScmId标识要用于存储库的源代码控制管理类型(例如“git”)。

对于请求的正文,我也不确定Invoke-RestMethod是否会自动将其转换为JSON。您可以使用ConvertTo-Json cmdlet进行此操作,或在较小的情况下只需手动创建JSON字符串。以下是我的做法:

$baseUrl = 'http://example.com'
$usernamePwd = 'admin:passwd'
$project = 'SBOX'
$repoName = 'RestCreatedRepo'

$headers = @{}
$headers.Add('Accept', 'application/json')

$bytes = [System.Text.Encoding]::UTF8.GetBytes($usernamePwd)
$creds = 'Basic ' + [Convert]::ToBase64String($bytes)
$headers.Add('Authorization', $creds)

$data = '{"name": "{0}","scmId": "git","forkable": true}' -f $repoName
$url = '{0}/rest/api/1.0/projects/{1}/repos' -f $baseUrl,$project
$response = try {
    Invoke-RestMethod -Method Post `
            -Uri $url `
            -Headers $headers `
            -ContentType 'application/json' `
            -Body $data
} catch {
    $_.Exception.Response
}

“你可以使用ConvertTo-Json Cmdlet”是一个好的提示……我一直以为Body参数会自动转换为我的请求中的“Content-Type”。 - 3bh
警告:如果您使用此答案,则在设置$data时需要使用双重{{ }},否则-f将显示无效格式。$data = '{{"name": "{0}","scmId": "git","forkable": true}}' -f $repoName - Alvaromon

1
我想提供一些关于如何从响应中查看更多细节的一般指导,这并不是针对您在Atlassian问题上的问题的答案。
$response = try {
    Invoke-RestMethod -Method Post `
              -Headers @{ Authorization="Basic $Base64Creds" } `
              -Uri $CreateRepoUri `
              -ContentType 'application/json' `
              -Body @{ slug='test'; name='RestCreatedRepo';}
} catch {
    $_.Exception.Response
}

您可以检查$response以查看失败的实际原因。

谢谢提供这些信息!这肯定会让生活变得更轻松 :) - Michael Kargl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接