0

I am trying to automate creation of repositories and its initialization using Azure DevOps REST APIs. I am able to successfully create a repo using APIs.

How can we commit a bulk data, say a list of folders and files, that constitute the basic code structure, using REST API? In the request body of Pushes - Create , contentType can either be base64encoded or rawtext. I have used rawtext to test commit of a single file and it worked successfully. Now, I have to commit both files and folders together.

torek
  • 448,244
  • 59
  • 642
  • 775
Sneha Dominic
  • 368
  • 2
  • 14
  • did you try this? https://learn.microsoft.com/en-us/rest/api/azure/devops/git/pushes/create?view=azure-devops-rest-6.0#multiple-changes – Shayki Abramczyk Aug 11 '21 at 10:58
  • @ShaykiAbramczyk - Yes, I had referred this. In the sample request body, all items are individual files and contenttype is rawtext. Folders are not mentioned in that. – Sneha Dominic Aug 12 '21 at 11:08
  • I don't think it's possible :/ you can just automate it with `git` commands and no with api. – Shayki Abramczyk Aug 12 '21 at 11:14

1 Answers1

0

Accually, Rest API is always used to commit the documents related to the project.

If you want to commit all files in folders, you should define the paths of all files in changes. Shayki Abramczyk's comment is really helpful. Note: Git folders cannot be empty.

For example, these two paths will commit folder "content".

"item": {
     "path": "/tasks/content/newtasks.md"
}

"item": {
    "path": "/tasks/content/inactivetasks.md"
}

enter image description here

Please refer to this similar issue, Rakesh has created a function with C# to push files automatically.

public class Refs
    {
        public string name { get; set; }
        public string objectId { get; set; }

        public string oldObjectId { get; set; }

        public Creator creator { get; set; }
        public string url { get; set; }
    }
    
    public class Change
    {
        public string changeType { get; set; }
        public Item item { get; set; }
        public Newcontent newContent { get; set; }
    }

    public class CommitToAdd
    {
        public string comment { get; set; }
        public ChangeToAdd[] changes { get; set; }
    }

    public class ChangeToAdd
    {
        public string changeType { get; set; }
        public ItemBase item { get; set; }
        public Newcontent newContent { get; set; }
    }
     public class ItemBase
    {
          public string path { get; set; }
    }
    
     public class Newcontent
    {
        public string content { get; set; }
        public string contentType { get; set; }
    }
    
  //  ### Implementation 
    
//on your    Program.cs file

public static class program
{
    public async Task AddFileToRepository(string projectName, string repositoryId, Dictionary<string, Task<string>> blobContainer)
        {

            var refs = new List<Refs>() { new Refs { oldObjectId = "0000000000000000000000000000000000000000", name = Constants.DevOps.MASTER_REPO_REF_NAME } };

            var changes = new List<ChangeToAdd>();

            foreach (var blob in blobContainer)
            {
                if (!blob.Key.StartsWith(".git"))
                {
                    ChangeToAdd changeJson = new ChangeToAdd()
                    {
                        changeType = "add",
                        item = new ItemBase() { path = blob.Key },
                        newContent = new Newcontent()
                        {
                            contentType = "rawtext",
                            content = blob.Value.Result
                        }
                    };
                    changes.Add(changeJson);
                }
            }

            CommitToAdd commit = new CommitToAdd();
            commit.comment = "commit from code";
            commit.changes = changes.ToArray();

            var content = new List<CommitToAdd>() { commit };
            var request = new
            {
                refUpdates = refs,
                commits = content
            };

            var uri = $"https://dev.azure.com/{_orgnizationName}/{projectName}/_apis/git/repositories/{repositoryId}/pushes{Constants.DevOps.API_VERSION}";

            using (var client = this.HttpClient)
            {
                var authorizationToken = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", personalaccessToken)));

                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authorizationToken);

                var requestJson = JsonConvert.SerializeObject(request);
                var httpContent = new StringContent(requestJson, Encoding.ASCII, "application/json");
                var response = await client.PostAsync(uri, httpContent);

                if (!response.IsSuccessStatusCode)
                {
                    throw new Exception(ApplicationMessages.FailedToAddFilesToRepository);
                }
            }
        }
}
unknown
  • 6,778
  • 1
  • 5
  • 14