/// <summary> /// Push changes to remove, rename or move files /// </summary> /// <param name="teamProjectName"></param> /// <param name="gitRepoName"></param> /// <param name="branchRef"></param> /// <param name="branchOldId"></param> /// <param name="oldPath"></param> /// <param name="targetPath"></param> /// <param name="versionControlChangeType"></param> /// <param name="commitComment"></param> private static void PushChanges(string teamProjectName, string gitRepoName, string branchRef, string branchOldId, string oldPath, string targetPath, VersionControlChangeType versionControlChangeType, string commitComment) { GitRefUpdate branch = new GitRefUpdate(); branch.OldObjectId = branchOldId; branch.Name = branchRef; GitCommitRef newCommit = new GitCommitRef(); newCommit.Comment = commitComment; GitChange gitChange = new GitChange(); gitChange.ChangeType = versionControlChangeType; if (!string.IsNullOrEmpty(oldPath)) { gitChange.SourceServerItem = oldPath; } gitChange.Item = new GitItem() { Path = targetPath }; newCommit.Changes = new GitChange[] { gitChange }; GitPush gitPush = new GitPush(); gitPush.RefUpdates = new GitRefUpdate[] { branch }; gitPush.Commits = new GitCommitRef[] { newCommit }; var pushResult = GitClient.CreatePushAsync(gitPush, teamProjectName, gitRepoName).Result; Console.WriteLine("Push id: " + pushResult.PushId); }
/// <summary> /// Push changes to branch /// </summary> /// <param name="teamProjectName"></param> /// <param name="gitRepoName"></param> /// <param name="branchRef"></param> /// <param name="branchOldId"></param> /// <param name="targetPath"></param> /// <param name="fileContent"></param> /// <param name="itemContentType"></param> /// <param name="versionControlChangeType"></param> /// <param name="commitComment"></param> private static void PushChanges(string teamProjectName, string gitRepoName, string branchRef, string branchOldId, string targetPath, string fileContent, ItemContentType itemContentType, VersionControlChangeType versionControlChangeType, string commitComment) { GitRefUpdate branch = new GitRefUpdate(); branch.OldObjectId = branchOldId; branch.Name = branchRef; GitCommitRef newCommit = new GitCommitRef(); newCommit.Comment = commitComment; GitChange gitChange = new GitChange(); gitChange.ChangeType = versionControlChangeType; gitChange.Item = new GitItem() { Path = targetPath }; gitChange.NewContent = new ItemContent() { Content = fileContent, ContentType = itemContentType }; newCommit.Changes = new GitChange[] { gitChange }; GitPush gitPush = new GitPush(); gitPush.RefUpdates = new GitRefUpdate[] { branch }; gitPush.Commits = new GitCommitRef[] { newCommit }; var pushResult = GitClient.CreatePushAsync(gitPush, teamProjectName, gitRepoName).Result; Console.WriteLine("Push id: " + pushResult.PushId); }
private async Task <int?> CreatePullRequestIfChanged(Guid repoId, List <GitChange> changes, string lastCommit, string baseBranchName, string targetBranchName, ITemplateReplacer replacer) { if (changes.Count > 0) { var title = GetTitle(replacer); var description = GetDescription(replacer); var commitMessage = GetCommitMessage(replacer); var push = CreatePush(lastCommit, changes, targetBranchName, commitMessage); await _gitClient.CreatePushAsync(push, repoId).ConfigureAwait(false); Log($"Push for {repoId} at {targetBranchName} created."); if (!string.Equals(baseBranchName, targetBranchName, StringComparison.InvariantCultureIgnoreCase)) { var pr = CreatePullRequest(baseBranchName, targetBranchName, title, description); var result = await _gitClient.CreatePullRequestAsync(pr, repoId).ConfigureAwait(false); Log($"Pull request for {repoId} to {baseBranchName} created."); return(result.PullRequestId); } Log($"Skipping pull request since {baseBranchName} was the target."); } return(null); }
public GitPush CreatePush(string projectName, string repoName) { VssConnection connection = this.Connection; GitHttpClient gitClient = connection.GetClient <GitHttpClient>(); var repo = gitClient.GetRepositoryAsync(projectName, repoName).Result; //// we will create a new push by making a small change to the default branch //// first, find the default branch //GitRef defaultBranch = gitClient.GetRefsAsync(repo.Id).Result.First(); // next, craft the branch and commit that we'll push GitRefUpdate newBranch = new GitRefUpdate() { Name = $"refs/heads/master", OldObjectId = "0000000000000000000000000000000000000000" }; string newFileName = $"test.md"; GitCommitRef newCommit = new GitCommitRef() { Comment = "Add a sample file", Changes = new GitChange[] { new GitChange() { ChangeType = VersionControlChangeType.Add, Item = new GitItem() { Path = $"/master/{newFileName}" }, NewContent = new ItemContent() { Content = "# Thank you for using VSTS!", ContentType = ItemContentType.RawText, }, } }, }; // create the push with the new branch and commit GitPush push = gitClient.CreatePushAsync(new GitPush() { RefUpdates = new GitRefUpdate[] { newBranch }, Commits = new GitCommitRef[] { newCommit }, }, repo.Id).Result; Console.WriteLine("project {0}, repo {1}", projectName, repo.Name); Console.WriteLine("push {0} updated {1} to {2}", push.PushId, push.RefUpdates.First().Name, push.Commits.First().CommitId); return(push); }
private static GitPullRequest CreatePullRequestInternal(ClientSampleContext context, GitRepository repo, GitHttpClient gitClient) { // we need a new branch with changes in order to create a PR // first, find the default branch string defaultBranchName = WithoutRefsPrefix(repo.DefaultBranch); GitRef defaultBranch = gitClient.GetRefsAsync(repo.Id, filter: defaultBranchName).Result.First(); // next, craft the branch and commit that we'll push GitRefUpdate newBranch = new GitRefUpdate() { Name = $"refs/heads/vsts-api-sample/{ChooseRefsafeName()}", OldObjectId = defaultBranch.ObjectId, }; string newFileName = $"{ChooseItemsafeName()}.md"; GitCommitRef newCommit = new GitCommitRef() { Comment = "Add a sample file", Changes = new GitChange[] { new GitChange() { ChangeType = VersionControlChangeType.Add, Item = new GitItem() { Path = $"/vsts-api-sample/{newFileName}" }, NewContent = new ItemContent() { Content = "# Thank you for using VSTS!", ContentType = ItemContentType.RawText, }, } }, }; // create the push with the new branch and commit GitPush push = gitClient.CreatePushAsync(new GitPush() { RefUpdates = new GitRefUpdate[] { newBranch }, Commits = new GitCommitRef[] { newCommit }, }, repo.Id).Result; // finally, create a PR var pr = gitClient.CreatePullRequestAsync(new GitPullRequest() { SourceRefName = newBranch.Name, TargetRefName = repo.DefaultBranch, Title = $"Add {newFileName} (from VSTS REST samples)", Description = "Adding this file from the pull request samples", }, repo.Id).Result; return(pr); }
private async Task <string> InnerCreateBranch(string name, GitHttpClient client, Guid repositoryID, string newObjectCommitID) { bool isCIFileExist = true; try { _ = await client.GetItemAsync(repositoryID, ciFilePath); } catch (Exception) { isCIFileExist = false; } GitRefUpdate newBranch = new GitRefUpdate() { Name = $"{_azureDevopsConfiguration.GITSourceControl.NewBranchPath}/{name}", OldObjectId = newObjectCommitID }; GitCommitRef newCommit = new GitCommitRef() { Comment = "***No_CI****", Changes = new GitChange[] { new GitChange() { ChangeType = isCIFileExist ? VersionControlChangeType.Edit : VersionControlChangeType.Add, Item = new GitItem() { Path = $"/_no_ci_file" }, NewContent = new ItemContent() { Content = "", ContentType = ItemContentType.RawText, }, } } }; GitPush push = await client.CreatePushAsync(new GitPush() { RefUpdates = new GitRefUpdate[] { newBranch }, Commits = new GitCommitRef[] { newCommit }, }, repositoryID); return(push.Commits.First(x => !String.IsNullOrEmpty(x.CommitId))?.CommitId); }
public GitPush CreatePush() { VssConnection connection = this.Context.Connection; GitHttpClient gitClient = connection.GetClient <GitHttpClient>(); TeamProjectReference project = ClientSampleHelpers.FindAnyProject(this.Context); GitRepository repo = GitSampleHelpers.FindAnyRepository(this.Context, project.Id); // we will create a new push by making a small change to the default branch // first, find the default branch string defaultBranchName = GitSampleHelpers.WithoutRefsPrefix(repo.DefaultBranch); GitRef defaultBranch = gitClient.GetRefsAsync(repo.Id, filter: defaultBranchName).Result.First(); // next, craft the branch and commit that we'll push GitRefUpdate newBranch = new GitRefUpdate() { Name = $"refs/heads/vsts-api-sample/{GitSampleHelpers.ChooseRefsafeName()}", OldObjectId = defaultBranch.ObjectId, }; string newFileName = $"{GitSampleHelpers.ChooseItemsafeName()}.md"; GitCommitRef newCommit = new GitCommitRef() { Comment = "Add a sample file", Changes = new GitChange[] { new GitChange() { ChangeType = VersionControlChangeType.Add, Item = new GitItem() { Path = $"/vsts-api-sample/{newFileName}" }, NewContent = new ItemContent() { Content = "# Thank you for using VSTS!", ContentType = ItemContentType.RawText, }, } }, }; // create the push with the new branch and commit GitPush push = gitClient.CreatePushAsync(new GitPush() { RefUpdates = new GitRefUpdate[] { newBranch }, Commits = new GitCommitRef[] { newCommit }, }, repo.Id).Result; Console.WriteLine("project {0}, repo {1}", project.Name, repo.Name); Console.WriteLine("push {0} updated {1} to {2}", push.PushId, push.RefUpdates.First().Name, push.Commits.First().CommitId); // now clean up after ourselves (and in case logging is on, don't log these calls) ClientSampleHttpLogger.SetSuppressOutput(this.Context, true); // delete the branch GitRefUpdateResult refDeleteResult = gitClient.UpdateRefsAsync( new GitRefUpdate[] { new GitRefUpdate() { OldObjectId = push.RefUpdates.First().NewObjectId, NewObjectId = new string('0', 40), Name = push.RefUpdates.First().Name, } }, repositoryId: repo.Id).Result.First(); // pushes and commits are immutable, so no way to clean them up // but the commit will be unreachable after this return(push); }
public GitPullRequest CreatePullRequestInner(bool cleanUp) { VssConnection connection = this.Context.Connection; GitHttpClient gitClient = connection.GetClient <GitHttpClient>(); TeamProjectReference project = ClientSampleHelpers.FindAnyProject(this.Context); GitRepository repo = GitSampleHelpers.FindAnyRepository(this.Context, project.Id); // we need a new branch with changes in order to create a PR // first, find the default branch string defaultBranchName = GitSampleHelpers.WithoutRefsPrefix(repo.DefaultBranch); GitRef defaultBranch = gitClient.GetRefsAsync(repo.Id, filter: defaultBranchName).Result.First(); // next, craft the branch and commit that we'll push GitRefUpdate newBranch = new GitRefUpdate() { Name = $"refs/heads/vsts-api-sample/{GitSampleHelpers.ChooseRefsafeName()}", OldObjectId = defaultBranch.ObjectId, }; string newFileName = $"{GitSampleHelpers.ChooseItemsafeName()}.md"; GitCommitRef newCommit = new GitCommitRef() { Comment = "Add a sample file", Changes = new GitChange[] { new GitChange() { ChangeType = VersionControlChangeType.Add, Item = new GitItem() { Path = $"/vsts-api-sample/{newFileName}" }, NewContent = new ItemContent() { Content = "# Thank you for using VSTS!", ContentType = ItemContentType.RawText, }, } }, }; // create the push with the new branch and commit GitPush push = gitClient.CreatePushAsync(new GitPush() { RefUpdates = new GitRefUpdate[] { newBranch }, Commits = new GitCommitRef[] { newCommit }, }, repo.Id).Result; // finally, create a PR var pr = gitClient.CreatePullRequestAsync(new GitPullRequest() { SourceRefName = newBranch.Name, TargetRefName = repo.DefaultBranch, Title = $"Add {newFileName} (from VSTS REST samples)", Description = "Adding this file from the pull request samples", }, repo.Id).Result; Console.WriteLine("project {0}, repo {1}", project.Name, repo.Name); Console.WriteLine("{0} (#{1}) {2} -> {3}", pr.Title.Substring(0, Math.Min(40, pr.Title.Length)), pr.PullRequestId, pr.SourceRefName, pr.TargetRefName); if (cleanUp) { // clean up after ourselves (and in case logging is on, don't log these calls) ClientSampleHttpLogger.SetSuppressOutput(this.Context, true); // abandon the PR GitPullRequest updatedPr = new GitPullRequest() { Status = PullRequestStatus.Abandoned, }; pr = gitClient.UpdatePullRequestAsync(updatedPr, repo.Id, pr.PullRequestId).Result; // delete the branch GitRefUpdateResult refDeleteResult = gitClient.UpdateRefsAsync( new GitRefUpdate[] { new GitRefUpdate() { OldObjectId = push.RefUpdates.First().NewObjectId, NewObjectId = new string('0', 40), Name = push.RefUpdates.First().Name, } }, repositoryId: repo.Id).Result.First(); } return(pr); }
public Task <GitPush> CreatePushAsync(GitPush push, Guid repositoryId) => RetryHelper.GetWaitAndRetryPolicy <Exception>(_loggerService) .ExecuteAsync(() => _gitHttpClient.CreatePushAsync(push, repositoryId));
public Task <GitPush> CreatePushAsync(GitPush push, Guid repositoryId) => _gitHttpClient.CreatePushAsync(push, repositoryId);
private void uploadFile() { try { //VssCredentials creds = new VssClientCredentials(); //creds.Storage = new VssClientCredentialStorage(); VssBasicCredential creds = new VssBasicCredential(@"fareast\v-shgao", @"2wsx@WSX"); // Connect to VSTS VssConnection connection = new VssConnection(new Uri(c_collectionUri), creds); // Get a GitHttpClient to talk to the Git endpoints GitHttpClient gitClient = connection.GetClient <GitHttpClient>(); // Get data about a specific repository var repo = gitClient.GetRepositoryAsync(c_projectName, c_repoName).GetAwaiter().GetResult(); GitRef branch = gitClient.GetRefsAsync(repo.Id, filter: "heads/OfficeMarketing").GetAwaiter().GetResult().First(); GitRefUpdate refUpdate = new GitRefUpdate() { Name = $"refs/heads/OfficeMarketing", OldObjectId = branch.ObjectId, }; GitCommitRef newCommit = new GitCommitRef() { Comment = "add Json and xml file", Changes = new GitChange[] { new GitChange() { ChangeType = VersionControlChangeType.Add, Item = new GitItem() { Path = $"IRIS/Chatbot/Source/" + ChampaignNamelabel1.Text + "/" + ChampaignNamelabel1.Text + ".en-US.json" }, NewContent = new ItemContent() { Content = writeToJson(), ContentType = ItemContentType.RawText, } }, new GitChange() { ChangeType = VersionControlChangeType.Add, Item = new GitItem() { Path = $"IRIS/Chatbot/Source/" + ChampaignNamelabel1.Text + "/ExceptionMarketReference.xml" }, NewContent = new ItemContent() { Content = writeToXml(), ContentType = ItemContentType.RawText, } } }, }; // create the push with the new branch and commit GitPush push = gitClient.CreatePushAsync(new GitPush() { RefUpdates = new GitRefUpdate[] { refUpdate }, Commits = new GitCommitRef[] { newCommit }, }, repo.Id).GetAwaiter().GetResult(); } catch (VssUnauthorizedException e) { Form3 f3 = new Form3(); f3.ShowDialog(); if (f3.DialogResult == DialogResult.OK) { try { uploadFile(f3.UserName, f3.Password); MessageBox.Show("Upload Successfully"); } catch (Exception ex) { MessageBox.Show("Upload Fail:" + ex.Message); } } } catch (Exception ex) { MessageBox.Show("UpLoad Fail:" + ex.Message); } }
private void uploadFile(string userName, string password) { NetworkCredential netCred = new NetworkCredential(userName, password); WindowsCredential winCred = new WindowsCredential(netCred); VssCredentials creds = new VssClientCredentials(winCred); creds.Storage = new VssClientCredentialStorage(); // Connect to VSTS VssConnection connection = new VssConnection(new Uri(c_collectionUri), creds); // Get a GitHttpClient to talk to the Git endpoints GitHttpClient gitClient = connection.GetClient <GitHttpClient>(); // Get data about a specific repository var repo = gitClient.GetRepositoryAsync(c_projectName, c_repoName).GetAwaiter().GetResult(); GitRef branch = gitClient.GetRefsAsync(repo.Id, filter: "heads/OfficeMarketing").GetAwaiter().GetResult().First(); GitRefUpdate refUpdate = new GitRefUpdate() { Name = $"refs/heads/OfficeMarketing", OldObjectId = branch.ObjectId, }; GitCommitRef newCommit = new GitCommitRef() { Comment = "add Json and xml file", Changes = new GitChange[] { new GitChange() { ChangeType = VersionControlChangeType.Add, Item = new GitItem() { Path = $"IRIS/Chatbot/Source/" + ChampaignNamelabel1.Text + "/" + ChampaignNamelabel1.Text + ".en-US.json" }, NewContent = new ItemContent() { Content = writeToJson(), ContentType = ItemContentType.RawText, } }, new GitChange() { ChangeType = VersionControlChangeType.Add, Item = new GitItem() { Path = $"IRIS/Chatbot/Source/" + ChampaignNamelabel1.Text + "/ExceptionMarketReference.xml" }, NewContent = new ItemContent() { Content = writeToXml(), ContentType = ItemContentType.RawText, } } }, }; // create the push with the new branch and commit GitPush push = gitClient.CreatePushAsync(new GitPush() { RefUpdates = new GitRefUpdate[] { refUpdate }, Commits = new GitCommitRef[] { newCommit }, }, repo.Id).GetAwaiter().GetResult(); }