简体   繁体   中英

How to commit a list of folders and files to Azure DevOps Repository using Rest API?

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.

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"
}

在此处输入图像描述

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);
                }
            }
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM