microsoft / azure-devops-dotnet-samples

.NET/C# samples for integrating with Azure DevOps Services and Azure DevOps Server
https://docs.microsoft.com/azure/devops/integrate
MIT License
519 stars 511 forks source link

CreateRepositoryAsync help to create a new repo with master branch #281

Open TofferAtNeal opened 4 years ago

TofferAtNeal commented 4 years ago

I'd like a sample on how to create a new repo from scratch with a default "master" branch. Here's the code I'm using to try and accomplish it, but when I look at the newly created project...there's no git repo after...

GitRepository newRepo = gitClient.CreateRepositoryAsync(new GitRepository { Name = $"{newProject.Name} Git Repo" }, newProject.Id).Result;

newProject is of type TeamProject and is successfully being created with no issues earlier before the above call is being made.

I've tried variations where I created the GitRepository object and set the Name and DefaultBranch properties manually, but that had no effect. If there's something simple that I'm missing...please let me know. :)

gar-ema commented 3 years ago

I had the same "issue". Like you I supposed that creating a repo with a default branch named "master" would create the branch but, according to REST API documentation, you have to create an initial commit in order to have a new branch. So you have to write something like this in your code:

GitCommitRef commit = new GitCommitRef()
                    {
                        Comment = "commit comment",
                        Changes = new GitChange[]
                        {
                            new GitChange()
                            {
                               ChangeType = VersionControlChangeType.Add,
                               Item = new GitItem() { Path = "/folder/file.ext" },
                               NewContent = new ItemContent()
                               {
                                   Content = "Your file content",
                                   ContentType = ItemContentType.RawText,
                               },
                            }
                        },
                    };`

GitPush push = gitClient.CreatePushAsync(new GitPush()
                    {
                        RefUpdates = new GitRefUpdate[] { new GitRefUpdate { Name = "refs/heads/master", OldObjectId = "0000000000000000000000000000000000000000" } },
                        Commits = new GitCommitRef[] { commit },
                    }, newRepo.Id).Result