简体   繁体   English

如何使用 Rest API 将文件夹和文件列表提交到 Azure DevOps 存储库?

[英]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.我正在尝试使用 Azure DevOps REST API 自动创建存储库及其初始化。 I am able to successfully create a repo using APIs.我能够使用 API 成功创建存储库。

How can we commit a bulk data, say a list of folders and files, that constitute the basic code structure, using REST API?我们如何使用 REST API 提交构成基本代码结构的批量数据,比如文件夹和文件列表? In the request body of Pushes - Create , contentType can either be base64encoded or rawtext.Pushes - Create的请求体中,contentType 可以是 base64encoded 或 rawtext。 I have used rawtext to test commit of a single file and it worked successfully.我已经使用 rawtext 来测试单个文件的提交并且它成功运行。 Now, I have to commit both files and folders together.现在,我必须同时提交文件和文件夹。

Accually, Rest API is always used to commit the documents related to the project.实际上,Rest API 总是用来提交与项目相关的文件。

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. Shayki Abramczyk 的评论非常有帮助。 Note: Git folders cannot be empty.注意: Git文件夹不能为空。

For example, these two paths will commit folder "content".例如,这两个路径将提交文件夹“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.请参考this similar issue ,Rakesh创建了一个function和C#来自动推送文件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 REST API 列出 azure 回购中内容的文件 - How to list the files with content that are in azure repo using REST API 如何使用 Azure Devops 服务更新 Azure Devops 中测试用例的“区域路径” Rest API - How to update "Area Path" of a test case in Azure Devops using Azure Devops Services Rest API Azure DevOps:如何使用 REST API 从 git 下载文件? - Azure DevOps: How to download a file from git using REST API? 使用 rest api 将笔记本部署到 azure devops - deploy notebooks to azure devops using rest api Azure 开发运营 REST API 发送邮件 - Azure Devops REST API SendMail 设置 Azure devops 使用 REST API 发布管道变量 - Set Azure devops Release pipeline variable using REST API Rest API 对于 Azure devops 日历不工作 - Rest API for Azure devops calendar not working 有没有一种方法可以使用 Rest API 从 Azure 逻辑应用程序创建 Azure DevOps 工作项? - Is there a way that we can create Azure DevOps work items using Rest API from Azure Logic apps? Azure DevOps REST API 调用列表版本不起作用。 有什么建议么? - Azure DevOps REST API call to list releases is not working. Any suggestions? 如何使用 Azure DevOps API 将工作项与测试结果相关联? - How to associate a work item with a test result using the Azure DevOps API?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM