private IEnumerable <GitPullRequestCommentThread> CreateDiscussionThreads( GitHttpClient gitClient, IEnumerable <IIssue> issues, string commentSource) { // ReSharper disable once PossibleMultipleEnumeration issues.NotNull(nameof(issues)); this.Log.Verbose("Creating new discussion threads"); var result = new List <GitPullRequestCommentThread>(); // Code flow properties var iterationId = 0; GitPullRequestIterationChanges changes = null; if (this.tfsPullRequest.CodeReviewId > 0) { iterationId = this.GetCodeFlowLatestIterationId(gitClient); changes = this.GetCodeFlowChanges(gitClient, iterationId); } // Filter isues not related to a file. if (!this.settings.ReportIssuesNotRelatedToAFile) { issues = issues.Where(x => x.AffectedFileRelativePath != null); } // ReSharper disable once PossibleMultipleEnumeration foreach (var issue in issues) { this.Log.Information( "Creating a discussion comment for the issue at line {0} from {1}", issue.Line, issue.AffectedFileRelativePath); var newThread = new GitPullRequestCommentThread() { Status = CommentThreadStatus.Active }; var discussionComment = new Comment { CommentType = CommentType.System, IsDeleted = false, Content = ContentProvider.GetContent(issue) }; if (!this.AddThreadProperties(newThread, changes, issue, iterationId, commentSource)) { continue; } newThread.Comments = new List <Comment> { discussionComment }; result.Add(newThread); } return(result); }
public static WikiV2 FindOrCreateCodeWiki(VssConnection connection, Guid projectId) { WikiHttpClient wikiClient = connection.GetClient <WikiHttpClient>(); List <WikiV2> wikis = wikiClient.GetAllWikisAsync(projectId).SyncResult(); WikiV2 wikiToReturn = wikis != null && wikis.Count != 0 ? wikis.Find(w => w.Type == WikiType.CodeWiki) : null; if (wikiToReturn == null) { // No code wiki existing. Create one. GitHttpClient gitClient = connection.GetClient <GitHttpClient>(); List <GitRepository> repositories = gitClient.GetRepositoriesAsync(projectId).Result; Guid repositoryId = repositories[0].Id; var createParameters = new WikiCreateParametersV2() { Name = "sampleCodeWiki", ProjectId = projectId, RepositoryId = repositoryId, Type = WikiType.CodeWiki, MappedPath = "/", // any folder path in the repository Version = new GitVersionDescriptor() { Version = "main" } }; wikiToReturn = wikiClient.CreateWikiAsync(createParameters).SyncResult(); } return(wikiToReturn); }
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); }
/// <summary> /// Retrieves all active pull requests this user has created. /// </summary> /// <returns>An async stream of <see cref="PullRequestViewElement"/></returns> public async IAsyncEnumerable <PullRequestViewElement> FetchCreatedPullRequests() { foreach (var accountGroup in m_config.AccountsByUri) { Uri organizationUri = accountGroup.Key; using VssConnection connection = await GetConnectionAsync(organizationUri, accountGroup.Value); using GitHttpClient client = await connection.GetClientAsync <GitHttpClient>(); { // Capture the currentUserId so it can be used to filter PR's later. // Guid userId = connection.AuthorizedIdentity.Id; // Only fetch pull requests which are active, and assigned to this user. // GitPullRequestSearchCriteria criteria = new GitPullRequestSearchCriteria { CreatorId = userId, Status = PullRequestStatus.Active, IncludeLinks = false, }; foreach (AccountConfig account in accountGroup.Value) { List <GitPullRequest> requests = await client.GetPullRequestsByProjectAsync(account.Project, criteria); foreach (var request in requests) { yield return(new PullRequestViewElement(request, account.Handler !) { CreatedMode = true });
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); }
public async Task <IEnumerable <GitCommitRef> > GetLastCommitsAsync( Guid serviceId, Guid repositoryId, string branch, int top = 10, CancellationToken cancellationToken = default) { AzureDevOpsConnectedService service = await ClientFactory.ConnectAsync( serviceId, cancellationToken); GitHttpClient client = ClientFactory.CreateClient <GitHttpClient>(serviceId); return(await client.GetCommitsAsync( service.DefaultProject, repositoryId, new GitQueryCommitsCriteria() { ItemVersion = new GitVersionDescriptor() { VersionType = GitVersionType.Branch, VersionOptions = GitVersionOptions.None, Version = branch }, IncludeLinks = true }, top : top, cancellationToken : cancellationToken) .ConfigureAwait(false)); }
/// <summary> /// Creates a pull request, and then adds a reviewer to it. /// </summary> /// <param name="gitHttpClient"> GitHttpClient that is created for accessing vsts</param> /// <param name="gitPullRequest"> the pull request to be created</param> /// <param name="repositoryId"> the unique identifier of the repository</param> /// <param name="reviewerAlias"> reviewer's alias in vsts</param> /// <param name="vstsAccountUrl">vsts account's url</param> /// <param name="personalToken"> personal access token to access the vsts account. </param> public static async void CreatePullRequestAndAddReviewer( GitHttpClient gitHttpClient, GitPullRequest gitPullRequest, string repositoryId, string reviewerAlias, Uri vstsAccountUrl, string personalToken) { // 1- Create the pull request. GitPullRequest pullRequest = gitHttpClient.CreatePullRequestAsync(gitPullRequest, repositoryId, cancellationToken: CancellationToken.None).Result; // 2- Create an Identity Client to get the reviewer's vsts id IdentityHttpClient identityHttpClient = CreateIdentityClient(vstsAccountUrl, personalToken); // 3- Find the reviewer's vsts identity. Identity identity = SearchForReviewerVstsIdentity(identityHttpClient, reviewerAlias).Result; // 4- Create a IdentityRefWithVote for the reviewer IdentityRefWithVote identityRefWithVote = new IdentityRefWithVote { Id = identity.Id.ToString(), IsRequired = true // false otherwise. }; // 5- Finally add the reviewer to the pull request. await AddReviewerToPullRequest(gitHttpClient, pullRequest, identityRefWithVote); }
/// <summary> /// Gets a value indicating whether a branch with name <paramref name="branch"/> (like 'master', 'dev') contains the commit with specified <paramref name="commitId"/>. /// Just like the <code>git branch --contains</code> it doesn't take possible reversions into account. /// </summary> public static Boolean BranchContains(this GitHttpClient git, String project, String repositoryId, String branch, String commitId) { var commitToFind = git.TryGetCommit(project: project, repositoryId: repositoryId, commitId: commitId); if (commitToFind == null) { return(false); } var committedDate = commitToFind.Committer.Date; // TODO: It will usually be the same as the author's, but I have failed to check what date TFS actually uses in date queries. var criteria = new GitQueryCommitsCriteria { ItemVersion = new GitVersionDescriptor { Version = branch, VersionType = GitVersionType.Branch }, FromDate = DateToString(committedDate.AddSeconds(-1)), // Zero length interval seems to work, but just in case ToDate = DateToString(committedDate.AddSeconds(1)), }; var commitIds = git .GetAllCommits( project: project, repositoryId: repositoryId, searchCriteria: criteria) .Select(c => c.CommitId) .ToHashSet(StringComparer.InvariantCultureIgnoreCase); return(commitIds.Contains(commitId)); }
static void CloneRepositories(Options options) { VssCredentials creds = new VssBasicCredential(string.Empty, options.AccessToken); // Connect to Azure DevOps Services VssConnection connection = new VssConnection(options.CollectionUri, creds); ProjectHttpClient projClient = connection.GetClientAsync <ProjectHttpClient>().Result; var projects = projClient.GetProjects().Result; var cloneOptions = new CloneOptions() { CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials { Username = options.UserName, Password = options.AccessToken, } }; GitHttpClient gitClient = connection.GetClient <GitHttpClient>(); foreach (var project in projects) { var repositories = gitClient.GetRepositoriesAsync(project.Name).Result; if (repositories != null) { foreach (var repo in repositories) { string cloneDir = Path.Combine(options.OutputPath, project.Name, repo.Name); Console.WriteLine($"Cloning: {repo.RemoteUrl} to {cloneDir}"); Repository.Clone(repo.RemoteUrl, cloneDir, cloneOptions); } } } }
private bool ConfigureNextReleaseOnMaster(GitHttpClient gitClient, Guid repoId, VersionInfo versionInfo) { var nextVersion = new VersionInfo(versionInfo.ToString()); nextVersion.NextMinor(); nextVersion.LastScript = GetLastScriptName(); var topicBranchName = "dev/config-release-" + nextVersion.ToString(); gitClient.CreateBranch(repoId, "master", topicBranchName); if (!GitHelper.Checkout(topicBranchName, true, true)) { return(false); } SaveFileVersion(nextVersion); if (!GitHelper.AddAllFiles() || !GitHelper.Commit($"Inicialização da release {nextVersion}") || !GitHelper.Sync()) { return(false); } CreatePullRequest(gitClient, repoId, topicBranchName, "master", nextVersion); return(true); }
private static async Task <string> CheckAndPopulateFileContentAsync(GitHttpClient client, RepositoryReference repo, IEnumerable <GitTreeEntryRef> tree, string value, string folder = null) { if (string.IsNullOrEmpty(value) || !Uri.IsWellFormedUriString(value, UriKind.Relative)) { return(value); } var fileName = value.Split('/', StringSplitOptions.RemoveEmptyEntries).Last(); var filePath = string.IsNullOrEmpty(folder) ? fileName : $"{folder}/{fileName}"; var fileItem = tree.FirstOrDefault(i => i.RelativePath.Equals(filePath, StringComparison.Ordinal)); if (fileItem is null) { return(value); } var fileStream = await client .GetItemContentAsync(project : repo.Project, repo.Repository, fileItem.RelativePath, download : true, versionDescriptor : repo.VersionDescriptor()) .ConfigureAwait(false); using var streamReader = new StreamReader(fileStream); var file = await streamReader .ReadToEndAsync() .ConfigureAwait(false); return(string.IsNullOrEmpty(file) ? value : file); }
public static bool FindRepository(AzureDevOpsClientContext context, Guid projectId, string repositoryName, out GitRepository repo) { // Check if we already have a repo loaded VssConnection connection = context.Connection; GitHttpClient gitClient = connection.GetClient <GitHttpClient>(); // Check if an ID was already set (this could have been provided by the caller) if (!context.TryGetValue("repository" + repositoryName, out Guid repoId)) { repo = gitClient.GetRepositoriesAsync(projectId).Result.FirstOrDefault(c => c.Name == repositoryName); } else { repo = gitClient.GetRepositoryAsync(repoId.ToString()).Result; } if (repo != null) { context.SetValue("repository" + repositoryName, repo); } else { // create a project here? throw new Exception("No repos available for running the sample."); } return(repo != null); }
private void button1_Click(object sender, EventArgs e) { VssBasicCredential credential = new VssBasicCredential(string.Empty, textBox1.Text); GitHttpClient gitClient = new GitHttpClient(new Uri(textBox2.Text), credential); List <GitRepository> repositories = gitClient.GetRepositoriesAsync((bool?)null, null).GetAwaiter().GetResult(); List <KeyValuePair <GitRepository, Task <List <GitBranchStats> > > > branchStatsTasks = new List <KeyValuePair <GitRepository, Task <List <GitBranchStats> > > >(); List <KeyValuePair <GitRepository, GitBranchStats> > branches = new List <KeyValuePair <GitRepository, GitBranchStats> >(); StringBuilder builder = new StringBuilder(); StringBuilder fetchBuilder = new StringBuilder(); foreach (GitRepository repo in repositories) { builder.AppendLine("git clone " + repo.Url + " " + repo.Name); branchStatsTasks.Add(new KeyValuePair <GitRepository, Task <List <GitBranchStats> > >(repo, gitClient.GetBranchesAsync(repo.Id))); } textBox3.Text = builder.ToString(); foreach (KeyValuePair <GitRepository, Task <List <GitBranchStats> > > task in branchStatsTasks) { branches.AddRange(task.Value.GetAwaiter().GetResult().Where(o => o.Name.ToLowerInvariant() == "developer" || o.Name == task.Key.Name).Select(o => new KeyValuePair <GitRepository, GitBranchStats>(task.Key, o))); } foreach (KeyValuePair <GitRepository, GitBranchStats> branch in branches) { fetchBuilder.AppendLine("git -C ./" + branch.Key.Name + " fetch origin " + branch.Value.Name + ":" + branch.Value.Name); } textBox4.Text = fetchBuilder.ToString(); }
public override IEnumerable <PSObject> GetLiteralItem(Segment segment, Segment childSegment) { segment.GetProvider().WriteDebug("DriveItems.Projects.Git.Repos.GetLiteralItem(Segment, Segment)"); GitHttpClient httpClient = this.GetHttpClient(segment) as GitHttpClient; return(this.Wrap( segment, () => { string filter = childSegment.UnescapedName; string fullName = string.Format("refs/{0}", filter); return new[] { this.ConvertToChildDriveItem( segment, httpClient .GetRefsAsync( project: SegmentHelper.GetProjectName(segment), repositoryId: SegmentHelper.GetRepoName(segment), filter: filter, includeLinks: true) .Result .SingleOrDefault(x => string.Equals(x.Name, fullName, StringComparison.OrdinalIgnoreCase))) }; })); }
public WikiV2 UpdateWiki() { VssConnection connection = this.Context.Connection; GitHttpClient gitClient = connection.GetClient <GitHttpClient>(); WikiHttpClient wikiClient = connection.GetClient <WikiHttpClient>(); WikiV2 codeWiki = Helpers.FindOrCreateCodeWiki(this.Context); // Get the versions in that wiki List <GitVersionDescriptor> versions = codeWiki.Versions.ToList(); // Append the new version List <GitBranchStats> branches = gitClient.GetBranchesAsync(codeWiki.ProjectId, codeWiki.RepositoryId).SyncResult(); foreach (var branch in branches) { versions.Add(new GitVersionDescriptor() { Version = branch.Name }); } WikiUpdateParameters updateParams = new WikiUpdateParameters() { Versions = versions }; WikiV2 updatedCodeWiki = wikiClient.UpdateWikiAsync(updateParams, codeWiki.ProjectId, codeWiki.Name).SyncResult(); Context.Log("Updated wiki with name '{0}' in project '{1}'", updatedCodeWiki.Name, updatedCodeWiki.ProjectId); Context.Log("Updated versions are : {0}", string.Join(",", updatedCodeWiki.Versions.Select(v => v.Version))); return(updatedCodeWiki); }
public IEnumerable <GitCommitRef> ListCommitsForRepository() { VssConnection connection = this.Context.Connection; GitHttpClient gitClient = connection.GetClient <GitHttpClient>(); // Find a sample project to use for listing comments Guid projectId = ClientSampleHelpers.FindAnyProject(this.Context).Id; // Get first repo in the project Guid repoId = gitClient.GetRepositoriesAsync(projectId).Result[0].Id; // Get no more than 10 commits GitQueryCommitsCriteria criteria = new GitQueryCommitsCriteria() { Top = 10 }; List <GitCommitRef> commits = gitClient.GetCommitsAsync(repoId, criteria).Result; foreach (GitCommitRef commit in commits) { Console.WriteLine("{0} by {1} ({2})", commit.CommitId, commit.Committer.Email, commit.Comment); } return(commits); }
public WikiV2 CreateCodeWiki() { VssConnection connection = this.Context.Connection; GitHttpClient gitClient = connection.GetClient <GitHttpClient>(); WikiHttpClient wikiClient = connection.GetClient <WikiHttpClient>(); Guid projectId = ClientSampleHelpers.FindAnyProject(this.Context).Id; List <GitRepository> repositories = gitClient.GetRepositoriesAsync(projectId).Result; WikiV2 createdWiki = null; Guid repositoryId = repositories[0].Id; var createParameters = new WikiCreateParametersV2() { Name = "sampleCodeWiki", ProjectId = projectId, RepositoryId = repositoryId, Type = WikiType.CodeWiki, MappedPath = "/", // any folder path in the repository Version = new GitVersionDescriptor() { Version = "master" } }; createdWiki = wikiClient.CreateWikiAsync(createParameters).SyncResult(); Context.Log("Created wiki with name '{0}' in project '{1}'", createdWiki.Name, createdWiki.ProjectId); // Cleanup ClientSampleHttpLogger.SetSuppressOutput(this.Context, true); wikiClient.DeleteWikiAsync(createdWiki.Id).SyncResult(); return(createdWiki); }
public void CreateClients(string collectionUrl) { AzDConnection = SetUpConnection(collectionUrl); workItemTrackingHttpClient = AzDConnection.GetClient <WorkItemTrackingHttpClient>(); projectHttpClient = AzDConnection.GetClient <ProjectHttpClient>(); gitClient = AzDConnection.GetClient <GitHttpClient>(); }
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 ActionResult<IEnumerable<WorkItem>> Get() public async Task <IActionResult> Get() { await Security.GetSecretKeys(); VssConnection connection = null; connection = new VssConnection(new Uri(Security.DevOpsAccount), new VssBasicCredential(string.Empty, Security.PAT)); // Get a GitHttpClient to talk to the Git endpoints GitHttpClient gitClient = connection.GetClient <GitHttpClient>(); WorkItemTrackingHttpClient witClient = connection.GetClient <WorkItemTrackingHttpClient>(); //witClient.GetWorkItemsAsync() var wiqlQuery = new Wiql() { Query = "Select * from WorkItems" }; var workItemQueryResultForWiqlBasedQuery = witClient.QueryByWiqlAsync(wiqlQuery).Result; var workItemsForQueryResultForWiqlBasedQuery = witClient .GetWorkItemsAsync( workItemQueryResultForWiqlBasedQuery.WorkItems.Select(workItemReference => workItemReference.Id), expand: WorkItemExpand.All).Result; //JsonConvert.SerializeObject(workItemsForQueryResultForWiqlBasedQuery, Formatting.Indented); return(StatusCode(StatusCodes.Status200OK, workItemsForQueryResultForWiqlBasedQuery)); }
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); }
private static async Task <(string branchName, string buildNumber)> TryGetRoslynBranchAndBuildNumberForReleaseAsync( VisualStudioVersion release, GitHttpClient vsGitClient) { GitRepository vsRepository = await GetVSRepositoryAsync(vsGitClient); var commit = new GitVersionDescriptor { VersionType = GitVersionType.Commit, Version = release.CommitSha }; using var componentsJsonStream = await vsGitClient.GetItemContentAsync( vsRepository.Id, @".corext\Configs\dotnetcodeanalysis-components.json", download : true, versionDescriptor : commit); var componentsJsonContents = await new StreamReader(componentsJsonStream).ReadToEndAsync(); var componentsJson = JObject.Parse(componentsJsonContents); var languageServicesUrlAndManifestName = (string)componentsJson["Components"]["Microsoft.CodeAnalysis.LanguageServices"]["url"]; var parts = languageServicesUrlAndManifestName.Split(';'); if (parts.Length != 2) { return(default);
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 static async Task <Dictionary <GitPullRequest, bool> > CheckPullRequestFreshness( GitHttpClient gitClient, string project, IList <GitPullRequest> pullRequests, DateTime staleDate, string botId) { Dictionary <GitPullRequest, bool> pullCollection = new Dictionary <GitPullRequest, bool>(); foreach (GitPullRequest pr in pullRequests) { IList <GitPullRequestCommentThread> threads = await gitClient.GetThreadsAsync(project, pr.Repository.Id, pr.PullRequestId); GitPullRequestCommentThread lastUpdated = threads.OrderByDescending(p => p.LastUpdatedDate).FirstOrDefault(); // Stale PRs have never been updated, or haven't been updated since the staleDate if (lastUpdated == null || lastUpdated.LastUpdatedDate < staleDate) { // Knowing whether or not the last comment was from the bot will tell us if we need to check for tags or not bool commentByBot = lastUpdated != null && lastUpdated.Comments.Last().Author.Id == botId; pullCollection.Add(pr, commentByBot); } } return(pullCollection); }
/// <summary> /// Creates a repository Fork through the VSTS <see cref="GitHttpClient"/>. /// </summary> /// <param name="client">The <see cref="GitHttpClient"/> used to create the Fork.</param> /// <param name="vstsCollectionId">The target collection ID where we are creating the fork on.</param> /// <param name="vstsTargetProjectId">The target project ID where we are creating the fork on.</param> /// <param name="sourceRepo">The origin repo for the Fork.</param> /// <param name="targetRepo">name of the tenant fork</param> /// <returns>The async <see cref="Task{GitRepository}"/> wrapper with pre-existing or new repo</returns> internal static async Task <GitRepository> CreateForkIfNotExists(this GitHttpClient client, string vstsCollectionId, string vstsTargetProjectId, GitRepository sourceRepo, string targetRepo) { var repo = await client.LoadGitRepositoryIfExists(targetRepo); if (repo != null) { return(repo); } return(await client.CreateRepositoryAsync( new GitRepositoryCreateOptions { Name = targetRepo, ProjectReference = new TeamProjectReference { Id = Guid.Parse(vstsTargetProjectId) }, ParentRepository = new GitRepositoryRef { Id = sourceRepo.Id, ProjectReference = new TeamProjectReference { Id = sourceRepo.ProjectReference.Id }, Collection = new TeamProjectCollectionReference { Id = Guid.Parse(vstsCollectionId) } } })); }
private async Task <double?> GetCodeCoverageForBuild(String projectId, int buildId) { _logger.LogInformation($"[{nameof(GetCodeCoverageForBuild)}] BEGIN {{project:{projectId}, buildId:{buildId}}}"); try { const string CoverageStatsLabel = "Lines"; GitHttpClient gitClient = _connection.GetClient <GitHttpClient>(); TestManagementHttpClient testClient = _connection.GetClient <TestManagementHttpClient>(); //Получить покрытие кода по id билда var codeCoverage = await testClient.GetCodeCoverageSummaryAsync(projectId, buildId); _logger.LogInformation($"[{nameof(GetCodeCoverageForBuild)}] GetCodeCoverageSummaryAsync(project:{projectId}, buildId:{buildId}) success!"); CodeCoverageStatistics CoverageStats = null; if (codeCoverage.CoverageData.Count > 0) { // TODO: Переделать на случай если будет несколько CoverageData CoverageStats = codeCoverage?.CoverageData[0].CoverageStats .FirstOrDefault(x => x.Label.Equals(CoverageStatsLabel, StringComparison.OrdinalIgnoreCase)); } return(CoverageStats?.Covered * 100.00 / CoverageStats?.Total); } catch (Exception e) { _logger.LogError($"[{nameof(GetCodeCoverageForBuild)}] ERROR: {e.ToString()}"); return(null); } finally { _logger.LogInformation($"[{nameof(GetCodeCoverageForBuild)}] COMPLETED"); } }
/// <summary> /// Initializes a new instance of <see cref="RepositoryActor"/>. /// </summary> /// <param name="actorService">The ActorService context.</param> /// <param name="actorId">The Actor ID.</param> /// <param name="gitClient">The <see cref="GitHttpClient"/> to use on repo operations.</param> /// <param name="vstsConfiguration">The VSTS configuration payload.</param> /// <param name="bb">big brother instance</param> public RepositoryActor(ActorService actorService, ActorId actorId, GitHttpClient gitClient, VstsConfiguration vstsConfiguration, IBigBrother bb) : base(actorService, actorId) { _gitClient = gitClient; _vstsConfiguration = vstsConfiguration; _bigBrother = bb; }
public AzureDevOpsPullRequestServices(ClientContext clientContext, GitHttpClient client, string project, GitRepository repo) { this.clientContext = clientContext; this.client = client; this.project = project; this.repo = repo; }
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); }
static void Main(string[] args) { const String c_collectionUri = "https://dev.azure.com/microsoft"; const String c_projectName = "Edge"; const String c_repoName = "chromium.src"; // Interactively ask the user for credentials, caching them so the user isn't constantly prompted VssCredentials creds = new VssClientCredentials(); creds.Storage = new VssClientCredentialStorage(); // Connect to Azure DevOps Services 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).Result; // Create instance of WorkItemTrackingHttpClient using VssConnection WorkItemTrackingHttpClient witClient = connection.GetClient <WorkItemTrackingHttpClient>(); // Get 2 levels of query hierarchy items List <QueryHierarchyItem> queryHierarchyItems = witClient.GetQueriesAsync(c_projectName, depth: 2).Result; // Search for 'My Queries' folder QueryHierarchyItem myQueriesFolder = queryHierarchyItems.FirstOrDefault(qhi => qhi.Name.Equals("My Queries")); if (myQueriesFolder != null) { var foo = "Skippy"; } }