Example #1
0
        public List <GitPullRequestStatus> GetPullRequestIterationStatuses()
        {
            VssConnection connection = this.Context.Connection;
            GitHttpClient gitClient  = connection.GetClient <GitHttpClient>();

            TeamProjectReference project     = ClientSampleHelpers.FindAnyProject(this.Context);
            GitRepository        repo        = GitSampleHelpers.FindAnyRepository(this.Context, project.Id);
            GitPullRequest       pullRequest = GitSampleHelpers.CreatePullRequest(this.Context, repo);

            GitSampleHelpers.CreatePullRequestStatus(this.Context, repo.Id, pullRequest.PullRequestId, 1);
            GitSampleHelpers.CreatePullRequestStatus(this.Context, repo.Id, pullRequest.PullRequestId, 1);

            Console.WriteLine($"project {project.Name}, repo {repo.Name}, pullRequestId {pullRequest.PullRequestId}");

            List <GitPullRequestStatus> iterationStatuses = gitClient.GetPullRequestIterationStatusesAsync(repo.Id, pullRequest.PullRequestId, 1).Result;

            Console.WriteLine($"{iterationStatuses.Count} statuses found for pull request {pullRequest.PullRequestId} iteration {1}");
            foreach (var status in iterationStatuses)
            {
                Console.WriteLine($"{status.Description}({status.Context.Genre}/{status.Context.Name}) with id {status.Id}");
            }

            GitSampleHelpers.AbandonPullRequest(this.Context, repo, pullRequest.PullRequestId);

            return(iterationStatuses);
        }
Example #2
0
        public IEnumerable <GitPush> ListPushesInLast10Days()
        {
            VssConnection connection = this.Context.Connection;
            GitHttpClient gitClient  = connection.GetClient <GitHttpClient>();

            TeamProjectReference project = ClientSampleHelpers.FindAnyProject(this.Context);
            GitRepository        repo    = GitSampleHelpers.FindAnyRepository(this.Context, project.Id);

            List <GitPush> pushes = gitClient.GetPushesAsync(
                repo.Id,
                searchCriteria: new GitPushSearchCriteria()
            {
                FromDate = DateTime.UtcNow - TimeSpan.FromDays(10),
                ToDate   = DateTime.UtcNow,
            }).Result;

            Console.WriteLine("project {0}, repo {1}", project.Name, repo.Name);
            foreach (GitPush push in pushes)
            {
                Console.WriteLine("push {0} by {1} on {2}",
                                  push.PushId, push.PushedBy.DisplayName, push.Date);
            }

            return(pushes);
        }
Example #3
0
        public PropertiesCollection GetPullRequestProperties()
        {
            VssConnection connection = Context.Connection;
            GitHttpClient gitClient  = connection.GetClient <GitHttpClient>();

            TeamProjectReference project     = ClientSampleHelpers.FindAnyProject(this.Context);
            GitRepository        repo        = GitSampleHelpers.FindAnyRepository(this.Context, project.Id);
            GitPullRequest       pullRequest = GitSampleHelpers.CreatePullRequest(this.Context, repo);

            using (new ClientSampleHttpLoggerOutputSuppression())
            {
                JsonPatchDocument patch = new JsonPatchDocument();
                patch.Add(new JsonPatchOperation()
                {
                    Operation = Operation.Add, Path = "/sampleId", Value = 8
                });
                patch.Add(new JsonPatchOperation()
                {
                    Operation = Operation.Add, Path = "/startedDateTime", Value = DateTime.UtcNow
                });

                gitClient.UpdatePullRequestPropertiesAsync(patch, repo.Id, pullRequest.PullRequestId).SyncResult();
            }

            Console.WriteLine("project {0}, repo {1}, pullRequestId {2}", project.Name, repo.Name, pullRequest.PullRequestId);

            PropertiesCollection properties = gitClient.GetPullRequestPropertiesAsync(repo.Id, pullRequest.PullRequestId).SyncResult();

            Console.WriteLine($"Pull request {pullRequest.PullRequestId} has {properties.Count} properties");

            GitSampleHelpers.AbandonPullRequest(this.Context, repo, pullRequest.PullRequestId);

            return(properties);
        }
        public IEnumerable <GitPullRequest> ListPullRequestsIntoMaster()
        {
            VssConnection connection = this.Context.Connection;
            GitHttpClient gitClient  = connection.GetClient <GitHttpClient>();

            TeamProjectReference project = ClientSampleHelpers.FindAnyProject(this.Context);
            GitRepository        repo    = GitSampleHelpers.FindAnyRepository(this.Context, project.Id);

            List <GitPullRequest> prs = gitClient.GetPullRequestsAsync(
                repo.Id,
                new GitPullRequestSearchCriteria()
            {
                TargetRefName = "refs/heads/master",
            }).Result;

            Console.WriteLine("project {0}, repo {1}", project.Name, repo.Name);
            foreach (GitPullRequest pr in prs)
            {
                Console.WriteLine("{0} #{1} {2} -> {3}",
                                  pr.Title.Substring(0, Math.Min(40, pr.Title.Length)),
                                  pr.PullRequestId,
                                  pr.SourceRefName,
                                  pr.TargetRefName);
            }

            return(prs);
        }
Example #5
0
        public void UpdatePullRequestIterationStatuses()
        {
            VssConnection connection = this.Context.Connection;
            GitHttpClient gitClient  = connection.GetClient <GitHttpClient>();

            TeamProjectReference project     = ClientSampleHelpers.FindAnyProject(this.Context);
            GitRepository        repo        = GitSampleHelpers.FindAnyRepository(this.Context, project.Id);
            GitPullRequest       pullRequest = GitSampleHelpers.CreatePullRequest(this.Context, repo);

            GitPullRequestStatus status1 = GitSampleHelpers.CreatePullRequestStatus(this.Context, repo.Id, pullRequest.PullRequestId, 1);
            GitPullRequestStatus status2 = GitSampleHelpers.CreatePullRequestStatus(this.Context, repo.Id, pullRequest.PullRequestId, 1);

            Console.WriteLine($"project {project.Name}, repo {repo.Name}, pullRequestId {pullRequest.PullRequestId}");

            var patch = new JsonPatchDocument();

            patch.Add(new JsonPatchOperation()
            {
                Operation = VisualStudio.Services.WebApi.Patch.Operation.Remove, Path = $"/{status1.Id}"
            });
            patch.Add(new JsonPatchOperation()
            {
                Operation = VisualStudio.Services.WebApi.Patch.Operation.Remove, Path = $"/{status2.Id}"
            });

            gitClient.UpdatePullRequestIterationStatusesAsync(patch, repo.Id, pullRequest.PullRequestId, 1).SyncResult();

            Console.WriteLine($"Statuses {status1.Id}, and {status2.Id} deleted from the pull request {pullRequest.PullRequestId}, iteration {1}");

            GitSampleHelpers.AbandonPullRequest(this.Context, repo, pullRequest.PullRequestId);
        }
        public List <GitCommitRef> GetAllCommits()
        {
            GitRepository repo = GitSampleHelpers.FindAnyRepositoryOnAnyProject(this.Context);

            return(this.Context.Connection.GetClient <GitHttpClient>()
                   .GetCommitsAsync(repo.Id, new GitQueryCommitsCriteria()).Result);
        }
Example #7
0
        public IEnumerable <GitPush> ListPushesIntoDefault()
        {
            VssConnection connection = this.Context.Connection;
            GitHttpClient gitClient  = connection.GetClient <GitHttpClient>();

            TeamProjectReference project = ClientSampleHelpers.FindAnyProject(this.Context);
            GitRepository        repo    = GitSampleHelpers.FindAnyRepository(this.Context, project.Id);
            string branchName            = repo.DefaultBranch;

            List <GitPush> pushes = gitClient.GetPushesAsync(
                repo.Id,
                searchCriteria: new GitPushSearchCriteria()
            {
                IncludeRefUpdates = true,
                RefName           = branchName,
            }).Result;

            Console.WriteLine("project {0}, repo {1}", project.Name, repo.Name);
            foreach (GitPush push in pushes)
            {
                Console.WriteLine("push {0} by {1} on {2}",
                                  push.PushId, push.PushedBy.DisplayName, push.Date);
            }

            return(pushes);
        }
        public List <GitCommitRef> GetCommitsByCommitter()
        {
            GitRepository repo = GitSampleHelpers.FindAnyRepositoryOnAnyProject(this.Context);

            return(this.Context.Connection.GetClient <GitHttpClient>()
                   .GetCommitsAsync(repo.Id, new GitQueryCommitsCriteria()
            {
                Committer = "*****@*****.**"
            }).Result);
        }
        public IEnumerable <GitBranchStats> GetBranchStatsForAFewBranches()
        {
            VssConnection connection = this.Context.Connection;
            GitHttpClient gitClient  = connection.GetClient <GitHttpClient>();

            TeamProjectReference project = ClientSampleHelpers.FindAnyProject(this.Context);
            GitRepository        repo    = GitSampleHelpers.FindAnyRepository(this.Context, project.Id);

            // find a handful of branches to compare
            List <GitRef>        branches    = gitClient.GetRefsAsync(repo.Id, filter: "heads/").Result;
            IEnumerable <string> branchNames = from branch in branches
                                               where branch.Name.StartsWith("refs/heads/")
                                               select branch.Name.Substring("refs/heads/".Length);

            if (branches.Count < 1)
            {
                throw new Exception($"Repo {repo.Name} doesn't have any branches in it.");
            }

            if (string.IsNullOrEmpty(repo.DefaultBranch))
            {
                throw new Exception($"Repo {repo.Name} doesn't have a default branch");
            }

            string defaultBranchName = repo.DefaultBranch.Substring("refs/heads/".Length);

            // list up to 10 branches we're interested in comparing
            GitQueryBranchStatsCriteria criteria = new GitQueryBranchStatsCriteria()
            {
                baseVersionDescriptor = new GitVersionDescriptor
                {
                    VersionType = GitVersionType.Branch,
                    Version     = defaultBranchName,
                },
                targetVersionDescriptors = branchNames
                                           .Take(10)
                                           .Select(branchName => new GitVersionDescriptor()
                {
                    Version     = branchName,
                    VersionType = GitVersionType.Branch,
                })
                                           .ToArray()
            };

            List <GitBranchStats> stats = gitClient.GetBranchStatsBatchAsync(criteria, repo.Id).Result;

            Console.WriteLine("project {0}, repo {1}", project.Name, repo.Name);
            foreach (GitBranchStats stat in stats)
            {
                Console.WriteLine(" branch `{0}` is {1} ahead, {2} behind `{3}`",
                                  stat.Name, stat.AheadCount, stat.BehindCount, defaultBranchName);
            }

            return(stats);
        }
Example #10
0
        public List <GitCommitRef> GetCommitsReachableFromACommit()
        {
            GitRepository repo = GitSampleHelpers.FindAnyRepositoryOnAnyProject(this.Context);

            return(this.Context.Connection.GetClient <GitHttpClient>()
                   .GetCommitsAsync(repo.Id, new GitQueryCommitsCriteria()
            {
                // Earliest commit in the graph to search.
                CompareVersion = m_oldestDescriptor
            }).Result);
        }
Example #11
0
        public List <GitCommitRef> GetCommitsInDateRange()
        {
            GitRepository repo = GitSampleHelpers.FindAnyRepositoryOnAnyProject(this.Context);

            return(this.Context.Connection.GetClient <GitHttpClient>()
                   .GetCommitsAsync(repo.Id, new GitQueryCommitsCriteria()
            {
                FromDate = new DateTime(2018, 6, 14).ToString(),
                ToDate = new DateTime(2018, 6, 16).ToString()
            }).Result);
        }
Example #12
0
        public List <GitCommitRef> GetCommitsReachableFromACommitAndInPath()
        {
            GitRepository repo = GitSampleHelpers.FindAnyRepositoryOnAnyProject(this.Context);

            return(this.Context.Connection.GetClient <GitHttpClient>()
                   .GetCommitsAsync(repo.Id, new GitQueryCommitsCriteria()
            {
                CompareVersion = m_tipCommitDescriptor,
                ItemVersion = m_oldestDescriptor,
                ItemPath = "/README.md",
            }).Result);
        }
Example #13
0
        public GitRevert CreateRevert()
        {
            VssConnection connection = this.Context.Connection;
            GitHttpClient gitClient  = connection.GetClient <GitHttpClient>();

            Guid          projectId  = ClientSampleHelpers.FindAnyProject(this.Context).Id;
            GitRepository repo       = GitSampleHelpers.FindAnyRepository(this.Context, projectId);
            string        branchName = repo.DefaultBranch;
            string        branchNameWithoutRefsHeads = branchName.Remove(0, "refs/heads/".Length);

            // find the latest commit on default
            GitCommitRef latestCommitOnDefault = gitClient.GetCommitsAsync(repo.Id, new GitQueryCommitsCriteria()
            {
                ItemVersion = new GitVersionDescriptor()
                {
                    Version     = branchNameWithoutRefsHeads,
                    VersionType = GitVersionType.Branch
                },
                Top = 1
            }).Result.First();

            // generate a unique name to suggest for the branch
            string suggestedBranchName = "refs/heads/azure-devops-dotnet-samples/" + GitSampleHelpers.ChooseRefsafeName();

            // write down the name for a later sample
            this.Context.SetValue <string>("$gitSamples.suggestedRevertBranchName", suggestedBranchName);

            // revert it relative to default branch
            GitRevert revert = gitClient.CreateRevertAsync(
                new GitAsyncRefOperationParameters()
            {
                OntoRefName      = branchName,
                GeneratedRefName = suggestedBranchName,
                Repository       = repo,
                Source           = new GitAsyncRefOperationSource()
                {
                    CommitList = new GitCommitRef[] { new GitCommitRef()
                                                      {
                                                          CommitId = latestCommitOnDefault.CommitId
                                                      } }
                },
            },
                projectId,
                repo.Id).Result;

            Console.WriteLine("Revert {0} created", revert.RevertId);

            // typically, the next thing you'd do is create a PR for this revert
            return(revert);
        }
Example #14
0
        public List <GitCommitRef> GetCommitsOnABranch()
        {
            GitRepository repo = GitSampleHelpers.FindAnyRepositoryOnAnyProject(this.Context);

            return(this.Context.Connection.GetClient <GitHttpClient>()
                   .GetCommitsAsync(repo.Id, new GitQueryCommitsCriteria()
            {
                ItemVersion = new GitVersionDescriptor()
                {
                    VersionType = GitVersionType.Branch,
                    VersionOptions = GitVersionOptions.None,
                    Version = "master"
                }
            }).Result);
        }
Example #15
0
        public List <GitCommitRef> GetCommitsOnABranch()
        {
            GitRepository repo       = GitSampleHelpers.FindAnyRepositoryOnAnyProject(this.Context);
            string        branchName = repo.DefaultBranch;
            string        branchNameWithoutRefsHeads = branchName.Remove(0, "refs/heads/".Length);

            return(this.Context.Connection.GetClient <GitHttpClient>()
                   .GetCommitsAsync(repo.Id, new GitQueryCommitsCriteria()
            {
                ItemVersion = new GitVersionDescriptor()
                {
                    VersionType = GitVersionType.Branch,
                    VersionOptions = GitVersionOptions.None,
                    Version = branchNameWithoutRefsHeads
                }
            }).Result);
        }
Example #16
0
        public GitRefUpdateResult CreateBranchInner(bool cleanUp)
        {
            VssConnection connection = this.Context.Connection;
            GitHttpClient gitClient  = connection.GetClient <GitHttpClient>();

            // find a project, repo, and source ref to branch from
            TeamProjectReference project = ClientSampleHelpers.FindAnyProject(this.Context);
            GitRepository        repo    = GitSampleHelpers.FindAnyRepository(this.Context, project.Id);
            string defaultBranch         = GitSampleHelpers.WithoutRefsPrefix(repo.DefaultBranch);
            GitRef sourceRef             = gitClient.GetRefsAsync(repo.Id, filter: defaultBranch).Result.First();

            // create a new branch from the source
            GitRefUpdateResult refCreateResult = gitClient.UpdateRefsAsync(
                new GitRefUpdate[] { new GitRefUpdate()
                                     {
                                         OldObjectId = new string('0', 40),
                                         NewObjectId = sourceRef.ObjectId,
                                         Name        = $"refs/heads/vsts-api-sample/{GitSampleHelpers.ChooseRefsafeName()}",
                                     } },
                repositoryId: repo.Id).Result.First();

            Console.WriteLine("project {0}, repo {1}, source branch {2}", project.Name, repo.Name, sourceRef.Name);
            Console.WriteLine("new branch {0} (success={1} status={2})", refCreateResult.Name, refCreateResult.Success, refCreateResult.UpdateStatus);

            if (cleanUp)
            {
                // silently (no logging) delete up the branch we just created
                ClientSampleHttpLogger.SetSuppressOutput(this.Context, true);
                GitRefUpdateResult refDeleteResult = gitClient.UpdateRefsAsync(
                    new GitRefUpdate[]
                {
                    new GitRefUpdate()
                    {
                        OldObjectId = refCreateResult.NewObjectId,
                        NewObjectId = new string('0', 40),
                        Name        = refCreateResult.Name,
                    }
                },
                    repositoryId: refCreateResult.RepositoryId).Result.First();

                return(null);
            }

            return(refCreateResult);
        }
Example #17
0
        public IEnumerable <GitItem> ListItems()
        {
            VssConnection connection = this.Context.Connection;
            GitHttpClient gitClient  = connection.GetClient <GitHttpClient>();

            TeamProjectReference project = ClientSampleHelpers.FindAnyProject(this.Context);
            GitRepository        repo    = GitSampleHelpers.FindAnyRepository(this.Context, project.Id);

            List <GitItem> items = gitClient.GetItemsAsync(repo.Id, scopePath: "/", recursionLevel: VersionControlRecursionType.OneLevel).Result;

            Console.WriteLine("project {0}, repo {1}", project.Name, repo.Name);
            foreach (GitItem item in items)
            {
                Console.WriteLine("{0} {1} {2}", item.GitObjectType, item.ObjectId, item.Path);
            }

            return(items);
        }
Example #18
0
        public IEnumerable <GitRef> ListBranches()
        {
            VssConnection connection = this.Context.Connection;
            GitHttpClient gitClient  = connection.GetClient <GitHttpClient>();

            TeamProjectReference project = ClientSampleHelpers.FindAnyProject(this.Context);
            GitRepository        repo    = GitSampleHelpers.FindAnyRepository(this.Context, project.Id);

            List <GitRef> refs = gitClient.GetRefsAsync(repo.Id, filter: "heads/").Result;

            Console.WriteLine("project {0}, repo {1}", project.Name, repo.Name);
            foreach (GitRef gitRef in refs)
            {
                Console.WriteLine("{0} {1} {2}", gitRef.Name, gitRef.ObjectId, gitRef.Url);
            }

            return(refs);
        }
Example #19
0
        public GitItem GetItem()
        {
            VssConnection connection = this.Context.Connection;
            GitHttpClient gitClient  = connection.GetClient <GitHttpClient>();

            TeamProjectReference project = ClientSampleHelpers.FindAnyProject(this.Context);
            GitRepository        repo    = GitSampleHelpers.FindAnyRepository(this.Context, project.Id);

            // get a filename we know exists
            string filename = gitClient.GetItemsAsync(repo.Id, scopePath: "/", recursionLevel: VersionControlRecursionType.OneLevel).Result
                              .Where(o => o.GitObjectType == GitObjectType.Blob).FirstOrDefault().Path;

            // retrieve the contents of the file
            GitItem item = gitClient.GetItemAsync(repo.Id, filename, includeContent: true).Result;

            Console.WriteLine("File {0} at commit {1} is of length {2}", filename, item.CommitId, item.Content.Length);

            return(item);
        }
Example #20
0
        public void DeletePullRequestIterationStatus()
        {
            VssConnection connection = this.Context.Connection;
            GitHttpClient gitClient  = connection.GetClient <GitHttpClient>();

            TeamProjectReference project     = ClientSampleHelpers.FindAnyProject(this.Context);
            GitRepository        repo        = GitSampleHelpers.FindAnyRepository(this.Context, project.Id);
            GitPullRequest       pullRequest = GitSampleHelpers.CreatePullRequest(this.Context, repo);

            GitPullRequestStatus status = GitSampleHelpers.CreatePullRequestStatus(this.Context, repo.Id, pullRequest.PullRequestId, 1);

            Console.WriteLine($"project {project.Name}, repo {repo.Name}, pullRequestId {pullRequest.PullRequestId}");

            gitClient.DeletePullRequestIterationStatusAsync(repo.Id, pullRequest.PullRequestId, 1, status.Id).SyncResult();

            Console.WriteLine($"Status {status.Id} deleted from pull request {pullRequest.PullRequestId}, iteration {1}");

            GitSampleHelpers.AbandonPullRequest(this.Context, repo, pullRequest.PullRequestId);
        }
Example #21
0
        public GitPullRequestStatus GetPullRequestIterationStatus()
        {
            VssConnection connection = this.Context.Connection;
            GitHttpClient gitClient  = connection.GetClient <GitHttpClient>();

            TeamProjectReference project         = ClientSampleHelpers.FindAnyProject(this.Context);
            GitRepository        repo            = GitSampleHelpers.FindAnyRepository(this.Context, project.Id);
            GitPullRequest       pullRequest     = GitSampleHelpers.CreatePullRequest(this.Context, repo);
            GitPullRequestStatus generatedStatus = GitSampleHelpers.CreatePullRequestStatus(this.Context, repo.Id, pullRequest.PullRequestId, 1);

            Console.WriteLine($"project {project.Name}, repo {repo.Name}, pullRequestId {pullRequest.PullRequestId}");

            GitPullRequestStatus status = gitClient.GetPullRequestIterationStatusAsync(repo.Id, pullRequest.PullRequestId, 1, generatedStatus.Id).Result;

            Console.WriteLine($"{status.Description}({status.Context.Genre}/{status.Context.Name}) with id {status.Id}");

            GitSampleHelpers.AbandonPullRequest(this.Context, repo, pullRequest.PullRequestId);

            return(status);
        }
Example #22
0
        public List <GitCommitRef> GetCommitsReachableFromACommitAndInPath()
        {
            GitRepository        repo       = GitSampleHelpers.FindAnyRepositoryOnAnyProject(this.Context);
            string               branchName = repo.DefaultBranch;
            string               branchNameWithoutRefsHeads = branchName.Remove(0, "refs/heads/".Length);
            GitVersionDescriptor tipCommitDescriptor        = new GitVersionDescriptor()
            {
                VersionType    = GitVersionType.Branch,
                VersionOptions = GitVersionOptions.None,
                Version        = branchNameWithoutRefsHeads
            };


            return(this.Context.Connection.GetClient <GitHttpClient>()
                   .GetCommitsAsync(repo.Id, new GitQueryCommitsCriteria()
            {
                CompareVersion = tipCommitDescriptor,
                ItemVersion = m_oldestDescriptor,
                ItemPath = "/README.md",
            }).Result);
        }
        public GitPullRequestStatus CreatePullRequestStatusWithCustomProperties()
        {
            VssConnection connection = this.Context.Connection;
            GitHttpClient gitClient  = connection.GetClient <GitHttpClient>();

            TeamProjectReference project     = ClientSampleHelpers.FindAnyProject(this.Context);
            GitRepository        repo        = GitSampleHelpers.FindAnyRepository(this.Context, project.Id);
            GitPullRequest       pullRequest = GitSampleHelpers.CreatePullRequest(this.Context, repo);

            Console.WriteLine("project {0}, repo {1}, pullRequestId {2}", project.Name, repo.Name, pullRequest.PullRequestId);

            GitPullRequestStatus status = GitSampleHelpers.GenerateSampleStatus(includeProperties: true);

            GitPullRequestStatus createdStatus = gitClient.CreatePullRequestStatusAsync(status, repo.Id, pullRequest.PullRequestId).Result;

            Console.WriteLine($"{createdStatus.Description}({createdStatus.Context.Genre}/{createdStatus.Context.Name}) with id {createdStatus.Id} created");

            GitSampleHelpers.AbandonPullRequest(this.Context, repo, pullRequest.PullRequestId);

            return(createdStatus);
        }
Example #24
0
        public PropertiesCollection AddPullRequestProperties()
        {
            VssConnection connection = Context.Connection;
            GitHttpClient gitClient  = connection.GetClient <GitHttpClient>();

            TeamProjectReference project     = ClientSampleHelpers.FindAnyProject(this.Context);
            GitRepository        repo        = GitSampleHelpers.FindAnyRepository(this.Context, project.Id);
            GitPullRequest       pullRequest = GitSampleHelpers.CreatePullRequest(this.Context, repo);

            Console.WriteLine("project {0}, repo {1}, pullRequestId {2}", project.Name, repo.Name, pullRequest.PullRequestId);

            JsonPatchDocument patch = new JsonPatchDocument();

            patch.Add(new JsonPatchOperation()
            {
                Operation = Operation.Add, Path = "/sampleId", Value = 8
            });
            patch.Add(new JsonPatchOperation()
            {
                Operation = Operation.Add, Path = "/startedDateTime", Value = DateTime.UtcNow
            });
            patch.Add(new JsonPatchOperation()
            {
                Operation = Operation.Add,
                Path      = "",
                Value     = new Dictionary <string, object>()
                {
                    { "bytes", Encoding.UTF8.GetBytes("this is sample base64 encoded string") },
                    { "globalId", Guid.NewGuid() }
                }
            });

            PropertiesCollection properties = gitClient.UpdatePullRequestPropertiesAsync(patch, repo.Id, pullRequest.PullRequestId).SyncResult();

            Console.WriteLine($"Pull request {pullRequest.PullRequestId} has {properties.Count} properties");

            GitSampleHelpers.AbandonPullRequest(this.Context, repo, pullRequest.PullRequestId);

            return(properties);
        }
Example #25
0
        public GitRevert GetRevert()
        {
            VssConnection connection = this.Context.Connection;
            GitHttpClient gitClient  = connection.GetClient <GitHttpClient>();

            Guid          projectId = ClientSampleHelpers.FindAnyProject(this.Context).Id;
            GitRepository repo      = GitSampleHelpers.FindAnyRepository(this.Context, projectId);

            // pull out the branch name we suggested before
            string branchName;

            if (this.Context.TryGetValue <string>("$gitSamples.suggestedRevertBranchName", out branchName))
            {
                GitRevert revert = gitClient.GetRevertForRefNameAsync(projectId, repo.Id, branchName).Result;

                Console.WriteLine("Revert {0} found with status {1}", revert.RevertId, revert.Status);
                return(revert);
            }

            Console.WriteLine("(skipping sample; did not find a branch to check for reverts)");
            return(null);
        }
        public GitPullRequest AbandonPullRequest()
        {
            VssConnection connection = this.Context.Connection;
            GitHttpClient gitClient  = connection.GetClient <GitHttpClient>();

            TeamProjectReference project = ClientSampleHelpers.FindAnyProject(this.Context);
            GitRepository        repo    = GitSampleHelpers.FindAnyRepository(this.Context, project.Id);

            // first we need to create a pull request
            GitPullRequest pr = CreatePullRequestInner(cleanUp: false);

            // now abandon the PR
            GitPullRequest updatedPr = new GitPullRequest()
            {
                Status = PullRequestStatus.Abandoned,
            };
            GitPullRequest abandonedPr = gitClient.UpdatePullRequestAsync(updatedPr, repo.Id, pr.PullRequestId).Result;

            Console.WriteLine("{0} (#{1}) {2}",
                              abandonedPr.Title.Substring(0, Math.Min(40, pr.Title.Length)),
                              abandonedPr.PullRequestId,
                              abandonedPr.Status);

            // delete the branch that was associated with the PR (and do not log)
            ClientSampleHttpLogger.SetSuppressOutput(this.Context, true);
            GitRefUpdateResult refDeleteResult = gitClient.UpdateRefsAsync(
                new GitRefUpdate[]
            {
                new GitRefUpdate()
                {
                    OldObjectId = gitClient.GetRefsAsync(repo.Id, filter: GitSampleHelpers.WithoutRefsPrefix(pr.SourceRefName)).Result.First().ObjectId,
                    NewObjectId = new string('0', 40),
                    Name        = pr.SourceRefName,
                }
            },
                repositoryId: repo.Id).Result.First();

            return(abandonedPr);
        }
Example #27
0
        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);
        }