public async Task ReturnsCorrectCountOfIssueLabelsWithoutStartForAMilestone()
    {
        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.RepositoryOwner, _context.RepositoryName, 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 options = new ApiOptions
        {
            PageCount = 1,
            PageSize  = 1
        };

        var issueLabelsInfo = await _issuesLabelsClient.GetAllForMilestone(_context.RepositoryOwner, _context.RepositoryName, milestone.Number, options);

        Assert.Equal(1, issueLabelsInfo.Count);
    }
Exemple #2
0
        private static async Task CloseIssuesAsync(GitHubClient client, string orgName, string policyRepo, IReadOnlyList <PolicyViolation> violations, IReadOnlyList <Issue> existingIssues)
        {
            var newFingerprints = new HashSet <Guid>(violations.Select(v => v.Fingerprint));

            var solvedIssues = existingIssues.Select(issue => (Fingerprint: GetFingerprint(issue.Title), Issue: issue))
                               .Where(t => t.Fingerprint != null && !newFingerprints.Contains(t.Fingerprint.Value))
                               .Select(t => t.Issue)
                               .ToList();

            var i = 0;

            foreach (var solvedIssue in solvedIssues)
            {
                await client.PrintProgressAsync(Console.Out, "Closing issue", solvedIssue.Title, i ++, solvedIssues.Count);

                await client.Issue.Comment.Create(orgName, policyRepo, solvedIssue.Number, "The violation was addressed.");

                var issueUpdate = new IssueUpdate
                {
                    State = ItemState.Closed
                };
                await client.Issue.Update(orgName, policyRepo, solvedIssue.Number, issueUpdate);
            }
        }
Exemple #3
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);
    }
Exemple #5
0
 public abstract void UpdateIssue(Repository repository, int id, IssueUpdate update);
            public void PostsToCorrectUrl()
            {
                var issueUpdate = new IssueUpdate();
                var connection = Substitute.For<IApiConnection>();
                var client = new IssuesClient(connection);

                client.Update("fake", "repo", 42, issueUpdate);

                connection.Received().Patch<Issue>(Arg.Is<Uri>(u => u.ToString() == "repos/fake/repo/issues/42"),
                    issueUpdate);
            }
        public void UpdateIssue(string issueKey, IssueUpdate issueUpdate)
        {
            var source = $"{JiraSource}/issue/{issueKey}";

            SendHttpRequest(source, Method.PUT, issueUpdate);
        }
        /// <summary>
        /// Creates an issue for the specified repository. Any user with pull access to a repository can create an
        /// issue.
        /// </summary>
        /// <remarks>http://developer.github.com/v3/issues/#create-an-issue</remarks>
        /// <param name="owner">The owner of the repository</param>
        /// <param name="name">The name of the repository</param>
        /// <param name="number">The issue number</param>
        /// <param name="issueUpdate">An <see cref="IssueUpdate"/> instance describing the changes to make to the issue
        /// </param>
        /// <returns></returns>
        public IObservable<Issue> Update(string owner, string name, int number, IssueUpdate issueUpdate)
        {
            Ensure.ArgumentNotNullOrEmptyString(owner, "owner");
            Ensure.ArgumentNotNullOrEmptyString(name, "name");
            Ensure.ArgumentNotNull(issueUpdate, "issueUpdate");

            return _client.Update(owner, name, number, issueUpdate).ToObservable();
        }
        /// <summary>
        /// Creates an issue for the specified repository. Any user with pull access to a repository can create an
        /// issue.
        /// </summary>
        /// <remarks>http://developer.github.com/v3/issues/#create-an-issue</remarks>
        /// <param name="repositoryId">The Id of the repository</param>
        /// <param name="number">The issue number</param>
        /// <param name="issueUpdate">An <see cref="IssueUpdate"/> instance describing the changes to make to the issue
        /// </param>
        public IObservable <Issue> Update(int repositoryId, int number, IssueUpdate issueUpdate)
        {
            Ensure.ArgumentNotNull(issueUpdate, "issueUpdate");

            return(_client.Update(repositoryId, number, issueUpdate).ToObservable());
        }
        public async Task ProcessIssueEvent(IssuesHookData issuePayload)
        {
            if (issuePayload.Action != "opened" &&
                issuePayload.Action != "reopened" &&
                issuePayload.Action != "closed")
            {
                _logger.LogInformation($"Received github action '{issuePayload.Action}', nothing to do");
                return;
            }

            // Determine identifiable information for triage items
            var triageItems = GetTriageItems(issuePayload.Issue.Body);

            if (!triageItems.Any())
            {
                /* Item is not a triage item (does not contain identifiable information), do nothing */
                _logger.LogInformation($"{issuePayload.Issue.Url} is not a triage type issue.");

                return;
            }

            IGitHubClient gitHubClient = await _gitHubApplicationClientFactory.CreateGitHubClientAsync(issuePayload.Repository.Owner.Login, issuePayload.Repository.Name);

            if (issuePayload.Action == "opened" || issuePayload.Action == "reopened")
            {
                // First, look for duplicate issues that are open
                var openIssues = new RepositoryIssueRequest
                {
                    Filter        = IssueFilter.All,
                    State         = ItemStateFilter.Open,
                    SortProperty  = IssueSort.Created,
                    SortDirection = SortDirection.Ascending,
                };
                openIssues.Labels.Add(_markingLabelName);

                _logger.LogInformation("Getting open issues");
                var existingTriageIssues = await gitHubClient.Issue.GetAllForRepository(issuePayload.Repository.Id, openIssues);

                _logger.LogInformation($"There are {existingTriageIssues.Count} open issues with the '{_markingLabelName}' label");
                foreach (var existingIssue in existingTriageIssues)
                {
                    if (existingIssue.Number != issuePayload.Issue.Number)
                    {
                        var existingIssueItems = GetTriageItems(existingIssue.Body);
                        if (IsDuplicate(triageItems, existingIssueItems))
                        {
                            await gitHubClient.Issue.Comment.Create(issuePayload.Repository.Id, issuePayload.Issue.Number, $"Duplicate issue was detected.\n\nClosing as duplicate of {existingIssue.HtmlUrl}\n\nFor more information see {_docLink}");

                            var issueUpdate = new IssueUpdate
                            {
                                State = ItemState.Closed,
                            };
                            await gitHubClient.Issue.Update(issuePayload.Repository.Id, issuePayload.Issue.Number, issueUpdate);

                            return;
                        }
                    }
                }

                // No duplicates, add label and move issue to triage
                var issue = await gitHubClient.Issue.Get(issuePayload.Repository.Id, issuePayload.Issue.Number);

                if (!issue.Labels.Any(l => l.Name == _markingLabelName))
                {
                    var update = issue.ToUpdate();
                    update.AddLabel(_markingLabelName);
                    foreach (var label in _issueLabels)
                    {
                        if (issue.Labels.All(l => l.Name != label))
                        {
                            update.AddLabel(label);
                        }
                    }
                    await gitHubClient.Issue.Update(issuePayload.Repository.Id, issuePayload.Issue.Number, update);

                    await AddToZenHubTopic(issuePayload, gitHubClient, issue);
                }
            }

            if (issuePayload.Action == "closed")
            {
                IReadOnlyList <IssueComment> comments = gitHubClient.Issue.Comment.GetAllForIssue(issuePayload.Repository.Id, issuePayload.Issue.Number).Result;

                // find the latest comment with category command
                string updatedCategory = null;
                foreach (var comment in comments)
                {
                    string category = GetTriageIssueProperty("category", comment.Body);
                    if (!string.IsNullOrEmpty(category))
                    {
                        updatedCategory = category;
                    }
                }
                if (updatedCategory != null)
                {
                    foreach (var triageItem in triageItems)
                    {
                        triageItem.UpdatedCategory = updatedCategory;
                    }
                }
            }

            foreach (var triageItem in triageItems)
            {
                triageItem.Url = issuePayload.Issue.HtmlUrl;
                _logger.LogInformation($"buildId: {triageItem.BuildId}, recordId: {triageItem.RecordId}, index: {triageItem.Index}, category: {triageItem.UpdatedCategory}, url: {triageItem.Url}");
            }

            await IngestTriageItemsIntoKusto(triageItems);

            await gitHubClient.Issue.Comment.Create(issuePayload.Repository.Id, issuePayload.Issue.Number, $"Bot has updated the 'TimelineIssuesTriage' database.\n**PowerBI reports may take up to 24 hours to refresh**\n\nSee {_docLink} for more information.");

            return;
        }
Exemple #11
0
 public Issue UpdateIssue(int repositoryId, int issueId, IssueUpdate issueUpdate)
 {
     return(client.Issue.Update(repositoryId, issueId, issueUpdate).Result);
 }
Exemple #12
0
        /// <summary>
        /// Creates an issue for the specified repository. Any user with pull access to a repository can create an
        /// issue.
        /// </summary>
        /// <remarks>http://developer.github.com/v3/issues/#create-an-issue</remarks>
        /// <param name="repositoryId">The Id of the repository</param>
        /// <param name="number">The issue number</param>
        /// <param name="issueUpdate">An <see cref="IssueUpdate"/> instance describing the changes to make to the issue
        /// </param>
        public IObservable <Issue> Update(long repositoryId, long number, IssueUpdate issueUpdate)
        {
            Ensure.ArgumentNotNull(issueUpdate, nameof(issueUpdate));

            return(_client.Update(repositoryId, number, issueUpdate).ToObservable());
        }
        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);
        }
            public void PostsToCorrectUrlWithRepositoryId()
            {
                var issueUpdate = new IssueUpdate();
                var connection = Substitute.For<IApiConnection>();
                var client = new IssuesClient(connection);

                client.Update(1, 42, issueUpdate);

                connection.Received().Patch<Issue>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/issues/42"),
                    issueUpdate);
            }
Exemple #15
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 void UpdateIssue(IssueUpdate update, NetworkCredential credential,
            Action<string> stdout, Action<string> stderr)
        {
            var client = new Gurtle.WebClient();
            System.Collections.Specialized.NameValueCollection data = new System.Collections.Specialized.NameValueCollection(1);
            if (update.Comment.Length > 0)
            {
                data.Add("comment", update.Comment);
            }

            client.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(credential.UserName + ":" + credential.Password)));
            client.UploadValues(CommentIssueUrl(update.Issue.Id), data);
            data.Clear();
            client.UploadValues(CloseIssueUrl(update.Status, update.Issue.Id), data);
        }
        public Issue CreateTestCase(string projectKey, IssueInCycle issueInCycle, string reporter = null)
        {
            Issue issue = null;

            try
            {
                var description = $"Please refer to automation test - {issueInCycle.TestName}()";

                // step 1, create a test case in Jira
                if (string.IsNullOrWhiteSpace(issueInCycle.Key))
                {
                    var issueCreation = new IssueCreation
                    {
                        fields = new Fields
                        {
                            project = new ProjectField {
                                key = projectKey
                            },
                            summary     = issueInCycle.TestSummary,
                            description = description,
                            issuetype   = new Issuetype {
                                name = "Test"
                            },
                            reporter = new Reporter {
                                name = reporter
                            },
                            labels = issueInCycle.Labels
                        }
                    };
                    issueInCycle.Overwritten = false;
                    issue = CreateTestCase(issueCreation);
                }
                else // step 1, update a test case in Jira
                {
                    var issueUpdate = new IssueUpdate
                    {
                        fields = new UpdateFields
                        {
                            description = description,
                            labels      = issueInCycle.Labels,
                            summary     = issueInCycle.TestSummary
                        }
                    };
                    issueInCycle.Overwritten = true;
                    issue = UpdateTestCase(issueInCycle.Key, issueUpdate);
                }

                if (issue != null)
                {
                    // step 2, add test steps to the issue in Zephyr
                    if (issueInCycle.Steps != null && issueInCycle.Steps.Count > 0)
                    {
                        AddStepsToTestCase(issue.Key, issueInCycle.Steps, issueInCycle.Overwritten);
                    }

                    // step 3, add the test case to the constrain of version-cycles
                    if (issueInCycle.CycleNames != null && issueInCycle.CycleNames.Count > 0)
                    {
                        if (!string.IsNullOrWhiteSpace(issueInCycle.VersionName))
                        {
                            var version = GetReleaseVersion(issueInCycle.VersionName);
                            if (version != null)
                            {
                                foreach (var cycleName in issueInCycle.CycleNames)
                                {
                                    var cycle = GetTestCycle(version.Id, version.ProjectId, cycleName);
                                    if (cycle != null)
                                    {
                                        AddTestCaseToCycle(issue, cycle);
                                    }
                                }
                            }
                        }
                    }
                }

                return(issue);
            }
            catch (Exception e)
            {
                Debug.WriteLine($"Create test {issueInCycle.TestName} in Jira failed at: {e.Message}");
                return(issue);
            }
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "POST", Route = null)]
            HttpRequestMessage req, ILogger log)
        {
            var payloadJson = await req.Content.ReadAsStringAsync();

            SimpleJsonSerializer serializer   = new SimpleJsonSerializer();
            IssueEventPayload    issuePayload = serializer.Deserialize <IssueEventPayload>(payloadJson);

            if (issuePayload.Issue.User.Type.HasValue &&
                issuePayload.Issue.User.Type.Value == AccountType.Bot)
            {
                log.LogInformation("Comment is from DarcBot, ignoring.");
                return(new OkObjectResult($"Ignoring DarcBot comment"));
            }

            if (issuePayload.Action != "opened" &&
                issuePayload.Action != "reopened" &&
                issuePayload.Action != "closed")
            {
                log.LogInformation($"Received github action '{issuePayload.Action}', nothing to do");
                return(new OkObjectResult($"DarcBot has nothing to do with github issue action '{issuePayload.Action}'"));
            }

            // Determine identifiable information for triage item
            TriageItem triageItem = GetTriageItemProperties(issuePayload.Issue.Body);

            triageItem.Url = issuePayload.Issue.HtmlUrl;

            if (triageItem == null)
            {
                /* Item is not a triage item (does not contain identifiable information), do nothing */
                log.LogInformation($"{issuePayload.Issue.Url} is not a triage type issue.");
                return(new OkObjectResult("No identifiable information detected"));
            }

            int.TryParse(System.Environment.GetEnvironmentVariable("AppId"), out int appId);

            // Create jwt token
            // Private key is stored in Azure Key vault by downloading the private key (pem file) from GitHub, then
            // using the Azure CLI to store the value in key vault.
            // ie: az keyvault secret set --vault-name [vault name] --name GitHubApp-DarcBot-PrivateKey --encoding base64 --file [pem key file path]
            GitHubAppTokenProvider gitHubTokenProvider = new GitHubAppTokenProvider();
            var installationToken = gitHubTokenProvider.GetAppTokenFromEnvironmentVariableBase64(appId, "PrivateKey");

            // create client using jwt as a bearer token
            var          userAgent = new Octokit.ProductHeaderValue("DarcBot");
            GitHubClient appClient = new GitHubClient(userAgent)
            {
                Credentials = new Credentials(installationToken, AuthenticationType.Bearer),
            };

            // using the client, create an installation token
            AccessToken token = await appClient.GitHubApps.CreateInstallationToken(issuePayload.Installation.Id);

            // with the installation token, create a new GitHubClient that has the apps permissions
            var gitHubClient = new GitHubClient(new ProductHeaderValue("DarcBot-Installation"))
            {
                Credentials = new Credentials(token.Token)
            };

            if (issuePayload.Action == "created" ||
                issuePayload.Action == "opened" ||
                issuePayload.Action == "reopened")
            {
                // First, look for duplicate issues that are open
                var openIssues = new RepositoryIssueRequest
                {
                    Filter        = IssueFilter.All,
                    State         = ItemStateFilter.Open,
                    SortProperty  = IssueSort.Created,
                    SortDirection = SortDirection.Ascending,
                };
                openIssues.Labels.Add(_darcBotLabelName);

                log.LogInformation("Getting open issues");
                var issues = await gitHubClient.Issue.GetAllForRepository(issuePayload.Repository.Id, openIssues);

                log.LogInformation($"There are {issues.Count} open issues with the '{_darcBotLabelName}' label");
                foreach (var checkissue in issues)
                {
                    if (checkissue.Number != issuePayload.Issue.Number)
                    {
                        TriageItem issueItem = GetTriageItemProperties(checkissue.Body);
                        if (triageItem.Equals(issueItem))
                        {
                            await gitHubClient.Issue.Comment.Create(issuePayload.Repository.Id, issuePayload.Issue.Number, $"DarcBot has detected a duplicate issue.\n\nClosing as duplicate of {checkissue.HtmlUrl}\n\nFor more information see {_docLink}");

                            var issueUpdate = new IssueUpdate
                            {
                                State = ItemState.Closed,
                            };
                            await gitHubClient.Issue.Update(issuePayload.Repository.Id, issuePayload.Issue.Number, issueUpdate);

                            return(new OkObjectResult($"Resolved as duplicate of {checkissue.Number}"));
                        }
                    }
                }

                // No duplicates, add label and move issue to triage
                var issue = await gitHubClient.Issue.Get(issuePayload.Repository.Id, issuePayload.Issue.Number);

                var update = issue.ToUpdate();
                update.AddLabel(_darcBotLabelName);
                await gitHubClient.Issue.Update(issuePayload.Repository.Id, issuePayload.Issue.Number, update);

                triageItem.UpdatedCategory = "InTriage";
            }

            if (issuePayload.Action == "closed")
            {
                IReadOnlyList <IssueComment> comments = gitHubClient.Issue.Comment.GetAllForIssue(issuePayload.Repository.Id, issuePayload.Issue.Number).Result;

                foreach (var comment in comments)
                {
                    // Look for category information in comment
                    string category = GetDarcBotProperty("category", comment.Body);
                    if (!string.IsNullOrEmpty(category))
                    {
                        triageItem.UpdatedCategory = category;
                    }
                }
            }

            log.LogInformation($"buildId: {triageItem.BuildId}, recordId: {triageItem.RecordId}, index: {triageItem.Index}, category: {triageItem.UpdatedCategory}, url: {triageItem.Url}");

            await IngestTriageItemsIntoKusto(new[] { triageItem }, log);

            await gitHubClient.Issue.Comment.Create(issuePayload.Repository.Id, issuePayload.Issue.Number, $"DarcBot has updated the 'TimelineIssuesTriage' database.\n**PowerBI reports may take up to 24 hours to refresh**\n\nSee {_docLink} for more information and 'darcbot' usage.");

            return(new OkObjectResult("Success"));
        }
            public void UpdatesClientIssueIssue()
            {
                var IssueUpdate = new IssueUpdate();
                var gitHubClient = Substitute.For<IGitHubClient>();
                var client = new ObservableIssuesClient(gitHubClient);

                client.Update("fake", "repo", 42, IssueUpdate);

                gitHubClient.Issue.Received().Update("fake", "repo", 42, IssueUpdate);
            }
Exemple #20
0
        public void UpdateIssue(IssueUpdate update, NetworkCredential credential,
            Action<string> stdout, Action<string> stderr)
        {
            var client = new WebClient();
            client.Headers.Add("Content-Type", "application/json");
            client.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(credential.UserName + ":" + credential.Password)));

            var jsonRPCQuery = new JsonWriter();
            jsonRPCQuery.WriteObjectStart();
            jsonRPCQuery.WritePropertyName("method");
            jsonRPCQuery.Write("ticket.update");
            jsonRPCQuery.WritePropertyName("params");
            jsonRPCQuery.WriteArrayStart();
            jsonRPCQuery.Write(update.Issue.Id);
            jsonRPCQuery.Write(update.Comment);
            jsonRPCQuery.WriteObjectStart();
            jsonRPCQuery.WritePropertyName("action");
            jsonRPCQuery.Write("resolve");
            jsonRPCQuery.WritePropertyName("action_resolve_resolve_resolution");
            jsonRPCQuery.Write("fixed");
            jsonRPCQuery.WriteObjectEnd();
            jsonRPCQuery.Write(true);
            jsonRPCQuery.WriteArrayEnd();
            jsonRPCQuery.WriteObjectEnd();

            client.UploadString(this.RPCUrl(), jsonRPCQuery.ToString());
        }
        /// <summary>
        /// Creates an issue for the specified repository. Any user with pull access to a repository can create an
        /// issue.
        /// </summary>
        /// <remarks>http://developer.github.com/v3/issues/#create-an-issue</remarks>
        /// <param name="repositoryId">The ID of the repository</param>
        /// <param name="number">The issue number</param>
        /// <param name="issueUpdate">An <see cref="IssueUpdate"/> instance describing the changes to make to the issue
        /// </param>
        public IObservable<Issue> Update(int repositoryId, int number, IssueUpdate issueUpdate)
        {
            Ensure.ArgumentNotNull(issueUpdate, "issueUpdate");

            return _client.Update(repositoryId, number, issueUpdate).ToObservable();
        }
        public async ValueTask <string> UpdateIssueAsync(int number, IssueUpdate input)
        {
            var result = await _client.Issue.Update(_config.Owner, _config.Repo, number, input);

            return(result.NodeId);
        }
Exemple #23
0
        public static async Task CreateIssue(
            string TagName,
            string ExceptionMessage,
            string StackTrace,
            string Title,
            string Description)
        {
            try
            {
                //Gain access to the BrawlBox account on github for submitting the report.
                //I don't really care if this gets compromised, the token has no user settings access so I'll just revoke access to the token and generate a new one.
                //Have to use a byte array to (hopefully) bypass github's automatic detection of the token as a string.
                Octokit.Credentials s = new Credentials(System.Text.Encoding.Default.GetString(_rawData));
                var github            = new GitHubClient(new Octokit.ProductHeaderValue("Brawltools"))
                {
                    Credentials = s
                };
                IReadOnlyList <Release> releases = null;
                IReadOnlyList <Issue>   issues   = null;
                try
                {
                    releases = await github.Release.GetAll("libertyernie", "brawltools");

                    issues = await github.Issue.GetForRepository("BrawlBox", "BrawlBoxIssues");
                }
                catch (System.Net.Http.HttpRequestException)
                {
                    MessageBox.Show("Unable to connect to the internet.");
                    return;
                }

                if (releases != null && releases.Count > 0 && releases[0].TagName != TagName)
                {
                    //This build's version tag does not match the latest release's tag on the repository.
                    //This bug may have been fixed by now. Tell the user to update to be allowed to submit bug reports.

                    DialogResult UpdateResult = MessageBox.Show(releases[0].Name + " is available!\nYou cannot submit bug reports using an older version of the program.\nUpdate now?", "An update is available", MessageBoxButtons.YesNo);
                    if (UpdateResult == DialogResult.Yes)
                    {
                        DialogResult OverwriteResult = MessageBox.Show("Overwrite current installation?", "", MessageBoxButtons.YesNoCancel);
                        if (OverwriteResult != DialogResult.Cancel)
                        {
                            Task t = Updater.UpdateCheck(OverwriteResult == DialogResult.Yes);
                            t.Wait();
                        }
                    }
                }
                else
                {
                    bool found = false;
                    if (issues != null && !String.IsNullOrEmpty(StackTrace))
                    {
                        foreach (Issue i in issues)
                        {
                            if (i.State == ItemState.Open)
                            {
                                string desc = i.Body;
                                if (desc.Contains(StackTrace) &&
                                    desc.Contains(ExceptionMessage) &&
                                    desc.Contains(TagName))
                                {
                                    found = true;
                                    IssueUpdate update = i.ToUpdate();

                                    update.Body =
                                        Title +
                                        Environment.NewLine +
                                        Description +
                                        Environment.NewLine +
                                        Environment.NewLine +
                                        i.Body;

                                    Issue x = await github.Issue.Update("BrawlBox", "BrawlBoxIssues", i.Number, update);
                                }
                            }
                        }
                    }

                    if (!found)
                    {
                        NewIssue issue = new NewIssue(Title)
                        {
                            Body =
                                Description +
                                Environment.NewLine +
                                Environment.NewLine +
                                TagName +
                                Environment.NewLine +
                                ExceptionMessage +
                                Environment.NewLine +
                                StackTrace
                        };
                        Issue x = await github.Issue.Create("BrawlBox", "BrawlBoxIssues", issue);
                    }
                }
            }
            catch
            {
                MessageBox.Show("The application was unable to retrieve permission to send this issue.");
            }
        }
 public static IssueUpdate SetMilestone(this IssueUpdate update, Milestone milestone)
 {
     update.Milestone = milestone.Number;
     return(update);
 }
        public static async Task CreateIssue(
            string TagName,
            string ExceptionMessage,
            string StackTrace,
            string Title,
            string Description)
        {
            if (File.Exists(Updater.AppPath + "\\Canary\\Active") &&
                !Updater.currentRepo.Equals(Updater.mainRepo, StringComparison.OrdinalIgnoreCase))
            {
                MessageBox.Show(
                    "Issue reporter does not allow reporting issues from forks. Please contact the owner of the repository to report your issue.");
                return;
            }

            try
            {
                Issue        x      = null;
                Credentials  cr     = new Credentials(Encoding.Default.GetString(Program.RawData));
                GitHubClient github = new GitHubClient(new ProductHeaderValue("BrawlCrate"))
                {
                    Credentials = cr
                };
                IReadOnlyList <Issue> issues = null;
                if (!TagName.ToLower().Contains("canary"))
                {
                    IReadOnlyList <Release> releases;
                    try
                    {
                        releases = await github.Repository.Release.GetAll("soopercool101", "BrawlCrate");

                        // Remove all pre-release (Documentation) versions from the list
                        releases = releases.Where(r => !r.Prerelease).ToList();

                        issues = await github.Issue.GetAllForRepository("BrawlCrate", "BrawlCrateIssues");
                    }
                    catch (HttpRequestException)
                    {
                        MessageBox.Show("Unable to connect to the internet.");
                        return;
                    }

                    if (releases.Count > 0 && releases[0].TagName != TagName)
                    {
                        //This build's version tag does not match the latest release's tag on the repository.
                        //This issue may have been fixed by now. Tell the user to update to be allowed to submit reports.

                        DialogResult UpdateResult =
                            MessageBox.Show(
                                releases[0].Name +
                                " is available!\nYou cannot submit bug reports using an older version of the program.\nUpdate now?",
                                "An update is available", MessageBoxButtons.YesNo);
                        if (UpdateResult == DialogResult.Yes)
                        {
                            Task t = Updater.ForceDownloadStable("");
                            t.Wait();
                        }

                        return;
                    }
                }

                TagName += $" {Updater.platform}";
                bool found = false;
                if (issues != null && !string.IsNullOrEmpty(StackTrace))
                {
                    foreach (Issue i in issues.Where(i => i.State == ItemState.Open))
                    {
                        string desc = i.Body;
                        if (desc.Contains(StackTrace) &&
                            desc.Contains(ExceptionMessage))
                        {
                            found = true;
                            IssueUpdate update = i.ToUpdate();

                            update.Body =
                                Title +
                                Environment.NewLine +
                                Description +
                                Environment.NewLine +
                                Environment.NewLine +
                                TagName +
                                Environment.NewLine +
                                i.Body;

                            x = await github.Issue.Update("BrawlCrate", "BrawlCrateIssues", i.Number, update);
                        }
                    }
                }

                if (!found)
                {
                    NewIssue issue = new NewIssue(Title)
                    {
                        Body =
                            Description +
                            Environment.NewLine +
                            Environment.NewLine +
                            TagName +
                            Environment.NewLine +
                            "```" +
                            Environment.NewLine +
                            ExceptionMessage +
                            Environment.NewLine +
                            StackTrace +
                            Environment.NewLine +
                            "```"
                    };
                    x = await github.Issue.Create("BrawlCrate", "BrawlCrateIssues", issue);
                }

                if (x != null)
                {
                    if (MessageBox.Show(
                            $"Your issue can be found at {x.HtmlUrl}. Please add any clarification on the issue there.\n\nWould you like to open this webpage in your browser?",
                            "Issue Reported", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        Process issue = Process.Start(new ProcessStartInfo
                        {
                            FileName = x.HtmlUrl
                        });
                    }
                }
            }
            catch
            {
                MessageBox.Show("The application was unable to retrieve permission to send this issue.");
            }
        }
        public void UpdateIssue(IssueUpdate update, NetworkCredential credential,
            Action<string> stdout, Action<string> stderr)
        {
            var client = new WebClient();
            if (token == null)
            {
                System.Collections.Specialized.NameValueCollection data = new System.Collections.Specialized.NameValueCollection(1);
                data.Add("accountType", "GOOGLE");
                data.Add("Email", credential.UserName);
                data.Add("Passwd", credential.Password);
                data.Add("service", "code");
                data.Add("source", "opensource-gurtlereloaded-1");

                string[] result = ByteArrayToString(client.UploadValues("https://www.google.com/accounts/ClientLogin", data)).Split('\n');

                for (int i = 0; i < result.Length; i++)
                {
                    if (result[i].StartsWith("auth=", StringComparison.InvariantCultureIgnoreCase))
                    {
                        token = result[i];
                        break;
                    }
                }
            }

            var doc = new XmlDocument();
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
            doc.AppendChild(dec);
            XmlSchema schema = new XmlSchema();
            schema.Namespaces.Add("xmlns", "http://www.w3.org/2005/Atom");
            schema.Namespaces.Add("issues", "http://schemas.google.com/projecthosting/issues/2009");
            doc.Schemas.Add(schema);
            XmlElement entry = doc.CreateElement("entry", "http://www.w3.org/2005/Atom");
            doc.AppendChild(entry);
            XmlElement author = doc.CreateElement("author", "http://www.w3.org/2005/Atom");
            entry.AppendChild(author);
            XmlElement name = doc.CreateElement("name", "http://www.w3.org/2005/Atom");
            name.InnerText = "empty";
            author.AppendChild(name);
            if (update.Comment.Length > 0)
            {
                XmlElement content = doc.CreateElement("content", "http://www.w3.org/2005/Atom");
                XmlAttribute contentType = doc.CreateAttribute("type");
                contentType.InnerText = "html";
                content.Attributes.Append(contentType);
                content.InnerText = update.Comment;
                entry.AppendChild(content);
            }
            XmlElement updates = doc.CreateElement("issues", "updates", "http://schemas.google.com/projecthosting/issues/2009");
            entry.AppendChild(updates);
            XmlElement status = doc.CreateElement("issues", "status", "http://schemas.google.com/projecthosting/issues/2009");
            status.InnerText = update.Status;
            updates.AppendChild(status);

            client.Headers.Add("Content-Type", "application/atom+xml");
            client.Headers.Add("Authorization", "GoogleLogin " + token);

            client.UploadString(new Uri("https://code.google.com/feeds/issues/p/" + ProjectName + "/issues/"+ update.Issue.Id +"/comments/full"), doc.InnerXml);
        }
Exemple #27
0
 public override void UpdateIssue(Repository repository, int id, IssueUpdate update)
 {
     Issue.Title = update.Title;
     Issue.Body  = update.Body;
 }
Exemple #28
0
        public IssueResponse CreateIssue(IssueUpdate issue)
        {
            var json = JsonSerializer.Serialize(issue, new JsonSerializerOptions
            {
                IgnoreNullValues = true
            });
            var uri                 = UriHelper.BuildPath(BaseUri, RestPathConstants.Issue);
            var httpContent         = new StringContent(json, Encoding.UTF8, "application/json");
            var response            = Client.PostAsync(uri.ToString(), httpContent);
            var httpResponseMessage = response.Result;

            switch (httpResponseMessage.StatusCode)
            {
            case HttpStatusCode.OK:
            {
                var readAsStringAsync = httpResponseMessage.Content.ReadAsStringAsync();
                var result            = readAsStringAsync.Result;
                var createdIssue      = JsonSerializer.Deserialize <Issue>(result);
                return(new IssueResponse
                    {
                        Key = createdIssue.Key
                    });
            }

            case HttpStatusCode.BadRequest:
            {
                var readAsStringAsync = httpResponseMessage.Content.ReadAsStringAsync();
                var result            = readAsStringAsync.Result;
                return(JsonSerializer.Deserialize <IssueResponse>(result));
            }

            case HttpStatusCode.Accepted:
                break;

            case HttpStatusCode.Ambiguous:
                break;

            case HttpStatusCode.BadGateway:
                break;

            case HttpStatusCode.Conflict:
                break;

            case HttpStatusCode.Continue:
                break;

            case HttpStatusCode.Created:
            {
                var readAsStringAsync = httpResponseMessage.Content.ReadAsStringAsync();
                var result            = readAsStringAsync.Result;
                var createdIssue      = JsonSerializer.Deserialize <Issue>(result);
                return(new IssueResponse
                    {
                        Key = createdIssue.Key
                    });
            }

            case HttpStatusCode.ExpectationFailed:
                break;

            case HttpStatusCode.Forbidden:
                break;

            case HttpStatusCode.Found:
                break;

            case HttpStatusCode.GatewayTimeout:
                break;

            case HttpStatusCode.Gone:
                break;

            case HttpStatusCode.HttpVersionNotSupported:
                break;

            case HttpStatusCode.InternalServerError:
            {
                var readAsStringAsync = httpResponseMessage.Content.ReadAsStringAsync();
                var result            = readAsStringAsync.Result;
                return(JsonSerializer.Deserialize <IssueResponse>(result));
            }

            case HttpStatusCode.LengthRequired:
                break;

            case HttpStatusCode.MethodNotAllowed:
                break;

            case HttpStatusCode.Moved:
                break;

            case HttpStatusCode.NoContent:
                break;

            case HttpStatusCode.NonAuthoritativeInformation:
                break;

            case HttpStatusCode.NotAcceptable:
                break;

            case HttpStatusCode.NotFound:
                break;

            case HttpStatusCode.NotImplemented:
                break;

            case HttpStatusCode.NotModified:
                break;

            case HttpStatusCode.PartialContent:
                break;

            case HttpStatusCode.PaymentRequired:
                break;

            case HttpStatusCode.PreconditionFailed:
                break;

            case HttpStatusCode.ProxyAuthenticationRequired:
                break;

            case HttpStatusCode.RedirectKeepVerb:
                break;

            case HttpStatusCode.RedirectMethod:
                break;

            case HttpStatusCode.RequestedRangeNotSatisfiable:
                break;

            case HttpStatusCode.RequestEntityTooLarge:
                break;

            case HttpStatusCode.RequestTimeout:
                break;

            case HttpStatusCode.RequestUriTooLong:
                break;

            case HttpStatusCode.ResetContent:
                break;

            case HttpStatusCode.ServiceUnavailable:
                break;

            case HttpStatusCode.SwitchingProtocols:
                break;

            case HttpStatusCode.Unauthorized:
                return(new IssueResponse
                {
                    ErrorMessages = new List <string> {
                        "Unauthorized"
                    }
                });

            case HttpStatusCode.UnsupportedMediaType:
                break;

            case HttpStatusCode.Unused:
                break;

            case HttpStatusCode.UpgradeRequired:
                break;

            case HttpStatusCode.UseProxy:
                break;

            default:
                return(new IssueResponse
                {
                    ErrorMessages = new List <string> {
                        $"HttpStatusCode: {httpResponseMessage.StatusCode}"
                    }
                });
            }
            return(null);
        }
        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;
            }
        }
 public override void UpdateIssue(Repository repository, int id, IssueUpdate update)
 {
     Issue = new Issue(null, null, null, id, ItemState.Open, update.Title, update.Body, null, null, null, null, 0, null, null, DateTimeOffset.Now, null);
 }
Exemple #31
0
 public Task <Issue> Update(long repositoryId, int number, IssueUpdate issueUpdate)
 {
     throw new NotImplementedException();
 }
Exemple #32
0
 public async Task <Issue> UpdateIssue(long repositoryId, int issueNumber, IssueUpdate updatedIssueDetails, GitHubClient authorizedGitHubClient)
 {
     return(await _issueRepository.UpdateIssue(repositoryId, issueNumber, updatedIssueDetails,
                                               authorizedGitHubClient));
 }