Search code examples
c#gittfstfs-sdk

Cannot successfully call CreatePushAsync


I'm trying to programmatically update a file in an existing branch but I get this exception.

The combination of parameters is either not valid or not complete. Parameter name: refUpdate

Here is my code:

GitRefUpdate desiredBranch = new GitRefUpdate()
{
    RepositoryId = sourceRepoGuid,
    OldObjectId = branch.ObjectId
};

GitCommitRef newCommit = new GitCommitRef()
{
    Comment = $"Update config to match new branch ",
    Changes = new GitChange[]
    {
        new GitChange()
        {
            ChangeType = VersionControlChangeType.Edit,
            Item = new GitItem() { Path = $"/{fileName}" },
            NewContent = new ItemContent()
            {
                Content = fileContent,
                ContentType = ItemContentType.RawText,
            },
        }
    },
};
        
GitPush push = gitClient.CreatePushAsync(new GitPush()
{
    RefUpdates = new GitRefUpdate[] { desiredBranch },
        Commits = new GitCommitRef[] { newCommit }
}, sourceRepoGuid).Result;

I would imagine from the error message that I'm doing something wrong with the GitRefUpdate object. I've tried several different combinations of OldObjectId, NewObjectId with the SHA from the last commit of the file to the SHA of the branch itself, nothing satisfies the call to CreatePushAsync.

The only example I've found is in the MS samples and it creates a new branch and adds a new file. I want to update an existing file in an existing branch.

I'm out of ideas.


Solution

  • You could try TFS REST API as the steps below:

    1. Get commit ID value: Request method: GET; URL [collection url]/[team project name]/_apis/git/repositories/[repository name]/commits?api-version=1.0&branch=master&$top=1
    2. Update file content: Request method: Post; URL: [collection url]/[team project name]/_apis/git/repositories/[repository name]/pushes?api-version=3.0-preview.2; Content Type: application/json;

    JSON data:

    {
        "refUpdates": [{
            "name": "refs/heads/master",
            "oldObjectId": "[step 1 commit ID]"
        }],
        "commits": [{
            "comment": "Updated BuildLog.cs",
            "changes": [{
                "changeType": 2,
                "item": {"path": "/BuildLog.cs"},
                "newContent": {
                    "content": "using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleApplication1
    {
        public class BuildLog
        {
            public int count;
            public string[] value6;
        }
    }
    ",
                    "contentType": 0
                }
            }]
        }]
    }
    

    Please refer to this case for more details: Updating a file using REST Api Visual Studio Team Services