Exemplo n.º 1
0
        private async Task ApplyLabel(IGitHubClient gitHub, string owner, string repo, int issueNumber, string prediction)
        {
            var issue = await gitHub.Issue.Get(owner, repo, issueNumber);

            var issueUpdate = new IssueUpdate
            {
                Milestone = issue.Milestone?.Number // Have to re-set milestone because otherwise it gets cleared out. See https://github.com/octokit/octokit.net/issues/1927
            };

            issueUpdate.AddLabel(prediction);
            // Add all existing labels to the update so that they don't get removed
            foreach (var label in issue.Labels)
            {
                issueUpdate.AddLabel(label.Name);
            }

            await gitHub.Issue.Update(owner, repo, issueNumber, issueUpdate);

            // Because GitHub search queries can show stale data, add a cache entry to
            // indicate this issue should be hidden for a while because it was just labeled.
            _memoryCache.Set(
                MikLabelService.GetIssueHiderCacheKey(owner, repo, issueNumber),
                0, // no data is needed; the existence of the cache key is what counts
                new MemoryCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(30),
            });
        }
Exemplo n.º 2
0
        protected override async Task ProcessRecordAsync()
        {
            var repository = await GitHubClient.Repository.GetForOrg(Organization, Repository);

            var issue = await GitHubClient.Issue.Get(repository.Id, IssueNumber);

            var issueUpdate = new IssueUpdate()
            {
                Milestone = issue.Milestone?.Number
            };

            if (MileStoneTitle != null)
            {
                var milestone = await GitHubClient.Issue.Milestone.GetAllForRepository(repository.Id).ToObservable().SelectMany(list => list).FirstAsync(_ => _.Title == MileStoneTitle);

                issueUpdate.Milestone = milestone.Number;
            }

            if (State.HasValue)
            {
                issueUpdate.State = State;
            }

            if (Labels != null || RemoveLabels != null)
            {
                foreach (var label in issue.Labels.Select(label => label.Name.ToLower()).Except(RemoveLabels.Select(s => s.ToLower())))
                {
                    issueUpdate.AddLabel(label);
                }
                if (Labels != null)
                {
                    foreach (var label in Labels)
                    {
                        issueUpdate.AddLabel(label);
                    }
                }

                if (RemoveLabels != null)
                {
                    foreach (var label in RemoveLabels)
                    {
                        issueUpdate.RemoveLabel(label);
                    }
                }
            }

            await GitHubClient.Issue.Update(repository.Id, IssueNumber, issueUpdate)
            .ToObservable()
            .WriteObject(this)
            .HandleErrors(this);
        }
Exemplo n.º 3
0
        public async Task PredictAndApplyLabelAsync(int number, string title, string body, ILogger logger)
        {
            var corefxIssue = new GitHubIssue
            {
                ID          = number.ToString(),
                Title       = title,
                Description = body
            };

            string label = await Predictor.PredictAsync(corefxIssue, logger);

            if (label != null)
            {
                var issueUpdate = new IssueUpdate();
                issueUpdate.AddLabel(label);

                await _client.Issue.Update(_repoOwner, _repoName, number, issueUpdate);

                logger.LogInformation($"Issue {corefxIssue.ID} : \"{corefxIssue.Title}\" was labeled as: {label}");
            }
            else
            {
                logger.LogInformation($"The Model is not able to assign the label to the Issue {corefxIssue.ID} confidently.");
            }
        }
    public async Task ReturnsCorrectCountOfIssueLabelsWithStartForARepositoryWithRepositoryId()
    {
        for (int i = 0; i < 2; i++)
        {
            int k        = i + 1;
            var newIssue = new NewIssue("A test issue " + k)
            {
                Body = "A new unassigned issue " + k
            };
            var newLabel = new NewLabel("test label " + k, "FFFFF" + k);

            var label = await _issuesLabelsClient.Create(_context.Repository.Id, newLabel);

            var issue = await _issuesClient.Create(_context.RepositoryOwner, _context.RepositoryName, newIssue);

            var issueUpdate = new IssueUpdate();
            issueUpdate.AddLabel(label.Name);
            var updated = await _issuesClient.Update(_context.RepositoryOwner, _context.RepositoryName, issue.Number, issueUpdate);

            Assert.NotNull(updated);
        }

        var options = new ApiOptions
        {
            PageCount = 1,
            PageSize  = 1,
            StartPage = 2
        };

        var issueLabelsInfo = await _issuesLabelsClient.GetAllForRepository(_context.Repository.Id, options);

        Assert.Equal(1, issueLabelsInfo.Count);
    }
    public async Task CanListLabelsForAnIssue()
    {
        var newIssue = new NewIssue("A test issue")
        {
            Body = "A new unassigned issue"
        };
        var newLabel = new NewLabel("test label", "FFFFFF");

        var label = await _issuesLabelsClient.Create(_repositoryOwner, _repository.Name, newLabel);

        var issue = await _issuesClient.Create(_repositoryOwner, _repositoryName, newIssue);

        var issueLabelsInfo = await _issuesLabelsClient.GetAllForIssue(_repositoryOwner, _repositoryName, issue.Number);

        Assert.Empty(issueLabelsInfo);

        var issueUpdate = new IssueUpdate();

        issueUpdate.AddLabel(label.Name);
        var updated = await _issuesClient.Update(_repositoryOwner, _repository.Name, issue.Number, issueUpdate);

        Assert.NotNull(updated);
        issueLabelsInfo = await _issuesLabelsClient.GetAllForIssue(_repositoryOwner, _repositoryName, issue.Number);

        Assert.Equal(1, issueLabelsInfo.Count);
        Assert.Equal(newLabel.Color, issueLabelsInfo[0].Color);
    }
    public async Task CanListLabelsForAnMilestoneWithRepositoryId()
    {
        var newIssue = new NewIssue("A test issue")
        {
            Body = "A new unassigned issue"
        };
        var newLabel     = new NewLabel("test label", "FFFFFF");
        var newMilestone = new NewMilestone("New Milestone");

        var label = await _issuesLabelsClient.Create(_context.Repository.Id, newLabel);

        var issue = await _issuesClient.Create(_context.RepositoryOwner, _context.RepositoryName, newIssue);

        var milestone = await _issuesClient.Milestone.Create(_context.RepositoryOwner, _context.RepositoryName, newMilestone);

        var issueLabelsInfo = await _issuesLabelsClient.GetAllForMilestone(_context.Repository.Id, milestone.Number);

        Assert.Empty(issueLabelsInfo);

        var issueUpdate = new IssueUpdate {
            Milestone = milestone.Number
        };

        issueUpdate.AddLabel(label.Name);

        var updated = await _issuesClient.Update(_context.RepositoryOwner, _context.RepositoryName, issue.Number, issueUpdate);

        Assert.NotNull(updated);

        issueLabelsInfo = await _issuesLabelsClient.GetAllForMilestone(_context.Repository.Id, milestone.Number);

        Assert.Equal(1, issueLabelsInfo.Count);
        Assert.Equal(label.Color, issueLabelsInfo[0].Color);
    }
Exemplo n.º 7
0
        private void CreatePullRequest(Repository repo, GitHubClient gitHubClient, Remote origin, string branch)
        {
            // Oktokit is async-heavy, but we don't want to make ICommand asynchronous just for that.
            CreatePullRequestAsync().GetAwaiter().GetResult();

            async Task CreatePullRequestAsync()
            {
                string user = origin.Url.Substring("https://github.com/".Length).Split('/').First();
                string head = $"{user}:{branch}";

                var commitMessage      = repo.Commits.First().Message;
                var commitMessageLines = commitMessage.Replace("\r", "").Split('\n').ToList();
                var pullRequestLines   = UnwrapLines(commitMessageLines);

                var request = new NewPullRequest(pullRequestLines.First(), head, "master")
                {
                    Body = string.Join('\n', pullRequestLines.Skip(1))
                };
                var pullRequest = await gitHubClient.PullRequest.Create(RepositoryOwner, RepositoryName, request);

                Console.WriteLine($"Created pull request {pullRequest.Number}");

                // Note: using a collection initializer looks reasonable, but fails with an NRE, because the Labels
                // property is lazily initialized :(
                var issueUpdate = new IssueUpdate();

                issueUpdate.AddLabel(AutoreleasePendingLabel);
                await gitHubClient.Issue.Update(RepositoryOwner, RepositoryName, pullRequest.Number, issueUpdate);

                Console.WriteLine($"Applied '{AutoreleasePendingLabel}' label to pull request.");
                Console.WriteLine($"Done! When the following pull request is reviewed and merged, it will be automatically released:");
                // We put the pull request URL on a line on its own to make it easier to copy/paste.
                Console.WriteLine(pullRequest.HtmlUrl);
            }
        }
    public async Task ReturnsCorrectCountOfIssueLabelsWithoutStartForAnIssue()
    {
        var newIssue = new NewIssue("A test issue")
        {
            Body = "A new unassigned issue"
        };
        var newLabel = new NewLabel("test label", "FFFFFF");

        var label = await _issuesLabelsClient.Create(_context.RepositoryOwner, _context.RepositoryName, newLabel);

        var issue = await _issuesClient.Create(_context.RepositoryOwner, _context.RepositoryName, newIssue);

        var issueLabelsInfo = await _issuesLabelsClient.GetAllForIssue(_context.RepositoryOwner, _context.RepositoryName, issue.Number);

        Assert.Empty(issueLabelsInfo);

        var issueUpdate = new IssueUpdate();

        issueUpdate.AddLabel(label.Name);
        var updated = await _issuesClient.Update(_context.RepositoryOwner, _context.RepositoryName, issue.Number, issueUpdate);

        Assert.NotNull(updated);

        var options = new ApiOptions
        {
            PageCount = 1,
            PageSize  = 1
        };

        issueLabelsInfo = await _issuesLabelsClient.GetAllForIssue(_context.RepositoryOwner, _context.RepositoryName, issue.Number, options);

        Assert.Equal(1, issueLabelsInfo.Count);
        Assert.Equal(newLabel.Color, issueLabelsInfo[0].Color);
    }
Exemplo n.º 9
0
        public async Task PredictAndApplyLabelAsync(int number, string title, string body, int?milestone, ILogger logger)
        {
            if (_client == null)
            {
                await GitSetupAsync();
            }

            var corefxIssue = new GitHubIssue
            {
                ID          = number.ToString(),
                Title       = title,
                Description = body
            };

            string label = await Predictor.PredictAsync(corefxIssue, logger, _threshold);

            if (label != null)
            {
                var issueUpdate = new IssueUpdate();
                issueUpdate.AddLabel(label);
                issueUpdate.Milestone = milestone; // The number of milestone associated with the issue.

                await _client.Issue.Update(_repoOwner, _repoName, number, issueUpdate);
            }
            else
            {
                logger.LogInformation($"! The Model is not able to assign the label to the Issue {corefxIssue.ID} confidently.");
            }
        }
Exemplo n.º 10
0
        public async Task PredictAndApplyLabelAsync(int number, string title, string body, ILogger logger)
        {
            if (_client == null)
            {
                await GitSetupAsync();
            }

            var corefxIssue = new GitHubIssue
            {
                Number = number,
                Title  = title,
                Body   = body
            };

            string label = Predictor.Predict(corefxIssue, logger, _threshold);
            Issue  issueGithubVersion = await _client.Issue.Get(_repoOwner, _repoName, number);

            if (label != null && issueGithubVersion.Labels.Count == 0)
            {
                var issueUpdate = new IssueUpdate();
                issueUpdate.AddLabel(label);
                issueUpdate.Milestone = issueGithubVersion.Milestone?.Number; // The number of milestone associated with the issue.

                await _client.Issue.Update(_repoOwner, _repoName, number, issueUpdate);
            }
            else
            {
                logger.LogInformation($"! The Model is not able to assign the label to the Issue {corefxIssue.Number} confidently.");
            }
        }
Exemplo n.º 11
0
        public override async Task <IEnumerable <WorkItemModel> > FileWorkItems(IEnumerable <WorkItemModel> workItemModels)
        {
            foreach (WorkItemModel workItemModel in workItemModels)
            {
                var newIssue = new NewIssue(workItemModel.Title)
                {
                    Body = workItemModel.BodyOrDescription,
                };

                Issue issue = await this.gitHubClient.Issue.Create(
                    this.AccountOrOrganization,
                    this.ProjectOrRepository,
                    newIssue);

                // TODO: Can we collapse GH issue creation to a single operation?
                //
                // https://github.com/microsoft/sarif-sdk/issues/1790

                if (workItemModel.LabelsOrTags?.Count != 0)
                {
                    var issueUpdate = new IssueUpdate();

                    foreach (string tag in workItemModel.LabelsOrTags)
                    {
                        issueUpdate.AddLabel(tag);
                    }

                    await this.gitHubClient.Issue.Update(
                        this.AccountOrOrganization,
                        this.ProjectOrRepository,
                        issue.Number,
                        issueUpdate);
                }

                workItemModel.Uri     = new Uri(issue.Url, UriKind.Absolute);
                workItemModel.HtmlUri = new Uri(issue.HtmlUrl, UriKind.Absolute);

                // TODO: Extend GitHub issue filer to add file attachments
                // https://github.com/microsoft/sarif-sdk/issues/1754

                // TODO: Provide helper that generates useful attachment name from filed bug.
                //       This helper should be common to both ADO and GH filers. The implementation
                //       should work like this: the filer should prefix the proposed file name with
                //       the account and project and number of the filed work item. So an attachment
                //       name of Scan.sarif would be converted tO
                //
                //          MyAcct_MyProject_WorkItem1000_Scan.sarif
                //
                //       The GH filer may prefer to use 'issue' instead:
                //
                //          myowner_my-repo_Issue1000_Scan.sarif
                //
                //       The common helper should preserve casing choices in the account/owner and
                //       project/repo information that's provided.
                //
                //       https://github.com/microsoft/sarif-sdk/issues/1753
            }
            return(workItemModels);
        }
Exemplo n.º 12
0
        private void UpdateLabels(Issue issue, string label)
        {
            var issueUpdate = new IssueUpdate();

            issueUpdate.AddLabel(label);

            _client.Issue.Update(_owner, _name, issue.Number, issueUpdate).GetAwaiter().GetResult();
        }
Exemplo n.º 13
0
        public void AddIssueLabel(long repo, int issueNum, string label)
        {
            var isseuUpdate = new IssueUpdate();

            isseuUpdate.AddLabel(label);

            client.Issue.Update(repo, issueNum, isseuUpdate).Wait();
        }
Exemplo n.º 14
0
        private void ApplyLabel(Issue issue, string label)
        {
            var issueUpdate = new IssueUpdate();
            issueUpdate.AddLabel(label);

            _client.Issue.Update(_repoOwner, _repoName, issue.Number, issueUpdate);

            Console.WriteLine($"Issue {issue.Number} : \"{issue.Title}\" \t was labeled as: {label}");
        }
Exemplo n.º 15
0
        private void CreatePullRequest(Repository repo, GitHubClient gitHubClient, Remote origin, string branch)
        {
            // Oktokit is async-heavy, but we don't want to make ICommand asynchronous just for that.
            CreatePullRequestAsync().GetAwaiter().GetResult();

            async Task CreatePullRequestAsync()
            {
                string user = origin.Url.Substring("https://github.com/".Length).Split('/').First();
                string head = $"{user}:{branch}";

                var commitMessage      = repo.Commits.First().Message;
                var commitMessageLines = commitMessage.Replace("\r", "").Split('\n').ToList();
                var pullRequestLines   = UnwrapLines(commitMessageLines);

                var request = new NewPullRequest(pullRequestLines.First(), head, "main")
                {
                    Body = string.Join('\n', pullRequestLines.Skip(1))
                };
                var pullRequest = await gitHubClient.PullRequest.Create(RepositoryOwner, RepositoryName, request);

                // Note: using a collection initializer looks reasonable, but fails with an NRE, because the Labels
                // property is lazily initialized :(
                var issueUpdate = new IssueUpdate();

                issueUpdate.AddLabel(AutoreleasePendingLabel);
                issueUpdate.AddLabel(AutomergeExactLabel);
                string assignee = Environment.GetEnvironmentVariable(AssigneeEnvironmentVariable);

                if (!string.IsNullOrEmpty(assignee))
                {
                    issueUpdate.AddAssignee(assignee);
                }
                await gitHubClient.Issue.Update(RepositoryOwner, RepositoryName, pullRequest.Number, issueUpdate);

                // The PR link is useful to be able to click on, and occasionally the release branch is useful.
                Console.WriteLine($"Created branch {branch} and PR {pullRequest.HtmlUrl}");
            }
        }
        /// <summary>
        /// Creates a Pull Request.
        /// </summary>
        /// <param name="appConfig">The application configuration object which contains values
        /// for connecting to the specified GitHub repository.</param>
        /// <param name="privateKey">The RSA private key of a registered GitHub app installed in the specified repository.</param>
        /// <returns>A task.</returns>
        public static async Task CreatePullRequestAsync(ApplicationConfig appConfig, string privateKey)
        {
            if (appConfig == null)
            {
                throw new ArgumentNullException(nameof(appConfig), "Parameter cannot be null");
            }
            if (string.IsNullOrEmpty(privateKey))
            {
                throw new ArgumentNullException(nameof(privateKey), "Parameter cannot be null or empty");
            }

            var gitHubClient = GitHubClientFactory.GetGitHubClient(appConfig, privateKey);

            // Create a PR
            // NB: If the PR already exists, this call will just throw an exception
            var pullRequest =
                await gitHubClient.Repository.PullRequest.Create(appConfig.GitHubOrganization,
                                                                 appConfig.GitHubRepoName,
                                                                 new NewPullRequest(appConfig.PullRequestTitle,
                                                                                    appConfig.WorkingBranch,
                                                                                    appConfig.ReferenceBranch)
                                                                 { Body = appConfig.PullRequestBody });

            // Add PR reviewers
            if (appConfig.Reviewers != null)
            {
                var reviewersResult = await gitHubClient.Repository.PullRequest.ReviewRequest.Create(appConfig.GitHubOrganization,
                                                                                                     appConfig.GitHubRepoName,
                                                                                                     pullRequest.Number,
                                                                                                     new PullRequestReviewRequest(appConfig.Reviewers.AsReadOnly(), null));
            }

            var issueUpdate = new IssueUpdate();

            // Add PR assignee
            appConfig.PullRequestAssignees?.ForEach(assignee => issueUpdate.AddAssignee(assignee));

            // Add PR label
            appConfig.PullRequestLabels?.ForEach(label => issueUpdate.AddLabel(label));

            // Update the PR with the relevant info.
            if (issueUpdate.Assignees?.Count > 0 ||
                issueUpdate.Labels?.Count > 0)
            {
                await gitHubClient.Issue.Update(appConfig.GitHubOrganization,
                                                appConfig.GitHubRepoName,
                                                pullRequest.Number,
                                                issueUpdate);
            }
        }
    public async Task ReturnsDistinctIssueLabelsBasedOnStartPageForAMilestoneWithRepositoryId()
    {
        var newMilestone = new NewMilestone("New Milestone");
        var milestone    = await _issuesClient.Milestone.Create(_context.RepositoryOwner, _context.RepositoryName, newMilestone);

        for (int i = 0; i < 2; i++)
        {
            int k        = i + 1;
            var newIssue = new NewIssue("A test issue " + k)
            {
                Body = "A new unassigned issue " + k
            };
            var newLabel = new NewLabel("test label " + k, "FFFFF" + k);

            var label = await _issuesLabelsClient.Create(_context.Repository.Id, newLabel);

            var issue = await _issuesClient.Create(_context.RepositoryOwner, _context.RepositoryName, newIssue);

            var issueUpdate = new IssueUpdate {
                Milestone = milestone.Number
            };
            issueUpdate.AddLabel(label.Name);
            var updated = await _issuesClient.Update(_context.RepositoryOwner, _context.RepositoryName, issue.Number, issueUpdate);

            Assert.NotNull(updated);
        }

        var startOptions = new ApiOptions
        {
            PageCount = 1,
            PageSize  = 1,
            StartPage = 1
        };

        var firstPage = await _issuesLabelsClient.GetAllForMilestone(_context.Repository.Id, milestone.Number, startOptions);

        var skipStartOptions = new ApiOptions
        {
            PageSize  = 1,
            PageCount = 1,
            StartPage = 2
        };

        var secondPage = await _issuesLabelsClient.GetAllForMilestone(_context.Repository.Id, milestone.Number, skipStartOptions);

        Assert.Equal(1, firstPage.Count);
        Assert.Equal(1, secondPage.Count);
        Assert.NotEqual(firstPage.First().Color, secondPage.First().Color);
    }
        private void UpdateIssue()
        {
            var issue = new IssueUpdate();

            issue.Title     = Title;
            issue.Body      = Body;
            issue.Assignee  = Assignee != null ? Assignee.Login : null;
            issue.Milestone = Milestone != null ? (int?)Milestone.Number : null;

            foreach (var label in SelectedLabels)
            {
                issue.AddLabel(label.Name);
            }

            GitHubApi.UpdateIssue(_repository, _issueNumber, issue);
        }
Exemplo n.º 19
0
        private void ApplyLabels(Issue issue, FullPrediction[] fullPredictions)
        {
            var issueUpdate = new IssueUpdate();

            //assign labels in GITHUB only if predicted score of all predictions is > 30%
            foreach (var fullPrediction in fullPredictions)
            {
                if (fullPrediction.Score >= 0.3)
                {
                    issueUpdate.AddLabel(fullPrediction.PredictedLabel);
                    _client.Issue.Update(_repoOwner, _repoName, issue.Number, issueUpdate);

                    Console.WriteLine($"Issue {issue.Number} : \"{issue.Title}\" \t was labeled as: {fullPredictions[0].PredictedLabel}");
                }
            }
        }
Exemplo n.º 20
0
        /// <summary>
        /// Update Lable for a given issue
        /// </summary>
        /// <param name="vm">IssuesConfigViewModel</param>
        /// <returns>Issue object</returns>
        public Octokit.Issue UpdateLabel(WorkingViewModel vm, string label)
        {
            //connect and build client
            var client    = new GitHubClient(new Octokit.ProductHeaderValue(_appName));
            var tokenAuth = new Credentials(_token);

            client.Credentials = tokenAuth;

            //issue we want to update
            IssueUpdate issueUpdate = vm.issue.ToUpdate();

            //add label to issue
            issueUpdate.AddLabel(label);

            //complete update and return results
            var result = client.Issue.Update(vm.organization, vm.repository, vm.issue.Number, issueUpdate).Result;

            return(result);
        }
    public async Task ReturnsDistinctIssueLabelsBasedOnStartPageForAnIssue()
    {
        var issue = await _issuesClient.Create(_context.RepositoryOwner, _context.RepositoryName, new NewIssue("A test issue") { Body = "A new unassigned issue" });

        var issueUpdate = new IssueUpdate();

        for (int i = 0; i < 2; i++)
        {
            var label = await _issuesLabelsClient.Create(_context.RepositoryOwner, _context.RepositoryName, new NewLabel("test label " + (i + 1), "FFFFF" + (i + 1)));

            issueUpdate.AddLabel(label.Name);
        }

        var issueLabelsInfo = await _issuesLabelsClient.GetAllForIssue(_context.RepositoryOwner, _context.RepositoryName, issue.Number);

        Assert.Empty(issueLabelsInfo);

        var updated = await _issuesClient.Update(_context.RepositoryOwner, _context.RepositoryName, issue.Number, issueUpdate);

        Assert.NotNull(updated);

        var startOptions = new ApiOptions
        {
            PageCount = 1,
            PageSize  = 1,
            StartPage = 1
        };

        var firstPage = await _issuesLabelsClient.GetAllForIssue(_context.RepositoryOwner, _context.RepositoryName, issue.Number, startOptions);

        var skipStartOptions = new ApiOptions
        {
            PageSize  = 1,
            PageCount = 1,
            StartPage = 2
        };

        var secondPage = await _issuesLabelsClient.GetAllForIssue(_context.RepositoryOwner, _context.RepositoryName, issue.Number, skipStartOptions);

        Assert.Equal(1, firstPage.Count);
        Assert.Equal(1, secondPage.Count);
        Assert.NotEqual(firstPage.First().Color, secondPage.First().Color);
    }
Exemplo n.º 22
0
        public async Task <IActionResult> DispatchIssueTo(string ownerName, string repoName, int issueNumber, string destinationLabel)
        {
            var accessToken = await HttpContext.GetTokenAsync("access_token");

            var gitHub = GitHubUtils.GetGitHubClient(accessToken);

            var issueUpdate = new IssueUpdate();

            issueUpdate.AddLabel(destinationLabel);
            try
            {
                await gitHub.Issue.Update(ownerName, repoName, issueNumber, issueUpdate);

                return(Ok());
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Exemplo n.º 23
0
        public async Task PredictAndApplyLabelAsync(int number, string title, string body, GithubObjectType issueOrPr, ILogger logger)
        {
            if (_client == null)
            {
                await GitSetupAsync();
            }
            if (_regex == null)
            {
                _regex = new Regex(@"@[a-zA-Z0-9_//-]+");
            }
            var userMentions = _regex.Matches(body).Select(x => x.Value).ToArray();

            string label;

            if (issueOrPr == GithubObjectType.Issue)
            {
                IssueModel issue = CreateIssue(number, title, body, userMentions);
                label = Predictor.Predict(issue, logger, _threshold);
            }
            else
            {
                PrModel pr = await CreatePullRequest(number, title, body, userMentions);

                label = Predictor.Predict(pr, logger, _threshold);
            }

            Issue issueGithubVersion = await _client.Issue.Get(_repoOwner, _repoName, number);

            if (label != null && issueGithubVersion.Labels.Count == 0)
            {
                var issueUpdate = new IssueUpdate();
                issueUpdate.AddLabel(label);
                issueUpdate.Milestone = issueGithubVersion.Milestone?.Number; // The number of milestone associated with the issue.

                await _client.Issue.Update(_repoOwner, _repoName, number, issueUpdate);
            }
            else
            {
                logger.LogInformation($"! The Model is not able to assign the label to the {issueOrPr} {number} confidently.");
            }
        }
Exemplo n.º 24
0
        public async Task PredictAndApplyLabelAsync(int number, string title, string body, GithubObjectType issueOrPr, ILogger logger)
        {
            if (_client == null)
            {
                await GitSetupAsync();
            }

            var corefxIssue = new GitHubIssue
            {
                Number    = number,
                Title     = title,
                Body      = body,
                IssueOrPr = issueOrPr,
                IsPR      = issueOrPr == GithubObjectType.PullRequest,
                FilePaths = string.Empty
            };

            if (corefxIssue.IsPR)
            {
                IReadOnlyList <PullRequestFile> prFiles = await _client.PullRequest.Files(_repoOwner, _repoName, number);

                corefxIssue.FilePaths = String.Join(";", prFiles.Select(x => x.FileName));
            }

            string label = Predictor.Predict(corefxIssue, logger, _threshold);
            Issue  issueGithubVersion = await _client.Issue.Get(_repoOwner, _repoName, number);

            if (label != null && issueGithubVersion.Labels.Count == 0)
            {
                var issueUpdate = new IssueUpdate();
                issueUpdate.AddLabel(label);
                issueUpdate.Milestone = issueGithubVersion.Milestone?.Number; // The number of milestone associated with the issue.

                await _client.Issue.Update(_repoOwner, _repoName, number, issueUpdate);
            }
            else
            {
                logger.LogInformation($"! The Model is not able to assign the label to the {issueOrPr} {corefxIssue.Number} confidently.");
            }
        }
Exemplo n.º 25
0
    public async Task CanGetWithLabelsForRepositoryWithRepositoryId()
    {
        await CreateTheWorld();

        var newPullRequest = new NewPullRequest("a pull request", branchName, "master");
        var result         = await _fixture.Create(_context.Repository.Id, newPullRequest);

        // Add a label
        var issueUpdate = new IssueUpdate();

        issueUpdate.AddLabel(labelName);
        await _github.Issue.Update(_context.Repository.Id, result.Number, issueUpdate);

        // Retrieve the Pull Requests
        var pullRequests = await _fixture.GetAllForRepository(_context.Repository.Id);

        Assert.Equal(1, pullRequests.Count);
        Assert.Equal(result.Title, pullRequests[0].Title);
        Assert.Equal(Helper.UserName, pullRequests[0].Assignee.Login);
        Assert.Equal(1, pullRequests[0].Labels.Count);
        Assert.Contains(pullRequests[0].Labels, x => x.Name == labelName);
    }
Exemplo n.º 26
0
        public async Task PredictAndApplyLabelAsync(int number, string title, string body, GithubObjectType issueOrPr, ILogger logger)
        {
            if (_client == null)
            {
                await GitSetupAsync();
            }

            var corefxIssue = new GitHubIssue
            {
                Number    = number,
                Title     = title,
                Body      = body,
                IssueOrPr = issueOrPr
            };

            string label = Predictor.Predict(corefxIssue, logger, _threshold);
            Issue  issueGithubVersion = await _client.Issue.Get(_repoOwner, _repoName, number);

            if (label.Equals("area-System.Net.Http.SocketsHttpHandler", StringComparison.OrdinalIgnoreCase))
            {
                label = "area-System.Net.Http";
            }

            if (label != null && issueGithubVersion.Labels.Count == 0)
            {
                var issueUpdate = new IssueUpdate();
                issueUpdate.AddLabel(label);
                issueUpdate.Milestone = issueGithubVersion.Milestone?.Number; // The number of milestone associated with the issue.

                await _client.Issue.Update(_repoOwner, _repoName, number, issueUpdate);
            }
            else
            {
                logger.LogInformation($"! The Model is not able to assign the label to the {issueOrPr} {corefxIssue.Number} confidently.");
            }
        }
    public async Task ReturnsCorrectCountOfIssueLabelsWithStartForAnIssueWithRepositoryId()
    {
        var issue = await _issuesClient.Create(_context.RepositoryOwner, _context.RepositoryName, new NewIssue("A test issue") { Body = "A new unassigned issue" });

        var issueUpdate = new IssueUpdate();

        var labels = new List <Label>();

        for (int i = 0; i < 2; i++)
        {
            var label = await _issuesLabelsClient.Create(_context.Repository.Id, new NewLabel("test label " + (i + 1), "FFFFF" + (i + 1)));

            labels.Add(label);
            issueUpdate.AddLabel(label.Name);
        }

        var issueLabelsInfo = await _issuesLabelsClient.GetAllForIssue(_context.Repository.Id, issue.Number);

        Assert.Empty(issueLabelsInfo);

        var updated = await _issuesClient.Update(_context.RepositoryOwner, _context.RepositoryName, issue.Number, issueUpdate);

        Assert.NotNull(updated);

        var options = new ApiOptions
        {
            PageCount = 1,
            PageSize  = 1,
            StartPage = 2
        };

        issueLabelsInfo = await _issuesLabelsClient.GetAllForIssue(_context.Repository.Id, issue.Number, options);

        Assert.Equal(1, issueLabelsInfo.Count);
        Assert.Equal(labels.Last().Color, issueLabelsInfo.First().Color);
    }
Exemplo n.º 28
0
        public async Task <Pr> OpenAsync(GitHubClientParameters parameters, bool update, Settings settings = null)
        {
            var inMemoryCredentialStore = new InMemoryCredentialStore(new Credentials(KnownGitHubs.Username, parameters.Password));
            var githubClient            = new GitHubClient(new ProductHeaderValue("ImgBot"), inMemoryCredentialStore);

            var repo = await githubClient.Repository.Get(parameters.RepoOwner, parameters.RepoName);

            var branch = await githubClient.Repository.Branch.Get(parameters.RepoOwner, parameters.RepoName, KnownGitHubs.BranchName);

            var commit = await githubClient.Repository.Commit.Get(parameters.RepoOwner, parameters.RepoName, branch.Commit.Sha);

            if (branch == null)
            {
                return(null);
            }

            var baseBranch = repo.DefaultBranch;

            if (settings != null && !string.IsNullOrEmpty(settings.DefaultBranchOverride))
            {
                baseBranch = settings.DefaultBranchOverride;
            }

            var stats = Stats.ParseStats(commit.Commit.Message);

            Octokit.PullRequest result;
            if (update)
            {
                // get PR number
                var allPrs = await githubClient.PullRequest.GetAllForRepository(parameters.RepoOwner, parameters.RepoName);

                var pr = allPrs.FirstOrDefault(p => p.State == ItemState.Open && p.Head.Sha == commit.Sha);

                if (pr == null)
                {
                    throw new Exception("Couldn't update PR. PR not found");
                }

                var pru = new PullRequestUpdate()
                {
                    Body = PullRequestBody.Generate(stats, settings),
                };

                result = await githubClient.PullRequest.Update(parameters.RepoOwner, parameters.RepoName, pr.Number, pru);
            }
            else
            {
                var commitMessageTitle = KnownGitHubs.CommitMessageTitle;
                if (settings?.PrTitle != null)
                {
                    commitMessageTitle = settings.PrTitle;
                }

                var pr = new NewPullRequest(commitMessageTitle, KnownGitHubs.BranchName, baseBranch)
                {
                    Body = PullRequestBody.Generate(stats, settings),
                };
                result = await githubClient.PullRequest.Create(parameters.RepoOwner, parameters.RepoName, pr);
            }

            var labels = new List <string>();

            if (settings?.Labels != null)
            {
                var issueUpdate = new IssueUpdate();
                foreach (var label in settings.Labels.Split(','))
                {
                    issueUpdate.AddLabel(label);
                }

                await githubClient.Issue.Update(parameters.RepoOwner, parameters.RepoName, result.Number, issueUpdate);
            }

            if (stats == null)
            {
                return(null);
            }

            return(new Pr(parameters.RepoOwner)
            {
                RepoName = parameters.RepoName,
                Id = result.Id,
                NumImages = stats.Length == 1 ? 1 : stats.Length - 1,
                Number = result.Number,
                SizeBefore = ImageStat.ToDouble(stats[0].Before),
                SizeAfter = ImageStat.ToDouble(stats[0].After),
                PercentReduced = stats[0].Percent,
            });
        }
        public async Task WriteToRepositoryAsync(ApplicationConfig appConfig, string privateKey)
        {
            if (appConfig == null)
            {
                throw new ArgumentNullException(nameof(appConfig), "Parameter cannot be null");
            }

            try
            {
                string token = await GitHubAuthService.GetGithubAppTokenAsync(appConfig, privateKey);

                // Pass the JWT as a Bearer token to Octokit.net
                var finalClient = new GitHubClient(new ProductHeaderValue(appConfig.GitHubAppName))
                {
                    Credentials = new Credentials(token, AuthenticationType.Bearer)
                };

                // Get repo references
                var references = await finalClient.Git.Reference.GetAll(appConfig.GitHubOrganization, appConfig.GitHubRepoName);

                // Check if the working branch is in the refs
                var workingBranch = references.Where(reference => reference.Ref == $"refs/heads/{appConfig.WorkingBranch}").FirstOrDefault();

                // Check if branch already exists.
                if (workingBranch == null)
                {
                    // Working branch does not exist so branch off reference branch
                    var refBranch = references.Where(reference => reference.Ref == $"refs/heads/{appConfig.ReferenceBranch}").FirstOrDefault();

                    // Exception will throw if branch already exists
                    var newBranch = await finalClient.Git.Reference.Create(appConfig.GitHubOrganization, appConfig.GitHubRepoName,
                                                                           new NewReference($"refs/heads/{appConfig.WorkingBranch}", refBranch.Object.Sha));

                    // create file
                    var createChangeSet = await finalClient.Repository.Content.CreateFile(
                        appConfig.GitHubOrganization,
                        appConfig.GitHubRepoName,
                        appConfig.FileContentPath,
                        new CreateFileRequest(appConfig.CommitMessage,
                                              appConfig.FileContent,
                                              appConfig.WorkingBranch));
                }
                else
                {
                    // Get reference of the working branch
                    var masterReference = await finalClient.Git.Reference.Get(appConfig.GitHubOrganization,
                                                                              appConfig.GitHubRepoName, workingBranch.Ref);

                    // Get the latest commit of this branch
                    var latestCommit = await finalClient.Git.Commit.Get(appConfig.GitHubOrganization, appConfig.GitHubRepoName,
                                                                        masterReference.Object.Sha);

                    // Create blob
                    NewBlob blob = new NewBlob {
                        Encoding = EncodingType.Utf8, Content = appConfig.FileContent
                    };
                    BlobReference blobRef =
                        await finalClient.Git.Blob.Create(appConfig.GitHubOrganization, appConfig.GitHubRepoName, blob);

                    // Create new Tree
                    var tree = new NewTree {
                        BaseTree = latestCommit.Tree.Sha
                    };

                    // Add items based on blobs
                    tree.Tree.Add(new NewTreeItem
                    {
                        Path = appConfig.FileContentPath, Mode = appConfig.TreeItemMode.ToString(), Type = TreeType.Blob, Sha = blobRef.Sha
                    });

                    var newTree = await finalClient.Git.Tree.Create(appConfig.GitHubOrganization, appConfig.GitHubRepoName, tree);

                    // Create commit
                    var newCommit = new NewCommit(appConfig.CommitMessage, newTree.Sha,
                                                  masterReference.Object.Sha);
                    var commit =
                        await finalClient.Git.Commit.Create(appConfig.GitHubOrganization, appConfig.GitHubRepoName, newCommit);

                    // Push the commit
                    await finalClient.Git.Reference.Update(appConfig.GitHubOrganization, appConfig.GitHubRepoName, workingBranch.Ref,
                                                           new ReferenceUpdate(commit.Sha));
                }

                // Create PR
                var pullRequest = await finalClient.Repository.PullRequest.Create(appConfig.GitHubOrganization,
                                                                                  appConfig.GitHubAppName,
                                                                                  new NewPullRequest(appConfig.PullRequestTitle, appConfig.WorkingBranch, appConfig.ReferenceBranch) { Body = appConfig.PullRequestBody });

                // Add reviewers
                var teamMembers     = appConfig.Reviewers;
                var reviewersResult = await finalClient.Repository.PullRequest.ReviewRequest.Create(appConfig.GitHubOrganization,
                                                                                                    appConfig.GitHubRepoName, pullRequest.Number,
                                                                                                    new PullRequestReviewRequest(teamMembers.AsReadOnly(), null));

                // Add label
                var issueUpdate = new IssueUpdate();
                issueUpdate.AddAssignee(appConfig.PullRequestAssignee);
                issueUpdate.AddLabel(appConfig.PullRequestLabel);

                // Update the PR with the relevant info
                await finalClient.Issue.Update(appConfig.GitHubOrganization, appConfig.GitHubRepoName, pullRequest.Number,
                                               issueUpdate);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 30
0
        static async Task Main()
        {
            string token = await GetGithubAppToken();

            // Pass the JWT as a Bearer token to Octokit.net
            var finalClient = new GitHubClient(new ProductHeaderValue("PermissionsScraper"))
            {
                Credentials = new Credentials(token, AuthenticationType.Bearer)
            };

            // Get Repo references
            var references = await finalClient.Git.Reference.GetAll("microsoftgraph", "microsoft-graph-devx-content");

            // Check if the test branch is in the refs
            var testBranch = references.Where(reference => reference.Ref == "refs/heads/test").FirstOrDefault();

            // check if branch already exists.
            if (testBranch == null)
            {
                // test branch does not exist so branch odd dev
                var devBranch = references.Where(reference => reference.Ref == "refs/heads/dev").FirstOrDefault();

                // exception will throw if branch already exists
                var newBranch = await finalClient.Git.Reference.Create("microsoftgraph", "microsoft-graph-devx-content",
                                                                       new NewReference("refs/heads/test", devBranch.Object.Sha));

                // create file
                var createChangeSet = await finalClient.Repository.Content.CreateFile(
                    "microsoftgraph",
                    "microsoft-graph-devx-content",
                    "path/file.txt",
                    new CreateFileRequest("File creation",
                                          "Hello Andrew!",
                                          "test"));
            }
            else
            {
                // Get reference of test branch
                var masterReference = await finalClient.Git.Reference.Get("microsoftgraph",
                                                                          "microsoft-graph-devx-content", testBranch.Ref);

                // Get the laster commit of this branch
                var latestCommit = await finalClient.Git.Commit.Get("microsoftgraph", "microsoft-graph-devx-content",
                                                                    masterReference.Object.Sha);

                // Create text blob
                var textBlob = new NewBlob {
                    Encoding = EncodingType.Utf8, Content = "Hello Sunday"
                };
                var textBlobRef =
                    await finalClient.Git.Blob.Create("microsoftgraph", "microsoft-graph-devx-content", textBlob);

                // Create new Tree
                var nt = new NewTree {
                    BaseTree = latestCommit.Tree.Sha
                };
                // Add items based on blobs
                nt.Tree.Add(new NewTreeItem
                {
                    Path = "path/file.txt", Mode = "100644", Type = TreeType.Blob, Sha = textBlobRef.Sha
                });

                var newTree = await finalClient.Git.Tree.Create("microsoftgraph", "microsoft-graph-devx-content", nt);

                // Create Commit
                var newCommit = new NewCommit("Commit test with several files", newTree.Sha,
                                              masterReference.Object.Sha);
                var commit =
                    await finalClient.Git.Commit.Create("microsoftgraph", "microsoft-graph-devx-content", newCommit);

                // push the commit
                await finalClient.Git.Reference.Update("microsoftgraph", "microsoft-graph-devx-content", testBranch.Ref,
                                                       new ReferenceUpdate(commit.Sha));
            }

            // create PR
            var pullRequest = await finalClient.Repository.PullRequest.Create("microsoftgraph",
                                                                              "microsoft-graph-devx-content",
                                                                              new NewPullRequest("Timely content update", "test", "dev") { Body = "This is a test PR" });

            // Add reviewers
            var teamMembers = new List <string> {
                "andrueastman", "bettirosengugi"
            };
            var reviewersResult = await finalClient.Repository.PullRequest.ReviewRequest.Create("microsoftgraph",
                                                                                                "microsoft-graph-devx-content", pullRequest.Number,
                                                                                                new PullRequestReviewRequest(teamMembers.AsReadOnly(), null));

            // Add label
            var issueUpdate = new IssueUpdate();

            issueUpdate.AddAssignee("irvinesunday");
            issueUpdate.AddLabel("Generated");

            // Update the PR with the relevant info
            await finalClient.Issue.Update("microsoftgraph", "microsoft-graph-devx-content", pullRequest.Number,
                                           issueUpdate);
        }