public async Task CanSortPullRequests() { await CreateTheWorld(); var newPullRequest = new NewPullRequest("a pull request", branchName, "master"); var pullRequest = await _fixture.Create(Helper.UserName, _context.RepositoryName, newPullRequest); var newPullRequest2 = new NewPullRequest("another pull request", otherBranchName, "master"); var anotherPullRequest = await _fixture.Create(Helper.UserName, _context.RepositoryName, newPullRequest2); var updatePullRequest = new PullRequestUpdate { Body = "This is the body" }; await _fixture.Update(Helper.UserName, _context.RepositoryName, pullRequest.Number, updatePullRequest); var sortPullRequestsByUpdated = new PullRequestRequest { SortProperty = PullRequestSort.Updated, SortDirection = SortDirection.Ascending }; var pullRequests = await _fixture.GetAllForRepository(Helper.UserName, _context.RepositoryName, sortPullRequestsByUpdated); Assert.Equal(anotherPullRequest.Title, pullRequests[0].Title); var sortPullRequestsByLongRunning = new PullRequestRequest { SortProperty = PullRequestSort.LongRunning }; var pullRequestsByLongRunning = await _fixture.GetAllForRepository(Helper.UserName, _context.RepositoryName, sortPullRequestsByLongRunning); Assert.Equal(pullRequest.Title, pullRequestsByLongRunning[0].Title); }
private async Task <List <GitRepoTopicPublishRecord> > GetPublishHistory(GitHubRepository repo) { var github = new GitHubClient(new ProductHeaderValue("OPSMetrics")); var token = new Credentials(repo.AuthToken); github.Credentials = token; var repository = await github.Repository.Get(repo.Owner, repo.RepositoryName); var pullRequestRequest = new PullRequestRequest() { State = ItemState.Closed, Base = "live" }; var pullRequests = await github.Repository.PullRequest.GetAllForRepository(repository.Owner.Login, repository.Name, pullRequestRequest); List <GitRepoTopicPublishRecord> history = new List <GitRepoTopicPublishRecord>(); foreach (var pullRequest in pullRequests) { var merged = await github.PullRequest.Merged(repository.Owner.Login, repository.Name, pullRequest.Number); if (merged) { List <GitRepoTopicPublishRecord> records = new List <GitRepoTopicPublishRecord>(); var files = await github.Repository.PullRequest.Files(repository.Owner.Login, repository.Name, pullRequest.Number); var fileNames = files.Where(file => file.FileName.EndsWith(".md")).Select(file => file.FileName).ToList(); var commitInfos = await github.PullRequest.Commits(repository.Owner.Login, repository.Name, pullRequest.Number); foreach (var commitInfo in commitInfos) { var commit = await github.Repository.Commits.Get(repository.Owner.Login, repository.Name, commitInfo.Sha); if (commit.Parents.Count < 2) // Ignore merge commits { var updatedFiles = commit.Files; var updatedTopics = updatedFiles.Where(v => fileNames.Contains(v.Filename)).ToList(); foreach (var updatedTopic in updatedTopics) { AddToRecords(records, repo.PartitionKey, pullRequest.Number, updatedTopic.Filename, pullRequest.MergedAt.Value.DateTime, commit.Author == null ? null : commit.Author.Id.ToString()); // Merged time of PR as publish time instead of commit time if (updatedTopic.PreviousFileName != null) // If the topic is renamed { AddToRecords(records, repo.PartitionKey, pullRequest.Number, updatedTopic.PreviousFileName, pullRequest.MergedAt.Value.DateTime, commit.Author == null ? null : commit.Author.Id.ToString()); } } } } history.AddRange(records); } } return(history); }
public async Task ReturnsCorrectCountOfPullRequestsWithStartParameterized() { await CreateTheWorld(); var newPullRequest1 = new NewPullRequest("a pull request 1", branchName, "master"); var newPullRequest2 = new NewPullRequest("a pull request 2", otherBranchName, "master"); await _fixture.Create(Helper.UserName, _context.RepositoryName, newPullRequest1); var result = await _fixture.Create(Helper.UserName, _context.RepositoryName, newPullRequest2); var options = new ApiOptions { PageSize = 1, PageCount = 1, StartPage = 2 }; var openPullRequests = new PullRequestRequest { State = ItemStateFilter.Open }; var pullRequests = await _fixture.GetAllForRepository(Helper.UserName, _context.RepositoryName, openPullRequests, options); Assert.Equal(1, pullRequests.Count); Assert.Equal(result.Title, pullRequests[0].Title); }
public async Task OpenPullRequest(ForkData target, PullRequestRequest request, IEnumerable <string> labels) { var repo = await _client.GetGitRepository(target.Owner, target.Name); var req = new PullRequest { title = request.Title, source = new Source { branch = new Branch { name = request.Head } }, destination = new Source { branch = new Branch { name = request.BaseRef } }, description = request.Body, close_source_branch = request.DeleteBranchAfterMerge }; await _client.CreatePullRequest(req, target.Owner, repo.name); }
public async Task <bool> HasOpenPullRequest(IGitHubClient client, Repository repository, Reference reference) { if (client is null) { throw new ArgumentNullException(nameof(client)); } if (repository is null) { throw new ArgumentNullException(nameof(repository)); } if (reference is null) { throw new ArgumentNullException(nameof(reference)); } _logger.LogTrace("Checking if there is existing open pull request in repository {repositoryName} for reference '{pullRequest}'.", repository.FullName, reference.Ref); var openRequests = new PullRequestRequest { State = ItemStateFilter.Open }; var pullRequests = await client.Repository.PullRequest.GetAllForRepository(repository.Owner.Login, repository.Name, openRequests).ConfigureAwait(false); return(pullRequests.Any(pr => $"refs/heads/{pr.Head.Ref}" == reference.Ref)); }
public static async Task <PullRequest> FindGithubPullRequestAsync(DiscoveryContext context, string repoOwner, string repoName, string creator, string title) { // Optimization: if the creator is the current user, we can rely on the cached list of pull requests if (creator.EqualsIgnoreCase(context.GithubClient.Connection.Credentials.Login)) { return(context.PullRequestsCreatedByCurrentUser .Where(p => { var success = Misc.DeriveGitHubRepositoryInfo(new Uri(p.Url), out string owner, out string name); return owner.EqualsIgnoreCase(repoOwner) && name.EqualsIgnoreCase(repoName); }) .FirstOrDefault(i => i.Title.EqualsIgnoreCase(title))); } else { var request = new PullRequestRequest() { State = ItemStateFilter.Open, SortProperty = PullRequestSort.Created, SortDirection = SortDirection.Descending }; var pullRequests = await context.GithubClient.PullRequest.GetAllForRepository(repoOwner, repoName, request).ConfigureAwait(false); var pullRequest = pullRequests.FirstOrDefault(pr => pr.Title.EqualsIgnoreCase(title) && pr.User.Login.EqualsIgnoreCase(creator)); return(pullRequest); } }
protected virtual async Task <IReadOnlyList <PullRequest> > LoadPullRequestsAsync(Func <PullRequest, bool> predicate) { Repository repository = null; IReadOnlyList <PullRequest> pullRequests = null; PullRequestRequest pullRequestRequest = new PullRequestRequest { State = ItemStateFilter.All, }; try { repository = await gitHubClient.Repository.Get(Options.Owner, Options.Repository); pullRequests = await gitHubClient.PullRequest.GetAllForRepository(repository.Id, pullRequestRequest); } catch (ApiException exception) when(repository == null) { ExitWithException($"Failed to load repository data for {Options.Owner}, {Options.Repository}.", exception, ExitCode.FailedToLoadData); return(new List <PullRequest>()); } catch (ApiException exception) when(pullRequests == null) { ExitWithException($"Failed to load pullrequest for repository {repository?.Owner}/{repository?.Name}.", exception, ExitCode.FailedToLoadData); return(new List <PullRequest>()); } return(pullRequests.Where(predicate) .ToList()); }
/// <summary> /// Calculates pull request health /// </summary> /// <param name="metrics"></param> /// <returns></returns> public async Task GetPullRequestHealth(HealthMetrics metrics) { Logger.Debug($"GetPullRequestHealth('{purl.Namespace}', '{purl.Name}')"); double pullRequestHealth = 0; int pullRequestOpen = 0; int pullRequestClosed = 0; var pullRequestRequest = new PullRequestRequest() { State = ItemStateFilter.All }; var pullRequests = await Client.PullRequest.GetAllForRepository(purl.Namespace, purl.Name, pullRequestRequest, DEFAULT_API_OPTIONS); // Gather raw data foreach (var pullRequest in pullRequests) { if (pullRequest.State == ItemState.Open) { pullRequestOpen++; } else if (pullRequest.State == ItemState.Closed) { pullRequestClosed++; } } if (pullRequestOpen + pullRequestClosed > 0) { pullRequestHealth = 100.0 * pullRequestClosed / (pullRequestOpen + pullRequestClosed); } metrics.PullRequestHealth = pullRequestHealth; }
public async Task <Data.PullRequest[]> FetchAllPullRequests(string owner, string repo) { Ensure.ArgumentNotNullOrEmptyString(owner, nameof(owner)); Ensure.ArgumentNotNullOrEmptyString(repo, nameof(repo)); _logger.LogInformation("{datetime}: fetching pull reuqests from {owner}/{repo}.", DateTime.Now, owner, repo); var requestFilter = new PullRequestRequest() { State = ItemStateFilter.Closed, SortDirection = SortDirection.Ascending, SortProperty = PullRequestSort.Created }; var gitHubPullRequests = (await _client.PullRequest.GetAllForRepository(owner, repo, requestFilter, new ApiOptions() { PageSize = 1000 }).ConfigureAwait(false)) .ToArray(); var pullRequests = Mapper.Map <Data.PullRequest[]>(gitHubPullRequests); _logger.LogInformation("{datetime}: {count} pull requests have been fetched.", DateTime.Now, pullRequests.Length); return(pullRequests); }
/// <summary> /// Get top 10 pull request sorted in descending order /// </summary> /// <param name="supportedRepo"></param> /// <param name="topCount"></param> /// <returns></returns> public List <PullRequest> GetTopPullRequests(SupportedGitHubRepos supportedRepo, int topCount = 10) { if (topCount > 10) { Logger.LogException <ApplicationException>("Get more than 10 Pull Requsts is not supported"); } List <PullRequest> prInfoList = new List <PullRequest>(); Repository r = GetRepository(supportedRepo); ApiOptions apiOpt = new ApiOptions(); apiOpt.PageCount = 1; apiOpt.PageSize = topCount; PullRequestRequest prr = new PullRequestRequest(); prr.State = ItemStateFilter.Open; prr.SortDirection = SortDirection.Descending; IReadOnlyList <PullRequest> prList = OC.PullRequest.GetAllForRepository(r.Id, prr, apiOpt).GetAwaiter().GetResult(); if (prList.NotNullOrAny <PullRequest>()) { prInfoList = prList.ToList <PullRequest>(); } return(prInfoList); }
public async Task <string> CreatePullRequest( string userAgent, string authorizationToken, string repositoryName, string headBranchName, string baseBranchName) { HttpClient httpClient = new HttpClient { BaseAddress = new Uri(ApiBaseUri) }; this.SetRequestHeaders(httpClient.DefaultRequestHeaders, userAgent, authorizationToken, null); var requestUri = string.Format(@"repos/{0}/{1}/pulls", userAgent, repositoryName); var pullRequest = new PullRequestRequest { Title = headBranchName, Body = "comment to merge", Head = headBranchName, Base = baseBranchName, }; HttpResponseMessage response = await httpClient.PostAsJsonAsync(requestUri, pullRequest).ConfigureAwait(false); response.EnsureSuccessStatusCode(); return(response.Headers.Location.AbsoluteUri); }
public async Task OpenPullRequest(ForkData target, PullRequestRequest request, IEnumerable <string> labels) { if (target == null) { throw new ArgumentNullException(nameof(target)); } if (request == null) { throw new ArgumentNullException(nameof(request)); } var projectName = target.Owner; var repositoryName = target.Name; var mergeRequest = new Model.CreatePullRequestOption { Title = request.Title, Head = request.Head, Body = request.Body, Base = request.BaseRef, Labels = new long[] { 0 }, // Gitea needs a due date for its pull requests. Maybe get this from the config file? DueDate = DateTime.Now.AddDays(7) }; await _client.OpenPullRequest(projectName, repositoryName, mergeRequest); }
public async Task OpenPullRequest(ForkData target, PullRequestRequest request, IEnumerable <string> labels) { var repos = await _client.GetGitRepositories(target.Owner); var repo = repos.Single(x => x.name == target.Name); var req = new PRRequest { title = request.Title, sourceRefName = $"refs/heads/{request.Head}", description = request.Body, targetRefName = $"refs/heads/{request.BaseRef}", completionOptions = new GitPullRequestCompletionOptions { deleteSourceBranch = request.DeleteBranchAfterMerge } }; var pullRequest = await _client.CreatePullRequest(req, target.Owner, repo.id); foreach (var label in labels) { await _client.CreatePullRequestLabel(new LabelRequest { name = label }, target.Owner, repo.id, pullRequest.PullRequestId); } }
private async Task DeleteMergedBranches(DiscoveryContext context, IEnumerable <Branch> branches, TextWriter log) { // Delete branches when their corresponding PR has been merged foreach (var branch in branches) { var pullRequestsRequest = new PullRequestRequest() { State = ItemStateFilter.Closed, SortProperty = PullRequestSort.Updated, SortDirection = SortDirection.Descending, Head = $"{context.Options.GithubUsername}:{branch.Name}" }; var pullRequests = await context.GithubClient.Repository.PullRequest .GetAllForRepository(Constants.CAKE_REPO_OWNER, Constants.CAKE_WEBSITE_REPO_NAME, pullRequestsRequest) .ConfigureAwait(false); var pr = pullRequests.SingleOrDefault(pr => pr.Head.Sha == branch.Commit.Sha); if (pr != null && pr.Merged) { await log.WriteLineAsync($"Deleting branch {context.Options.GithubUsername}/{Constants.CAKE_WEBSITE_REPO_NAME}/{branch.Name}").ConfigureAwait(false); await context.GithubClient.Git.Reference .Delete(context.Options.GithubUsername, Constants.CAKE_WEBSITE_REPO_NAME, $"heads/{branch.Name}") .ConfigureAwait(false); } } }
public async Task <PullRequest> GetClosedNonMergedPullRequestOrNull(IGitHubClient client, Repository repository, string pullRequestTitle) { if (client is null) { throw new ArgumentNullException(nameof(client)); } if (repository is null) { throw new ArgumentNullException(nameof(repository)); } if (string.IsNullOrWhiteSpace(pullRequestTitle)) { throw new ArgumentException("Pull request title must be defined", nameof(pullRequestTitle)); } _logger.LogTrace("Checking if there is existing closed pull request in repository {repositoryName} for pull request '{pullRequest}'.", repository.FullName, pullRequestTitle); var closedRequests = new PullRequestRequest { State = ItemStateFilter.Closed }; var pullRequests = await client.Repository.PullRequest.GetAllForRepository(repository.Owner.Login, repository.Name, closedRequests).ConfigureAwait(false); return(pullRequests.FirstOrDefault(pr => !pr.Merged && pr.Title == pullRequestTitle)); }
public async Task OpenPullRequest(ForkData target, PullRequestRequest request, IEnumerable <string> labels) { var repos = await _client.GetGitRepositories(target.Owner); var repo = repos.Single(x => x.name == target.Name); var req = new PullRequest { title = request.Title, source = new Source { branch = new Branch { name = request.Head } }, destination = new Source { branch = new Branch { name = request.BaseRef } }, description = request.Body }; await _client.CreatePullRequest(req, target.Owner, repo.name); }
private async Task <SweeptargetBranchResult[]> GetMergedNotDeletedBranchesAsync(string repository) { var branchOptions = new ApiOptions() { PageSize = 100 }; var branchClient = client.GitHubClient.Repository.Branch; var allBranches = await branchClient.GetAll(Owner, repository, branchOptions); var branches = allBranches; if (ExcludeBranches != null && ExcludeBranches.Any()) { branches = allBranches.Where(x => ExcludeBranches.Any(y => Regex.IsMatch(x.Name, y, RegexOptions.IgnoreCase))).ToArray(); } // HEAVY TASK!!! // PR history length relates to task heaviness. (2000 histories = 30sec or more) var prRequest = new PullRequestRequest() { State = ItemStateFilter.Closed, SortProperty = PullRequestSort.Updated }; var prOptions = new ApiOptions() { PageSize = PrPageSize, PageCount = PrPageCount }; var prClient = client.GitHubClient.PullRequest; var prs = await prClient.GetAllForRepository(Owner, repository, prRequest, prOptions); // no pull requests if (prs == null || !prs.Any()) { return new SweeptargetBranchResult[] { } } ; var mergedNotDeletedBranches = prs.Where(x => x.Merged).Select(x => new SweeptargetBranchResult { CreatedBy = x.User.Login, RepositoryName = x.Head?.Repository?.Name, RepositoryId = x.Head?.Repository?.Id, PullrequestId = x.Id, BranchSha = x.Head?.Sha, BranchName = x.Head?.Ref, BranchDeleteRef = $"heads/{x.Head?.Ref}", Title = x.Title, Merged = x.Merged, Locked = x.Locked, MergedBy = x.MergedBy?.Login, CreatedAt = x.CreatedAt, MergedAt = x.MergedAt, UpdatedAt = x.UpdatedAt, ClosedAt = x.ClosedAt, }) .Where(x => branches.Any(y => y.Name == x.BranchName)) .Where(x => DateTime.Now.AddDays(-1 * DaysPast) > x.MergedAt) .ToArray(); return(mergedNotDeletedBranches); }
/// <summary> /// Implements actions before the request for Github's GraphQL API to determine if the request is ready to be made. /// </summary> /// <returns><c>true</c>, if request was befored, <c>false</c> otherwise.</returns> /// <param name="repoRequest">Repo request.</param> /// <param name="httpRequest">Http request.</param> public bool BeforeRequest(RepoRequest repoRequest, HttpRequestMessage httpRequest) { // For GraphQL, we're always a post and the same endpoint. httpRequest.RequestUri = s_ghGQLEndpoint; httpRequest.Method = HttpMethod.Post; if (repoRequest is PullRequestRequest) { PullRequestRequest prRequest = (PullRequestRequest)repoRequest; // Add in the request query string post - check for the first time to use the prRequest string specificRepo = _currentKey; if (string.IsNullOrEmpty(_currentKey)) { _currentKey = prRequest.RepoName; } httpRequest.Content = new StringContent(GetJSONQueryString(prRequest.Organization, _nextCursor, _currentKey, prRequest.State), Encoding.UTF8, "application/json"); return(true); } else { return(false); } }
public async Task OpenPullRequest(ForkData target, PullRequestRequest request, IEnumerable <string> labels) { if (request == null) { throw new ArgumentNullException(nameof(request)); } if (target == null) { throw new ArgumentNullException(nameof(target)); } var repositories = await _client.GetGitRepositories(target.Owner); var targetRepository = repositories.FirstOrDefault(x => x.Name.Equals(target.Name, StringComparison.InvariantCultureIgnoreCase)); var reviewers = await _client.GetBitBucketReviewers(target.Owner, targetRepository.Name); var pullReq = new PullRequest { Title = request.Title, Description = request.Body, FromRef = new Ref { Id = request.Head }, ToRef = new Ref { Id = request.BaseRef }, Reviewers = reviewers.ToList() }; await _client.CreatePullRequest(pullReq, target.Owner, targetRepository.Name); }
public async Task OpenPullRequest(ForkData target, PullRequestRequest request, IEnumerable <string> labels) { if (target == null) { throw new ArgumentNullException(nameof(target)); } if (request == null) { throw new ArgumentNullException(nameof(request)); } var projectName = target.Owner; var repositoryName = target.Name; var mergeRequest = new MergeRequest { Title = request.Title, SourceBranch = request.Head, Description = request.Body, TargetBranch = request.BaseRef, Id = $"{projectName}/{repositoryName}", RemoveSourceBranch = request.DeleteBranchAfterMerge, Labels = labels.ToList() }; await _client.OpenMergeRequest(projectName, repositoryName, mergeRequest); }
public async Task ReturnsDistinctPullRequestsBasedOnStartPageParameterized() { await CreateTheWorld(); var newPullRequest1 = new NewPullRequest("a pull request 1", branchName, "master"); var newPullRequest2 = new NewPullRequest("a pull request 2", otherBranchName, "master"); await _fixture.Create(Helper.UserName, _context.RepositoryName, newPullRequest1); await _fixture.Create(Helper.UserName, _context.RepositoryName, newPullRequest2); var openPullRequests = new PullRequestRequest { State = ItemStateFilter.Open }; var startOptions = new ApiOptions { PageSize = 1, PageCount = 1 }; var firstPage = await _fixture.GetAllForRepository(_context.RepositoryOwner, _context.RepositoryName, openPullRequests, startOptions); var skipStartOptions = new ApiOptions { PageSize = 1, PageCount = 1, StartPage = 2 }; var secondPage = await _fixture.GetAllForRepository(_context.RepositoryOwner, _context.RepositoryName, openPullRequests, skipStartOptions); Assert.NotEqual(firstPage[0].Title, secondPage[0].Title); }
public RepoBrowserFactory_UnitTests() { _gitHubOrg = new Organization(1); _gitHubOrg.Repository = new Organization.OrgRepository() { Type = RepositoryType.Github, Name = "unittestGH" }; _bitBucketOrg = new Organization(2); _bitBucketOrg.Repository = new Organization.OrgRepository() { Type = RepositoryType.Bitbucket, Name = "unittestGH" }; _request = new PullRequestRequest(); _request.State = PullRequestRequest.PullRequestState.All; List <string> scopes = new List <string>() { "mock_scope" }; _repoConfigList.Add(new RepoBrowserConfiguration() { TypeName = RepositoryType.Github, AuthType = "RepoBrowser.UnitTests.MockAuthenticationService, RepoBrowser.UnitTests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", TransformType = "RepoBrowser.UnitTests.MockTransformationService, RepoBrowser.UnitTests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", HttpMessageHandlerType = "RepoBrowser.UnitTests.MockHttpMessageHandler, RepoBrowser.UnitTests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", AuthSettings = new AuthenticationSettings() { EnvClientID = "MOCK_CLIENTID", EnvUserName = "******", EnvUserPassword = "******", EnvClientSecret = "MOCK_CLIENTSECRET", Note = "MockNote", OAuth2Endpoint = "http://mock/", Scopes = scopes } }); _repoConfigList.Add(new RepoBrowserConfiguration() { TypeName = RepositoryType.Bitbucket, AuthType = "RepoBrowser.UnitTests.MockAuthenticationService, RepoBrowser.UnitTests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", TransformType = "RepoBrowser.UnitTests.MockTransformationService, RepoBrowser.UnitTests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", HttpMessageHandlerType = "RepoBrowser.UnitTests.MockHttpMessageHandler, RepoBrowser.UnitTests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", AuthSettings = new AuthenticationSettings() { EnvClientID = "MOCK_CLIENTID", EnvUserName = "******", EnvUserPassword = "******", EnvClientSecret = "MOCK_CLIENTSECRET", Note = "MockNote", OAuth2Endpoint = "http://mock/", Scopes = scopes } }); }
public void ReplacesRemotesWhenCreatingPullRequestRequestObject() { var pr = new PullRequestRequest("head", "title", "origin/master", true, true, GitPullRequestMergeStrategy.NoFastForward); var pr2 = new PullRequestRequest("head", "title", "master", true, true, GitPullRequestMergeStrategy.NoFastForward); Assert.That(pr.BaseRef, Is.EqualTo("master")); Assert.That(pr2.BaseRef, Is.EqualTo("master")); }
public void ReturnsDefaultValuesForDefaultRequest() { var request = new PullRequestRequest(); var parameters = request.ToParametersDictionary(); Assert.Equal("open", parameters["state"]); }
public void ReplacesRemotesWhenCreatingPullRequestRequestObject() { var pr = new PullRequestRequest("head", "title", "origin/master"); var pr2 = new PullRequestRequest("head", "title", "master"); Assert.That(pr.BaseRef, Is.EqualTo("master")); Assert.That(pr2.BaseRef, Is.EqualTo("master")); }
/// <summary> /// Query pull requests for the repository based on criteria /// </summary> /// <remarks> /// http://developer.github.com/v3/pulls/#list-pull-requests /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="request">Used to filter and sort the list of pull requests returned</param> /// <param name="options">Options for changing the API response</param> public IObservable <PullRequest> GetAllForRepository(long repositoryId, PullRequestRequest request, ApiOptions options) { Ensure.ArgumentNotNull(request, nameof(request)); Ensure.ArgumentNotNull(options, nameof(options)); return(_connection.GetAndFlattenAllPages <PullRequest>(ApiUrls.PullRequests(repositoryId), request.ToParametersDictionary(), options)); }
/// <summary> /// Query pull requests for the repository based on criteria /// </summary> /// <remarks> /// http://developer.github.com/v3/pulls/#list-pull-requests /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="request">Used to filter and sort the list of pull requests returned</param> /// <returns>A collection of <see cref="PullRequest"/> results</returns> public IObservable<PullRequest> GetAllForRepository(string owner, string name, PullRequestRequest request) { Ensure.ArgumentNotNullOrEmptyString(owner, "owner"); Ensure.ArgumentNotNullOrEmptyString(name, "name"); Ensure.ArgumentNotNull(request, "request"); return _connection.GetAndFlattenAllPages<PullRequest>(ApiUrls.PullRequests(owner, name), request.ToParametersDictionary()); }
/// <summary> /// Query pull requests for the repository based on criteria /// </summary> /// <remarks> /// http://developer.github.com/v3/pulls/#list-pull-requests /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="request">Used to filter and sort the list of pull requests returned</param> /// <returns>A collection of <see cref="PullRequest"/> results</returns> public IObservable <PullRequest> GetForRepository(string owner, string name, PullRequestRequest request) { Ensure.ArgumentNotNullOrEmptyString(owner, "owner"); Ensure.ArgumentNotNullOrEmptyString(name, "name"); Ensure.ArgumentNotNull(request, "request"); return(_connection.GetAndFlattenAllPages <PullRequest>(ApiUrls.PullRequests(owner, name), request.ToParametersDictionary())); }
static void Main(string[] args) { PopulateLeadsArea().Wait(); GitHubClient client = new GitHubClient(new ProductHeaderValue("Octokit.Samples")); client.Credentials = CreateCredentials(); var request = new PullRequestRequest() { State = ItemStateFilter.Open, Base = "main" }; var prs = client.PullRequest.GetAllForRepository(org, repo, request).Result; var rl = client.GetLastApiInfo().RateLimit; Console.WriteLine($"Remaining api limit {rl.Remaining} will reset at {rl.Reset.ToLocalTime ()}"); DateTime cutDate = DateTime.Today.AddDays(-21); int drafts = 0; int active = 0; var inactive = new List <(PullRequest, DateTime)> (); foreach (PullRequest pr in prs) { if (pr.Draft) { ++drafts; continue; } if (IsActivePR(client, pr, cutDate, out DateTime lastActivity)) { ++active; continue; } inactive.Add((pr, lastActivity)); } StringWriter sw = new StringWriter(); ReportInactivePRs(inactive, sw, client); var res = typeof(Program).Assembly.GetManifestResourceStream("prmonitor.output.html.template"); using (var input = new StreamReader(res !, Encoding.UTF8)) { var text = input.ReadToEnd().Replace("##BODY##", sw.ToString()).Replace("##DATE##", DateTime.Today.ToString("dd MMMM yyyy")); File.WriteAllText("../../../output.html", text); } return; }
public void SendsAppropriateParameters() { var gitHubClient = Substitute.For<IGitHubClient>(); var client = new ObservablePullRequestsClient(gitHubClient); var pullRequestRequest = new PullRequestRequest { SortDirection = SortDirection.Descending }; client.GetAllForRepository("fake", "repo", pullRequestRequest); gitHubClient.Received().PullRequest.GetAllForRepository("fake", "repo", pullRequestRequest, Args.ApiOptions); }
public async Task OpenPullRequest(ForkData target, PullRequestRequest request, IEnumerable <string> labels) { if (target == null) { throw new ArgumentNullException(nameof(target)); } if (labels == null) { throw new ArgumentNullException(nameof(labels)); } if (request == null) { throw new ArgumentNullException(nameof(request)); } var repos = await _client.GetGitRepositories(target.Owner); var repo = repos.Single(x => x.name.Equals(target.Name, StringComparison.OrdinalIgnoreCase)); var req = new PRRequest { title = request.Title, sourceRefName = $"refs/heads/{request.Head}", description = request.Body, targetRefName = $"refs/heads/{request.BaseRef}", }; var pullRequest = await _client.CreatePullRequest(req, target.Owner, repo.id); if (request.SetAutoMerge) { await _client.PatchPullRequest(new PRRequest() { autoCompleteSetBy = new Creator() { id = pullRequest.CreatedBy.id }, completionOptions = new GitPullRequestCompletionOptions { deleteSourceBranch = request.DeleteBranchAfterMerge, mergeStrategy = request.MergeStrategy.ToString(), }, }, target.Owner, repo.id, pullRequest.PullRequestId); } foreach (var label in labels) { await _client.CreatePullRequestLabel(new LabelRequest { name = label }, target.Owner, repo.id, pullRequest.PullRequestId); } }
public static ResponseOrganization[] ToResponseOrganizations(this PullRequestRequest pullRequestRequest) { return(pullRequestRequest .Organizations .Select( organization => new ResponseOrganization( organization.Name, organization.Success, organization.ToResponseRepositories() ) ).ToArray()); }
public void SendsAppropriateParametersWithApiOptionsWithRepositoryId() { var gitHubClient = Substitute.For<IGitHubClient>(); var client = new ObservablePullRequestsClient(gitHubClient); var options = new ApiOptions { PageCount = 1, PageSize = 1, StartPage = 1 }; var pullRequestRequest = new PullRequestRequest { SortDirection = SortDirection.Descending }; client.GetAllForRepository(1, pullRequestRequest, options); gitHubClient.Received().PullRequest.GetAllForRepository(1, pullRequestRequest, options); }
/// <summary> /// Query pull requests for the repository based on criteria /// </summary> /// <remarks> /// http://developer.github.com/v3/pulls/#list-pull-requests /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="request">Used to filter and sort the list of pull requests returned</param> public IObservable<PullRequest> GetAllForRepository(long repositoryId, PullRequestRequest request) { Ensure.ArgumentNotNull(request, "request"); return GetAllForRepository(repositoryId, request, ApiOptions.None); }
/// <summary> /// Query pull requests for the repository based on criteria /// </summary> /// <remarks> /// http://developer.github.com/v3/pulls/#list-pull-requests /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="request">Used to filter and sort the list of pull requests returned</param> /// <param name="options">Options for changing the API response</param> public IObservable<PullRequest> GetAllForRepository(long repositoryId, PullRequestRequest request, ApiOptions options) { Ensure.ArgumentNotNull(request, "request"); Ensure.ArgumentNotNull(options, "options"); return _connection.GetAndFlattenAllPages<PullRequest>(ApiUrls.PullRequests(repositoryId), request.ToParametersDictionary(), options); }
/// <summary> /// Query pull requests for the repository based on criteria /// </summary> /// <remarks> /// http://developer.github.com/v3/pulls/#list-pull-requests /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="request">Used to filter and sort the list of pull requests returned</param> /// <returns>A collection of <see cref="PullRequest"/> results</returns> public IObservable<PullRequest> GetAllForRepository(string owner, string name, PullRequestRequest request) { Ensure.ArgumentNotNullOrEmptyString(owner, "owner"); Ensure.ArgumentNotNullOrEmptyString(name, "name"); Ensure.ArgumentNotNull(request, "request"); return GetAllForRepository(owner, name, request, ApiOptions.None); }