Beispiel #1
0
        public ProcessIssue(Issue issue)
        {
            this.Issue = issue;

            var collection = new ObservableCollection<ProcessIssue>();
            collection.CollectionChanged += (sender, args) =>
            {
                switch (args.Action)
                {
                    case NotifyCollectionChangedAction.Add:
                        args.NewItems.OfType<ProcessIssue>()
                            .ToList()
                            .ForEach(i => i.Parent = this);
                        break;
                    case NotifyCollectionChangedAction.Remove:
                        args.NewItems.OfType<ProcessIssue>()
                            .ToList()
                            .ForEach(i => i.Parent = null);
                        break;
                    default:
                        break;
                }
            };

            Children = collection;
        }
Beispiel #2
0
		public async Task when_task_list_link_doesnt_exists_then_adds_it_automatically()
		{
			var github = new Mock<IGitHubClient>();
			var task = new Issue
			{
				Number = 1,
				Title = "Issue with story link",
				Body = "Story #2",
			};

			github.SetupGet(repository, task);
			github.SetupGet(repository, new Issue
			{
				Number = 2,
				Title = "Story"
			});

			var expectedLink = OctoHook.Properties.Strings.FormatTask(" ", "#" + task.Number, task.Title);
			var linker = new AutoTask(github.Object);

			await linker.ProcessAsync(new Octokit.Events.IssuesEvent
			{
				Action = IssuesEvent.IssueAction.Opened,
				Issue = task,
				Repository = repository,
				Sender = repository.Owner
			});

			github.Verify(x => x.Issue.Update(repository.Owner.Login, repository.Name, 2, It.Is<IssueUpdate>(u =>
				u.Body.Contains(expectedLink))));
		}
        public AddCommentViewModel()
        {
            _issue = GitHubApi.Issue;

            CloseIssueCommand = new RelayCommand(OnCloseIssue, p => CanCloseIssue());
            CommentCommand = new RelayCommand(OnCommentOnIssue, p => CanCommentOnIssue());
        }
Beispiel #4
0
		public async Task when_octohook_header_doesnt_exists_then_adds_it_automatically()
		{
			var github = new Mock<IGitHubClient>();
			var task = new Issue
			{
				Number = 1,
				Title = "Issue with story link",
				Body = "Story #2",
			};

			github.SetupGet(repository, task);
			github.SetupGet(repository, new Issue
			{
				Number = 2,
				Title = "Story"
			});

			var linker = new AutoTask(github.Object);

			await linker.ProcessAsync(new Octokit.Events.IssuesEvent
			{
				Action = IssuesEvent.IssueAction.Opened,
				Issue = task,
				Repository = repository,
				Sender = repository.Owner
			});

			github.Verify(x => x.Issue.Update(repository.Owner.Login, repository.Name, 2, It.Is<IssueUpdate>(u =>
				u.Body.Contains(AutoTask.header))));
		}
Beispiel #5
0
        public AddCommentViewModel()
        {
            _issue = GitHubApi.Issue;

            CloseIssueCommand = new RelayCommand(OnCloseIssue, p => CanCloseIssue());
            CommentCommand    = new RelayCommand(OnCommentOnIssue, p => CanCommentOnIssue());
        }
Beispiel #6
0
        public static void HandleIssue(Octokit.Issue issue, long repo)
        {
            HandleUser(issue.User);

            bool IsSame(Issue i)
            {
                return(i.Number == issue.Number && i.Repository == repo);
            }

            using (var db = new RFCContext()) {
                var existing = db.Issues.Where(IsSame).FirstOrDefault();
                if (existing != null)
                {
                    db.Entry(existing).CurrentValues.SetValues(issue.ToDBIssue(existing, repo));
                }
                else
                {
                    existing = new Issue();
                    issue.ToDBIssue(existing, repo);
                    db.Issues.Add(existing);
                }

                db.SaveChanges();
            }
        }
Beispiel #7
0
 public IssueDrop(Issue issue, IEnumerable<string> excludedLabels)
 {
     Number = issue.Number;
     Title = issue.Title;
     Url = issue.HtmlUrl;
     Labels = issue.Labels.Where(label => !label.MatchesAny(excludedLabels))
         .Select(label => label.Name).ToArray();
 }
        public void ShouldConvertEmptyIssueToModel()
        {
            var issue = new Octokit.Issue();

            var result = issue.ToModel();

            result.Should().NotBeNull();
        }
        public bool? ShowModal()
        {
            _issue = new Issue(null, null, _issue.Number, ItemState.Open, "new title", "new body", null, null, null, null, 1, null, null, DateTimeOffset.Now, null);

            var api = Factory.Get<GitHubApiBase>();
            api.Issue = _issue;

            return true;
        }
Beispiel #10
0
 protected override bool IssueFilter(Issue issue)
 {
     if (Filter == null)
         return base.IssueFilter(issue);
     if (Filter.IssueState == IssueState.Open)
         return base.IssueFilter(issue) && issue.State == ItemState.Open;
     if (Filter.IssueState == IssueState.Closed)
         return base.IssueFilter(issue) && issue.State == ItemState.Closed;
     return base.IssueFilter(issue);
 }
Beispiel #11
0
 public IssueEvent(int id, Uri url, User actor, User assignee, Label label, EventInfoState @event, string commitId, DateTimeOffset createdAt, Issue issue)
 {
     Id = id;
     Url = url;
     Actor = actor;
     Assignee = assignee;
     Label = label;
     Event = @event;
     CommitId = commitId;
     CreatedAt = createdAt;
     Issue = issue;
 }
        private void LoadAssigneesAndSetIssueAssignee(Issue issue)
        {
            LoadAssignees();

            if (GitHubApi.Repository != null)
            {
                if (issue != null && issue.Assignee != null)
                {
                    SetAssignee(issue.Assignee);
                }
            }
        }
        private string PredictLabel(Octokit.Issue issue)
        {
            var corefxIssue = new GitHubIssue
            {
                ID          = issue.Number.ToString(),
                Title       = issue.Title,
                Description = issue.Body
            };

            var predictedLabel = Predict(corefxIssue);

            return(predictedLabel);
        }
Beispiel #14
0
        private FullPrediction[] PredictLabels(Octokit.Issue issue)
        {
            var corefxIssue = new GitHubIssue
            {
                ID          = issue.Number.ToString(),
                Title       = issue.Title,
                Description = issue.Body
            };

            _fullPredictions = Predict(corefxIssue);

            return(_fullPredictions);
        }
        void ValidateNeedsLabels(Issue issue, ValidationErrors validationErrors, Repository repository)
        {
            var lastActivityOnIssue = issue.UpdatedAt; //todo: does this include comments?

            if (issue.Labels.Any(l => l.Name == "Type: Bug") && !issue.Labels.Any(l => l.Name.StartsWith("Needs:")))
            {
                if (lastActivityOnIssue < DateTime.UtcNow.AddDays(-3))
                {
                    validationErrors.Add(new ValidationError
                    {
                        Reason = "This bug doesn't seem to be triaged, use one of the `Needs: X` labels to remember what the next steps are",
                        Issue = issue,
                        Repository = repository
                    });
                }

                return;
            }

            if (issue.Labels.Any(l => l.Name == "Needs: Triage") && lastActivityOnIssue < DateTime.UtcNow.AddDays(-3))
            {
                validationErrors.Add(new ValidationError
                {
                    Reason = "Issue needs triage but hasn't been updated for 3 days",
                    Issue = issue,
                    Repository = repository
                });
            }

            if (issue.Labels.Any(l => l.Name == "Needs: Reproduction") && lastActivityOnIssue < DateTime.UtcNow.AddDays(-7))
            {
                validationErrors.Add(new ValidationError
                {
                    Reason = "Issue needs a repro but hasn't been touched in the last 7 days",
                    Issue = issue,
                    Repository = repository
                });
            }

            if (issue.Labels.Any(l => l.Name == "Needs: Scheduling") && lastActivityOnIssue < DateTime.UtcNow.AddMonths(-3))
            {
                validationErrors.Add(new ValidationError
                {
                    Reason = "Issue needs scheduling but hasn't been touched in the last 3 months",
                    Issue = issue,
                    Repository = repository
                });
            }
        }
Beispiel #16
0
    internal static GitHubIssueKey GetIssueKey(this Octokit.Issue issue)
    {
        var regex = new Regex(@"https://github.com/([\w\d-]+)/([\w\d-]+)/issues/\d+");
        var match = regex.Match(issue.HtmlUrl.ToString());

        if (!match.Success)
        {
            throw new Exception("Cannot parse GitHub issue URL");
        }

        return(new GitHubIssueKey(
                   match.Groups[1].Value,
                   match.Groups[2].Value,
                   issue.Number));
    }
        private async void LoadAssignees(Issue issue)
        {
            if (GitHubApi.Repository != null)
            {
                IReadOnlyList <User> assignees = await GitHubApi.GetAssignees(_repository);

                foreach (var assignee in assignees)
                {
                    Assignees.Add(assignee);
                }

                if (issue != null && issue.Assignee != null)
                {
                    SetAssignee(issue.Assignee);
                }
            }
        }
Beispiel #18
0
        internal IssueItemViewModel(Issue issue)
        {
            var isPullRequest = issue.PullRequest != null && issue.PullRequest.HtmlUrl != null;
            var s1 = issue.Url.AbsolutePath.Substring(issue.Url.AbsolutePath.IndexOf("/repos/", StringComparison.Ordinal) + 7);
            var repoId = new RepositoryIdentifier(s1.Substring(0, s1.IndexOf("/issues", StringComparison.Ordinal)));

            RepositoryFullName = repoId.Owner + "/" + repoId.Name;
            RepositoryName = repoId.Name;
            RepositoryOwner = repoId.Owner;
            IsPullRequest = isPullRequest;
            Title = issue.Title;
            Number = issue.Number;
            State = issue.State.ToString();
            Comments = issue.Comments;
            Assignee = issue.Assignee != null ? issue.Assignee.Login : "******";
            UpdatedAt = issue.UpdatedAt ?? DateTimeOffset.Now;
            GoToCommand = ReactiveCommand.Create();
        }
Beispiel #19
0
        PullRequestView GetNewPullRequestView(Octokit.Issue request)
        {
            var repositoryName = request.PullRequest.HtmlUrl.Segments[2].TrimEnd('/');
            var newRequest     = new PullRequestView()
            {
                RepoName   = repositoryName,
                Title      = request.Title,
                Id         = request.Number,
                Created    = request.CreatedAt,
                Updated    = request.UpdatedAt.GetValueOrDefault(),
                State      = request.State,
                Developer  = request.User.Login,
                JiraIssues = GetJiraIssues(request, repositoryName), //TODO: Get Commits, Comments, etc?
                Tag        = request
            };

            return(newRequest);
        }
Beispiel #20
0
        public static Issue ToDBIssue(this Octokit.Issue issue, Issue inIssue, long repo)
        {
            inIssue.Assignee      = issue.Assignee?.Id;
            inIssue.Body          = issue.Body;
            inIssue.ClosedAt      = issue.ClosedAt;
            inIssue.CreatedAt     = issue.CreatedAt;
            inIssue.IsPullRequest = issue.PullRequest != null;
            inIssue.Labels        = issue.Labels.Select(x => x.Name).ToList();
            inIssue.Locked        = issue.Locked;
            inIssue.Number        = issue.Number;
            inIssue.Open          = issue.State.Value == ItemState.Open;
            inIssue.Title         = issue.Title;
            inIssue.UpdatedAt     = issue.UpdatedAt;
            inIssue.User          = (int)(issue.User?.Id);
            inIssue.Repository    = repo;

            return(inIssue);
        }
Beispiel #21
0
        async Task <PullRequestView> UpdateCommits(Octokit.Issue request, PullRequestView pullRequest, string sha)
        {
            var commitTask = await Client.Repository.Commit.Get(_owner, pullRequest.RepoName, sha);

            if (null != commitTask)
            {
                pullRequest.Commits.Add(commitTask);

                pullRequest.HasDbUpgrade         = commitTask.Files.Any(f => f.Filename.Contains("AdvUpgrade"));
                pullRequest.HasBuildScriptChange = commitTask.Files.Any(f => f.Filename.Contains("build.ps1"));

                pullRequest.Files = commitTask.Files.Select(f => f.Filename).ToList();

                var advantagePatchBuilder = new PullRequestAssembyHelper(pullRequest, "rroberts");
                pullRequest.AssembliesChanged = advantagePatchBuilder.AssemblyFiles;
            }

            return(pullRequest);
        }
        // TODO add lambda to remove repetetive logic in this class
        // -> call and pass a lambda calls create, and if fails remake and call it again.

        public async Task <Octokit.Issue> GetIssue(string owner, string repo, int number)
        {
            if (_client == null)
            {
                _client = await _gitHubClientFactory.CreateAsync(_skipAzureKeyVault);
            }
            Octokit.Issue iop = null;
            try
            {
                iop = await _client.Issue.Get(owner, repo, number);
            }
            catch (Exception ex)
            {
                _logger.LogError($"ex was of type {ex.GetType()}, message: {ex.Message}");
                _client = await _gitHubClientFactory.CreateAsync(_skipAzureKeyVault);

                iop = await _client.Issue.Get(owner, repo, number);
            }
            return(iop);
        }
Beispiel #23
0
        async Task <PullRequestView> GetPullRequestDetails(Octokit.Issue request, PullRequestView pullRequest)
        {
            var pullRequestDetails = await Client.Repository.PullRequest.Get(_owner, pullRequest.RepoName, pullRequest.Id);

            pullRequest.Branch     = pullRequestDetails.Base.Ref;
            pullRequest.RepoBranch = BranchVersionHelper.Map.GetRepoBranch(pullRequest.Branch);
            if (null != pullRequest.RepoBranch)
            {
                pullRequest.Version = pullRequest.RepoBranch.Version;
            }
            pullRequest.Mergeable        = pullRequestDetails.Mergeable;
            pullRequest.Merged           = pullRequestDetails.Merged;
            pullRequest.ChangedFileCount = pullRequestDetails.ChangedFiles;
            pullRequest.State            = pullRequestDetails.State;
            pullRequest.CommitCount      = pullRequestDetails.Commits;
            pullRequest.JiraIssues       = GetJiraIssues(request, pullRequest.RepoName);

            pullRequest = await UpdateCommits(request, pullRequest, pullRequestDetails.Head.Sha);

            return(pullRequest);
        }
Beispiel #24
0
        IList <Atlassian.Jira.Issue> GetJiraIssues(Octokit.Issue request, string repoName)
        {
            var    jiraIssues   = new List <Atlassian.Jira.Issue>();
            string titleAndBody = String.Empty;

            if (request.Title.Contains("…"))
            {
                titleAndBody = request.Title.Replace("…", "");
            }
            else
            {
                titleAndBody = request.Title;
            }
            if (request.Body.Contains("…"))
            {
                titleAndBody += request.Body.Replace("…", "");
            }
            else
            {
                titleAndBody += request.Body;
            }
            var jiraIssueNumbers = GetJiraIssueNumbers(titleAndBody);

            foreach (var jiraIssueNumber in jiraIssueNumbers)
            {
                try
                {
                    var jiraIssue = JiraHelper.GetJiraIssueByKey(jiraIssueNumber);
                    if (null != jiraIssue)
                    {
                        jiraIssues.Add(jiraIssue);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception reading JIRA issue with key " + jiraIssueNumber + ": " + ex.ToString());
                }
            }
            return(jiraIssues);
        }
        /// <summary>
        /// Sets the issue to add/edit. If null, we are adding, if set, we edit
        /// </summary>
        /// <param name="issue">The issue.</param>
        public void SetIssue(Issue issue)
        {
            LoadAssignees(issue);

            if (issue == null)
            {
                return;
            }

            _issueNumber = issue.Number;
            Title        = issue.Title;
            Body         = issue.Body;
            Assignee     = issue.Assignee;
            if (issue.Labels != null)
            {
                foreach (var label in issue.Labels)
                {
                    AddLabel(label);
                }
            }
            SetMilestone(issue.Milestone);
        }
Beispiel #26
0
        public void when_processing_issue_other_links_then_updates_with_story_link_from_prefix()
        {
            var github = new Mock<IGitHubClient>(MockBehavior.Strict);
            var task = new Issue
            {
                Number = 1,
                Title = "[ui] Issue with story prefix",
                Body = "An issue with an existing issue #2 link",
                Labels = new[] { new Label { Name = "Task" } }
            };

            github.SetupGet(repository, task);
            github.SetupGet(repository, new Issue
            {
                Number = 2,
                Labels = new List<Label>()
            });
            github.SetupSearch(new Issue
            {
                Number = 3,
                Title = "[ui] Story"
            });

            var linker = new AutoLink(github.Object);
            var update = new IssueUpdate();
            var updated = linker.Process(new Octokit.Events.IssuesEvent
            {
                Action = IssuesEvent.IssueAction.Opened,
                Issue = task,
                Repository = repository,
                Sender = repository.Owner,
            }, update);

            Assert.True(updated);
            Assert.True(update.Body.Contains("#3"));
        }
Beispiel #27
0
        private IssueItemViewModel CreateItemViewModel(Issue issue)
        {
            var item = new IssueItemViewModel(issue);
            if (item.IsPullRequest)
            {
                item.GoToCommand.Subscribe(_ => {
                    var vm = this.CreateViewModel<PullRequestViewModel>();
                    vm.Init(item.RepositoryOwner, item.RepositoryName, item.Number, issue: issue);
                    vm.IssueUpdated.Subscribe(x => UpdateIssue(x));
                    NavigateTo(vm);
                });
            }
            else
            {
                item.GoToCommand.Subscribe(_ => {
                    var vm = this.CreateViewModel<IssueViewModel>();
                    vm.Init(item.RepositoryOwner, item.RepositoryName, item.Number, issue);
                    vm.IssueUpdated.Subscribe(x => UpdateIssue(x));
                    NavigateTo(vm);
                });
            }

            return item;
        }
        public override async void AddComment(Issue issue, string comment)
        {
            if (Repository == null)
                return;

            try
            {
                var newComment = await _github.Issue.Comment.Create(Repository.Repository.Owner.Login, Repository.Repository.Name, issue.Number, comment);

                // Append the current comment
                AppendComments(new[] { newComment });
            }
            catch ( Exception exception )
            {
                _log.Write(LogLevel.Error, "Failed to add comment to issue.", exception );
            }
        }
        public override async void CloseIssue(Issue issue, string comment)
        {
            if (!string.IsNullOrWhiteSpace(comment))
                AddComment(issue, comment);

            if (Repository == null)
                return;

            var update = new IssueUpdate();
            update.State = ItemState.Closed;
            try
            {
                var updatedIssue = await _github.Issue.Update(Repository.Repository.Owner.Login, Repository.Repository.Name, issue.Number, update);
                if (updatedIssue.State == ItemState.Closed)
                {
                    AllIssues.Remove(issue);
                    Issue = null;
                    IssueMarkdown = string.Empty;
                }
            }
            catch ( Exception exception )
            {
                _log.Write(LogLevel.Error, "Failed to update issue.", exception );
            }
        }
 static void CheckForValidLabels(Issue issue)
 {
     var count = issue.Labels.Count(l =>
         l.Name == "Bug" ||
         l.Name == "Internal refactoring" ||
         l.Name == "Feature" ||
         l.Name == "Improvement");
     if (count != 1)
     {
         var message = string.Format("Bad Issue {0} expected to find a single label with either 'Bug', 'Internal refactoring', 'Improvement' or 'Feature'.", issue.HtmlUrl);
         throw new Exception(message);
     }
 }
        protected override async void GetComments(Issue issue)
        {
            if (issue == null)
                return;

            IssueMarkdown = issue.Body;

            if (issue.Comments == 0 || Repository == null)
                return;

            try
            {
                IReadOnlyList<IssueComment> comments = await _github.Issue.Comment.GetAllForIssue(Repository.Repository.Owner.Login, Repository.Repository.Name, issue.Number);
                AppendComments(comments);
            }
            catch ( Exception exception )
            {
                _log.Write( LogLevel.Error, "Failed to fetch comments for issue.", exception );
            }
        }
 protected override void GetComments(Issue issue)
 {
     IssueMarkdown += "\r\nComment";
 }
Beispiel #33
0
 public PullRequestViewModel Init(string repositoryOwner, string repositoryName, int id, PullRequest pullRequest = null, Issue issue = null)
 {
     RepositoryOwner = repositoryOwner;
     RepositoryName = repositoryName;
     Id = id;
     PullRequest = pullRequest;
     Issue = issue;
     return this;
 }
 public abstract void AddComment(Issue issue, string comment);
 public override void SaveIssue(Repository repository, NewIssue newIssue)
 {
     var issue = new Issue(null, null, 69, ItemState.Open, newIssue.Title, newIssue.Body, null, null, null, null, 0, null, null, DateTimeOffset.Now, null);
     AllIssues.Add(issue);
     Issue = issue;
 }
 public override void CloseIssue(Issue issue, string comment)
 {
     AddComment(issue, comment);
     Issue = new Issue(null, null, Issue.Number, ItemState.Closed, Issue.Title, Issue.Body, null, null, null, null, 1, null, null, Issue.CreatedAt, null);
     //issue.State = ItemState.Closed;
 }
Beispiel #37
0
            /// <summary>
            /// Export PullRequest To XML
            /// </summary>
            /// <param name="items"></param>
            public async void ExportPullRequestToXML(IReadOnlyList <TItem> items)
            {
                #region Pull Requests with More than One Issues
                var         project = "joda-time";
                var         path    = "JodaOrg";
                XmlDocument xmlDoc  = new XmlDocument();
                xmlDoc.Load("C:\\PhD\\Workbrench\\GitHub_NeturalNetworks\\Datasets\\PullRequests" + project + ".xml");
                XmlNode rootNode = xmlDoc["PullRequests"];

                foreach (var item in items)
                {
                    Octokit.Issue m = item as Octokit.Issue;

                    /*Checked it is not robot,check issue is mentioned in pullrequest*/
                    if (m != null)
                    {
                        XmlNode    PullRequestNode = xmlDoc.CreateElement("PullRequest");
                        XmlElement elemID          = xmlDoc.CreateElement("IssueID");
                        elemID.InnerText = m.Number.ToString();
                        PullRequestNode.AppendChild(elemID);

                        XmlElement elemRepoID = xmlDoc.CreateElement("RepoID");
                        elemRepoID.InnerText = project;
                        PullRequestNode.AppendChild(elemRepoID);

                        XmlElement elemFixedByID = xmlDoc.CreateElement("FixedByID");
                        elemFixedByID.InnerText = m.User.Login;
                        PullRequestNode.AppendChild(elemFixedByID);

                        XmlElement elemTitle = xmlDoc.CreateElement("Title");
                        elemTitle.InnerText = RemoveSpecialCharacters(m.Title?.ToString());
                        PullRequestNode.AppendChild(elemTitle);

                        XmlElement elemDescription = xmlDoc.CreateElement("Description");
                        //elemDescription.InnerText = RemoveSpecialCharacters(m.Body?.ToString());
                        elemDescription.InnerText = m.Body?.ToString();
                        PullRequestNode.AppendChild(elemDescription);

                        XmlElement elemOpenedAt = xmlDoc.CreateElement("CreatedDate");
                        elemOpenedAt.InnerText = m.CreatedAt.ToString("dd/MM/yyyy");
                        PullRequestNode.AppendChild(elemOpenedAt);

                        XmlElement elemClosedAt = xmlDoc.CreateElement("ClosedDate");
                        elemClosedAt.InnerText = m.ClosedAt?.ToString("dd/MM/yyyy");
                        PullRequestNode.AppendChild(elemClosedAt);

                        XmlElement pullrequestLabels = xmlDoc.CreateElement("PullRequestLabels");
                        foreach (var _label in m.Labels)
                        {
                            XmlElement label = xmlDoc.CreateElement("PullRequestLabel");
                            label.InnerText = _label.Name;
                            pullrequestLabels.AppendChild(label);
                        }
                        PullRequestNode.AppendChild(pullrequestLabels);

                        var issues = HasIssueNo(m.Body?.ToString());
                        if (issues != null && issues.Count() > 0)
                        {
                            /*Get Issue List*/
                            XmlElement IssuesNodes = xmlDoc.CreateElement("Issues");
                            foreach (var issue in issues)
                            {
                                var _tempissue = MainForm.GetIssue(path, project, Convert.ToInt32(issue.Replace("#", "")));
                                if (!_tempissue.IsCompleted)
                                {
                                    var tempIssue = await _tempissue.ConfigureAwait(false);

                                    Octokit.Issue _issue = tempIssue as Octokit.Issue;
                                    /*Get Only Class File (*.cs)*/
                                    if (_issue != null)
                                    {
                                        XmlElement IssuesNode = xmlDoc.CreateElement("Issue");
                                        if (_issue.Labels != null && _issue.Labels.Count() > 0)
                                        {
                                            XmlElement issue_RepoID = xmlDoc.CreateElement("RepoID");
                                            issue_RepoID.InnerText = project;
                                            IssuesNode.AppendChild(issue_RepoID);

                                            XmlElement parent_IssueID = xmlDoc.CreateElement("PullRequestID");
                                            parent_IssueID.InnerText = m.Number.ToString();
                                            IssuesNode.AppendChild(parent_IssueID);

                                            XmlElement issueID = xmlDoc.CreateElement("IssueID");
                                            issueID.InnerText = _issue.Number.ToString();
                                            IssuesNode.AppendChild(issueID);

                                            XmlElement issueTitle = xmlDoc.CreateElement("Title");
                                            issueTitle.InnerText = _issue.Title?.ToString();
                                            IssuesNode.AppendChild(issueTitle);

                                            if (!string.IsNullOrEmpty(_issue.Body))
                                            {
                                                XmlElement issueDescription = xmlDoc.CreateElement("Description");
                                                issueDescription.InnerText = _issue.Body;

                                                var codeblockcount = Regex.Matches(issueDescription.InnerText, "```").Count;
                                                if (codeblockcount > 1)
                                                {
                                                    /*Remove Code from Description*/
                                                    var noofcodeblock = codeblockcount / 2;
                                                    for (int i = 0; i <= noofcodeblock; i++)
                                                    {
                                                        var _valueD = issueDescription.InnerText;

                                                        int startIndex_D = _valueD.IndexOf("```");
                                                        int endIndex_D   = _valueD.LastIndexOf("```");
                                                        int length_D     = endIndex_D - startIndex_D + 1;
                                                        if (startIndex_D > -1 && endIndex_D > -1)
                                                        {
                                                            _valueD = _valueD.Remove(startIndex_D, length_D);
                                                            issueDescription.InnerText = _valueD;
                                                        }
                                                    }

                                                    XmlElement issueCode = xmlDoc.CreateElement("Code");
                                                    string     tempdata  = _issue.Body?.ToString();
                                                    /*Extract Code -- if csharp exist*/
                                                    for (int i = 0; i <= noofcodeblock; i++)
                                                    {
                                                        /*Extract Code from Description*/
                                                        var _valueDCode      = tempdata;
                                                        int startIndex_DCode = _valueDCode.IndexOf("```");
                                                        int endIndex_DCode   = _valueDCode.LastIndexOf("```");
                                                        int length_DCode     = endIndex_DCode - startIndex_DCode + 1;
                                                        if (startIndex_DCode > -1 && endIndex_DCode > -1)
                                                        {
                                                            _valueDCode = _valueDCode.Substring(startIndex_DCode, length_DCode);
                                                            if (_valueDCode.Contains("csharp") || _valueDCode.Contains("c#") || _valueDCode.Contains("cs") || _valueDCode.Contains("java"))
                                                            {
                                                                issueCode.InnerText = issueCode.InnerText + _valueDCode;
                                                            }
                                                            tempdata = tempdata.Remove(startIndex_DCode, length_DCode);
                                                        }
                                                    }
                                                    if (!string.IsNullOrEmpty(issueCode.InnerText))
                                                    {
                                                        issueCode.InnerText = issueCode.InnerText.Replace("```", string.Empty);
                                                        issueCode.InnerText = issueCode.InnerText.Replace("&gt;", ">");
                                                        issueCode.InnerText = issueCode.InnerText.Replace("&lt;", "<");
                                                        IssuesNode.AppendChild(issueCode);
                                                    }
                                                }

                                                issueDescription.InnerText = Regex.Replace(issueDescription.InnerText, @"http[^\s]+", "");          /*Removed URL*/
                                                issueDescription.InnerText = Regex.Replace(issueDescription.InnerText, @"(?<!\r)\n", String.Empty); /*Removed line Break*/
                                                //issueDescription.InnerText = RemoveSpecialCharacters(issueDescription.InnerText
                                                issueDescription.InnerText = issueDescription.InnerText;
                                                IssuesNode.AppendChild(issueDescription);
                                            }

                                            XmlElement issueOpenedAt = xmlDoc.CreateElement("CreatedDate");
                                            issueOpenedAt.InnerText = _issue.CreatedAt.ToString("dd/MM/yyyy");
                                            IssuesNode.AppendChild(issueOpenedAt);

                                            XmlElement issueClosedAt = xmlDoc.CreateElement("ClosedDate");
                                            issueClosedAt.InnerText = _issue.ClosedAt?.ToString("dd/MM/yyyy");
                                            IssuesNode.AppendChild(issueClosedAt);

                                            XmlElement issueLabels = xmlDoc.CreateElement("Labels");
                                            foreach (var _label in _issue.Labels)
                                            {
                                                XmlElement label = xmlDoc.CreateElement("Label");
                                                label.InnerText = _label.Name;
                                                issueLabels.AppendChild(label);
                                            }
                                            IssuesNode.AppendChild(issueLabels);

                                            /*Add to Parent Issue*/
                                            IssuesNodes.AppendChild(IssuesNode);
                                        }
                                    }
                                }
                            }
                            PullRequestNode.AppendChild(IssuesNodes);
                            rootNode.AppendChild(PullRequestNode);

                            ///*Get File List*/
                            //var files = MainForm.GetPullRequestFiles(path, project, Convert.ToInt32(m.Number));
                            //if (!files.IsCompleted)
                            //{
                            //    var tempFiles = await files.ConfigureAwait(false);
                            //    IReadOnlyList<PullRequestFile> _Files = tempFiles as IReadOnlyList<PullRequestFile>;
                            //    /*Get Only Class File (*.cs)*/
                            //    if (_Files != null && _Files.Count() > 0 && _Files.Where(x => x.FileName.EndsWith(".cs")).Any())
                            //    {
                            //        _Files = _Files.Where(x => x.FileName.EndsWith(".cs")).ToList();
                            //        XmlElement FilesNode = xmlDoc.CreateElement("Files");
                            //        XmlElement parent_FileID = xmlDoc.CreateElement("PullRequestID");
                            //        parent_FileID.InnerText = m.Number.ToString();

                            //        XmlElement File_RepoID = xmlDoc.CreateElement("RepoID");
                            //        File_RepoID.InnerText = project;
                            //        FilesNode.AppendChild(File_RepoID);

                            //        FilesNode.AppendChild(parent_FileID);

                            //        foreach (var file in _Files)
                            //        {
                            //            if (file != null)
                            //            {
                            //                XmlElement File = xmlDoc.CreateElement("File");
                            //                File.InnerText = file.FileName;
                            //                FilesNode.AppendChild(File);
                            //            }
                            //        }
                            //        PullRequestNode.AppendChild(FilesNode);
                            //        rootNode.AppendChild(PullRequestNode);
                            //    }

                            //}
                        }
                    }
                }
                xmlDoc.Save("C:\\PhD\\Workbrench\\GitHub_NeturalNetworks\\Datasets\\PullRequests" + project + ".xml");
                #endregion Pull Requests with More than One Issues
            }
Beispiel #38
0
 /// <summary>
 /// Sets the issue to add/edit. If null, we are adding, if set, we edit
 /// </summary>
 /// <param name="issue">The issue.</param>
 public void SetIssue(Octokit.Issue issue)
 {
     _gitHubViewModel.SetIssue(issue);
 }
 /// <summary>
 /// Sets the issue to add/edit
 /// </summary>
 /// <param name="issue">The issue.</param>
 public void SetIssue(Issue issue)
 {
     _issue = issue ?? new Issue();
 }
Beispiel #40
0
 public Issue(Octokit.Issue issue) : base(issue.Title, issue.HtmlUrl)
 {
     AssignedTo = issue.Assignee?.Login;
     Milestone  = issue.Milestone?.Title;
 }
Beispiel #41
0
 public IssueEvent(int id, string nodeId, string url, User actor, User assignee, Label label, EventInfoState @event, string commitId, DateTimeOffset createdAt, Issue issue, string commitUrl)
 {
     Id        = id;
     NodeId    = nodeId;
     Url       = url;
     Actor     = actor;
     Assignee  = assignee;
     Label     = label;
     Event     = @event;
     CommitId  = commitId;
     CreatedAt = createdAt;
     Issue     = issue;
     CommitUrl = commitUrl;
 }
 public abstract void CloseIssue(Issue issue, string comment);
 public override void GetIssues()
 {
     var issue = new Issue(null, null, 1, ItemState.Open, "title", "##body##",
         new User("https://avatars.githubusercontent.com/u/493828?v=1", null, null, 1, null, DateTimeOffset.Now,
             1, "*****@*****.**", 1, 1, true, null, 1,
             1, null, "user", "name", 1, null, 0, 0, 0, null, false), null, null, null, 1, null, null,
         DateTimeOffset.Now, null);
     AllIssues.Add(issue);
     Issue = issue;
     IssueMarkdown = issue.Body;
 }
 protected abstract void GetComments(Issue issue);
 public override void UpdateIssue(Repository repository, int id, IssueUpdate update)
 {
     Issue = new Issue(null, null, id, ItemState.Open, update.Title, update.Body, null, null, null, null, 0, null, null, DateTimeOffset.Now, null );
 }
        public void SetUp()
        {
            var cache = new Mock<ICache>().Object;
            _moq = new Mock<GitHubApiBase>(cache);
            _api = _moq.Object;

            _label = new Label(null, "One", "");

            _milestone = new Milestone(null, 1, ItemState.All, "1.0", "", null, 1, 1, DateTimeOffset.Now, null, null);

            _issue = new Issue(null, null, null, 1, ItemState.Open, "Title one", "Body one", null, new List<Label>(new[] {_label}),
                null, _milestone, 1, null, null, DateTimeOffset.Now, null);
            _api.AllIssues.Add(_issue);

            var issue2 = new Issue(null, null, null, 2, ItemState.Open, "Two", "Two", null, new List<Label>(),
                null, new Milestone(null, 2, ItemState.All, "2.0", "", null, 1, 1, DateTimeOffset.Now, null, null), 1, null, null, DateTimeOffset.Now, null);
            _api.AllIssues.Add(issue2);

            var issue3 = new Issue(null, null, null, 3, ItemState.Open, "Three", "Three", null, new List<Label>(),
                null, null, 1, null, null, DateTimeOffset.Now, null);
            _api.AllIssues.Add(issue3);
        }
 public override void AddComment(Issue issue, string comment)
 {
     IssueMarkdown += comment;
 }
        private void CheckForValidLabels(Issue issue)
        {
            var count = this.configuration.IssueLabelsInclude.Sum(issueLabel => issue.Labels.Count(l => l.Name.ToUpperInvariant() == issueLabel.ToUpperInvariant()));

            if (count != 1)
            {
                var allIssueLabels = this.configuration.IssueLabelsInclude.Union(this.configuration.IssueLabelsExclude).ToList();
                var allIssuesExceptLast = allIssueLabels.Take(allIssueLabels.Count - 1);
                var lastLabel = allIssueLabels.Last();

                var allIssuesExceptLastString = string.Join(", ", allIssuesExceptLast);

                var message = string.Format(CultureInfo.InvariantCulture, "Bad Issue {0} expected to find a single label with either {1} or {2}.", issue.HtmlUrl, allIssuesExceptLastString, lastLabel);
                throw new InvalidOperationException(message);
            }
        }
Beispiel #49
0
        private async Task UpdateIssueLabelsAsync(PortingInfo ruleToPort, Issue existingIssue)
        {
            var existingLabelNames = new Collection<string>(existingIssue.Labels.Select(label => label.Name).ToList());

            var labelNamesToAdd = new Collection<string>();
            var labelNamesToRemove = new Collection<string>();

            AddLabel(FxCopPortLabel, labelNamesToAdd, existingLabelNames);

            if (ruleToPort.Soon)
            {
                AddLabel(UrgencySoonLabel, labelNamesToAdd, existingLabelNames);
            }
            else
            {
                RemoveLabel(UrgencySoonLabel, labelNamesToRemove, existingLabelNames);
            }

            switch (ruleToPort.Disposition)
            {
                case Disposition.NeedsReview:
                    AddLabel(NeedsReviewLabel, labelNamesToAdd, existingLabelNames);
                    RemoveLabel(CutLabel, labelNamesToRemove, existingLabelNames);
                    RemoveLabel(PortedLabel, labelNamesToRemove, existingLabelNames);
                    break;

                case Disposition.Port:
                    RemoveLabel(NeedsReviewLabel, labelNamesToRemove, existingLabelNames);
                    RemoveLabel(CutLabel, labelNamesToRemove, existingLabelNames);
                    RemoveLabel(PortedLabel, labelNamesToRemove, existingLabelNames);
                    break;

                case Disposition.Cut:
                    AddLabel(CutLabel, labelNamesToAdd, existingLabelNames);
                    RemoveLabel(NeedsReviewLabel, labelNamesToRemove, existingLabelNames);
                    RemoveLabel(PortedLabel, labelNamesToRemove, existingLabelNames);
                    break;

                case Disposition.Ported:
                    AddLabel(PortedLabel, labelNamesToAdd, existingLabelNames);
                    RemoveLabel(CutLabel, labelNamesToRemove, existingLabelNames);
                    RemoveLabel(NeedsReviewLabel, labelNamesToRemove, existingLabelNames);
                    break;
            }

            RemoveAreaLabels(existingLabelNames, labelNamesToRemove);
            AddAreaLabel(ruleToPort, labelNamesToAdd);

            if (_options.DryRun)
            {
                _log.Info(Resources.InfoDryRunLabelsNotUpdated);
            }
            else
            {
                if (labelNamesToAdd.Any())
                {
                    await _issuesLabelsClient.AddToIssue(
                        _options.RepoOwner,
                        _options.RepoName,
                        existingIssue.Number,
                        labelNamesToAdd.ToArray());
                }

                // Take care not to remove any labels we've just added.
                //
                // For some reason the "Remove" API doesn't take an array.
                foreach (string labelName in labelNamesToRemove.Except(labelNamesToAdd))
                {
                    await _issuesLabelsClient.RemoveFromIssue(
                        _options.RepoOwner,
                        _options.RepoName,
                        existingIssue.Number,
                        labelName);
                }
            }
        }
Beispiel #50
0
        private async Task ProcessBuildNotificationsAsync(Build build)
        {
            const string fullBranchPrefix = "refs/heads/";

            foreach (var monitor in _options.Value.Monitor.Builds)
            {
                if (!string.Equals(build.Project.Name, monitor.Project, StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                if (!string.Equals(monitor.DefinitionPath, $"{build.Definition.Path}\\{build.Definition.Name}", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                if (monitor.Branches.All(mb => !string.Equals($"{fullBranchPrefix}{mb}",
                                                              build.SourceBranch,
                                                              StringComparison.OrdinalIgnoreCase)))
                {
                    continue;
                }

                if (monitor.Tags != null && monitor.Tags.Any() && !(monitor.Tags.Intersect(build.Tags).Any()))
                {
                    // We should only skip processing if tags were specified in the monitor, and none of those tags were found in the build
                    continue;
                }

                string prettyBranch = build.SourceBranch;
                if (prettyBranch.StartsWith(fullBranchPrefix))
                {
                    prettyBranch = prettyBranch.Substring(fullBranchPrefix.Length);
                }

                string prettyTags = (monitor.Tags != null && monitor.Tags.Any()) ? $"{string.Join(", ", build.Tags)}" : "";

                _logger.LogInformation(
                    "Build '{buildNumber}' in project '{projectName}' with definition '{definitionPath}', tags '{prettyTags}', and branch '{branch}' matches monitoring criteria, sending notification",
                    build.BuildNumber,
                    build.Project.Name,
                    build.Definition.Path,
                    prettyTags,
                    build.SourceBranch);

                _logger.LogInformation("Fetching timeline messages...");
                string timelineMessage = await BuildTimelineMessage(build);

                _logger.LogInformation("Fetching changes messages...");
                string changesMessage = await BuildChangesMessage(build);

                BuildMonitorOptions.IssuesOptions repo = _options.Value.Issues.SingleOrDefault(i => string.Equals(monitor.IssuesId, i.Id, StringComparison.OrdinalIgnoreCase));

                if (repo != null)
                {
                    IGitHubClient github = await _gitHubApplicationClientFactory.CreateGitHubClientAsync(repo.Owner, repo.Name);

                    DateTimeOffset?finishTime = DateTimeOffset.TryParse(build.FinishTime, out var parsedFinishTime) ?parsedFinishTime: (DateTimeOffset?)null;
                    DateTimeOffset?startTime  = DateTimeOffset.TryParse(build.StartTime, out var parsedStartTime) ? parsedStartTime:(DateTimeOffset?)null;

                    string timeString     = "";
                    string durationString = "";
                    if (finishTime.HasValue)
                    {
                        timeString = finishTime.Value.ToString("R");
                        if (startTime.HasValue)
                        {
                            durationString = ((int)(finishTime.Value - startTime.Value).TotalMinutes) + " minutes";
                        }
                    }

                    string icon = build.Result == "failed" ? ":x:" : ":warning:";

                    string body             = @$ "Build [#{build.BuildNumber}]({build.Links.Web.Href}) {build.Result}

## {icon} : {build.Project.Name} / {build.Definition.Name} {build.Result}

### Summary
**Finished** - {timeString}
**Duration** - {durationString}
**Requested for** - {build.RequestedFor.DisplayName}
**Reason** - {build.Reason}

### Details

{timelineMessage}

### Changes

{changesMessage}
";
                    string issueTitlePrefix = $"Build failed: {build.Definition.Name}/{prettyBranch} {prettyTags}";

                    if (repo.UpdateExisting)
                    {
                        // There is no way to get the username of our bot directly from the GithubApp with the C# api.
                        // Issue opened in Octokit: https://github.com/octokit/octokit.net/issues/2335
                        // We do, however, have access to the HtmlUrl, which ends with the name of the bot.
                        // Additionally, when the bot opens issues, the username used ends with [bot], which isn't strictly
                        // part of the name anywhere else. So, to get the correct creator name, get the HtmlUrl, grab
                        // the bot's name from it, and append [bot] to that string.
                        var    githubAppClient = _gitHubApplicationClientFactory.CreateGitHubAppClient();
                        string creator         = (await githubAppClient.GitHubApps.GetCurrent()).HtmlUrl.Split("/").Last();

                        RepositoryIssueRequest issueRequest = new RepositoryIssueRequest {
                            Creator       = $"{creator}[bot]",
                            State         = ItemStateFilter.Open,
                            SortProperty  = IssueSort.Created,
                            SortDirection = SortDirection.Descending
                        };

                        foreach (string label in repo.Labels.OrEmpty())
                        {
                            issueRequest.Labels.Add(label);
                        }

                        foreach (string label in monitor.Labels.OrEmpty())
                        {
                            issueRequest.Labels.Add(label);
                        }

                        List <Issue> matchingIssues = (await github.Issue.GetAllForRepository(repo.Owner, repo.Name, issueRequest)).ToList();
                        Issue        matchingIssue  = matchingIssues.FirstOrDefault(i => i.Title.StartsWith(issueTitlePrefix));

                        if (matchingIssue != null)
                        {
                            _logger.LogInformation("Found matching issue {issueNumber} in {owner}/{repo}. Will attempt to add a new comment.", matchingIssue.Number, repo.Owner, repo.Name);
                            // Add a new comment to the issue with the body
                            IssueComment newComment = await github.Issue.Comment.Create(repo.Owner, repo.Name, matchingIssue.Number, body);

                            _logger.LogInformation("Logged comment in {owner}/{repo}#{issueNumber} for build failure", repo.Owner, repo.Name, matchingIssue.Number);

                            return;
                        }
                        else
                        {
                            _logger.LogInformation("Matching issues for {issueTitlePrefix} not found. Creating a new issue.", issueTitlePrefix);
                        }
                    }

                    // Create new issue if repo.UpdateExisting is false or there were no matching issues
                    var newIssue =
                        new NewIssue($"{issueTitlePrefix} #{build.BuildNumber}")
                    {
                        Body = body,
                    };

                    if (!string.IsNullOrEmpty(monitor.Assignee))
                    {
                        newIssue.Assignees.Add(monitor.Assignee);
                    }

                    foreach (string label in repo.Labels.OrEmpty())
                    {
                        newIssue.Labels.Add(label);
                    }

                    foreach (string label in monitor.Labels.OrEmpty())
                    {
                        newIssue.Labels.Add(label);
                    }

                    Issue issue = await github.Issue.Create(repo.Owner, repo.Name, newIssue);

                    _logger.LogInformation("Logged issue {owner}/{repo}#{issueNumber} for build failure", repo.Owner, repo.Name, issue.Number);
                }