使用VSTS Git API将初始推入到新创建的存储库中

时间:2018-07-13 13:04:28

标签: c# git azure-devops

如何使用VSTS Git API向新创建的存储库中创建初始推送?

我创建了一个新的存储库。

using Microsoft.TeamFoundation.SourceControl.WebApi;
using Microsoft.VisualStudio.Services.WebApi;
using Microsoft.TeamFoundation.Core.WebApi

var accountUri = new Uri("https://mysite.visualstudio.com");  
var personalAccessToken = "myaccesstoken"; 
var connection = new VssConnection(accountUri, new VssBasicCredential(string.Empty, personalAccessToken));

// Get a GitHttpClient to talk to the Git endpoints
var gitClient = connection.GetClient<GitHttpClient>();

var teamProject = projectClient.GetProject("MyProject", true, true).Result;

var repo = gitClient.CreateRepositoryAsync(new GitRepository
{
    DefaultBranch = "refs/heads/master",
    Name = "TestRepo",
    ProjectReference = new TeamProjectReference
    {
        Id = teamProject.Id
    }
}).Result;

存储库已成功创建。但是为什么repo.DefaultBranch的值为空?

下一步,我想推送我的初始提交。

var newBranch = new GitRefUpdate
{
    RepositoryId = repo.Id,
    Name = $"refs/heads/master"
};

string newFileName = "README.md";
GitCommitRef newCommit = new GitCommitRef
{
    Comment = "Initial commit",
    Changes = new GitChange[]
    {
        new GitChange
        {
            ChangeType = VersionControlChangeType.Add,
            Item = new GitItem { Path = $"/master/{newFileName}" },
            NewContent = new ItemContent
            {
                Content = "# Thank you for using VSTS!",
                ContentType = ItemContentType.RawText,
            },
        }
    }
};

GitPush push = gitClient.CreatePushAsync(new GitPush
{
    RefUpdates = new GitRefUpdate[] { newBranch },
    Commits = new GitCommitRef[] { newCommit },
}, repo.Id).Result;

致电CreatePushAsync时出现错误:

  

VssServiceException:参数组合无效   还是不完整。参数名称:baseCommitId

请帮助您正确创建初始提交。

1 个答案:

答案 0 :(得分:1)

您可以使用rest api实现所需的功能。 creating an initial commit (create a new branch)的其余api如下:

POST https://fabrikam.visualstudio.com/_apis/git/repositories/{repositoryId}/pushes?api-version=4.1

{
  "refUpdates": [
    {
      "name": "refs/heads/master",
      "oldObjectId": "0000000000000000000000000000000000000000"
    }
  ],
  "commits": [
    {
      "comment": "Initial commit.",
      "changes": [
        {
          "changeType": "add",
          "item": {
            "path": "/readme.md"
          },
          "newContent": {
            "content": "My first file!",
            "contentType": "rawtext"
          }
        }
      ]
    }
  ]
}