예제 #1
0
        protected override IEnumerable <Notifications.INotification> CreateNotifications(IVssRequestContext requestContext, object notificationEventArgs, int maxLines)
        {
            var repositoryService = requestContext.GetService <ITeamFoundationGitRepositoryService>();
            var identityService   = requestContext.GetService <ITeamFoundationIdentityService>();
            var commonService     = requestContext.GetService <CommonStructureService>();
            var locationService   = requestContext.GetService <ILocationService>();

            string baseUrl = String.Format("{0}/{1}/",
                                           locationService.GetAccessMapping(requestContext, "PublicAccessMapping").AccessPoint,
                                           requestContext.ServiceHost.Name);

            var gitNotification = notificationEventArgs as GitNotification;

            Notifications.RepositoryNotification notification = null;

            if (gitNotification is RepositoryCreatedNotification)
            {
                var ev       = notificationEventArgs as RepositoryCreatedNotification;
                var identity = identityService.ReadIdentity(requestContext, IdentitySearchFactor.Identifier, ev.Creator.Identifier);

                notification             = new Notifications.RepositoryCreatedNotification();
                notification.UniqueName  = identity.UniqueName;
                notification.DisplayName = identity.DisplayName;
                notification.TeamNames   = GetUserTeamsByProjectUri(requestContext, gitNotification.TeamProjectUri, identity.Descriptor);
                using (ITfsGitRepository repository = repositoryService.FindRepositoryById(requestContext, gitNotification.RepositoryId))
                {
                    notification.RepoUri  = repository.GetRepositoryUri();
                    notification.RepoName = repository.Name;
                }
            }
            else if (gitNotification is RepositoryRenamedNotification)
            {
                notification          = new Notifications.RepositoryRenamedNotification();
                notification.RepoName = gitNotification.RepositoryName;
                using (ITfsGitRepository repository = repositoryService.FindRepositoryById(requestContext, gitNotification.RepositoryId))
                {
                    notification.RepoUri  = repository.GetRepositoryUri();
                    notification.RepoName = repository.Name;
                }
                notification.TeamNames = Enumerable.Empty <string>();
            }
            else if (gitNotification is RepositoryDeletedNotification)
            {
                var repoInfo = repositoryService
                               .QueryDeletedRepositories(requestContext, gitNotification.TeamProjectUri)
                               .Single(r => r.RepositoryId == gitNotification.RepositoryId);
                var identity = identityService.ReadIdentities(requestContext, new[] { repoInfo.DeletedBy }).First();
                notification             = new Notifications.RepositoryDeletedNotification();
                notification.UniqueName  = identity.UniqueName;
                notification.DisplayName = identity.DisplayName;
                notification.TeamNames   = GetUserTeamsByProjectUri(requestContext, gitNotification.TeamProjectUri, identity.Descriptor);
                notification.RepoName    = repoInfo.Name;
            }

            notification.TeamProjectCollection = requestContext.ServiceHost.Name;
            notification.ProjectName           = commonService.GetProject(requestContext, gitNotification.TeamProjectUri).Name;
            notification.ProjectUrl            = baseUrl + notification.ProjectName;

            yield return(notification);
        }
예제 #2
0
        private static CommitRow CreateCommitRow(IVssRequestContext requestContext, ITeamFoundationGitCommitService commitService,
                                                 ITfsGitRepository repository, TfsGitCommit gitCommit, CommitRowType rowType, PushNotification pushNotification, Dictionary <Sha1Id, List <GitRef> > refLookup)
        {
            var    commitManifest = commitService.GetCommitManifest(requestContext, repository, gitCommit.ObjectId);
            string repoUri        = repository.GetRepositoryUri();

            var commitRow = new CommitRow()
            {
                CommitId     = gitCommit.ObjectId,
                Type         = rowType,
                CommitUri    = repoUri + "/commit/" + gitCommit.ObjectId.ToHexString(),
                AuthorTime   = gitCommit.GetAuthor().LocalTime,
                Author       = gitCommit.GetAuthor().NameAndEmail,
                AuthorName   = gitCommit.GetAuthor().Name,
                AuthorEmail  = gitCommit.GetAuthor().Email,
                Comment      = gitCommit.GetComment(),
                ChangeCounts = commitManifest.ChangeCounts
            };
            List <GitRef> refs;

            refLookup.TryGetValue(gitCommit.ObjectId, out refs);
            commitRow.Refs = refs;

            return(commitRow);
        }
예제 #3
0
        public static bool IsForceRequired(this PushNotification pushNotification, IVssRequestContext requestContext, ITfsGitRepository repository)
        {
            foreach (var refUpdateResult in pushNotification.RefUpdateResults.Where(r => r.Succeeded))
            {
                // Don't bother with new or deleted refs
                if (refUpdateResult.OldObjectId.IsEmpty || refUpdateResult.NewObjectId.IsEmpty) continue;

                TfsGitObject gitObject = repository.LookupObject(refUpdateResult.NewObjectId);
                if (gitObject.ObjectType != GitObjectType.Commit) continue;
                TfsGitCommit gitCommit = (TfsGitCommit)gitObject;

                if (!gitCommit.IsDescendantOf(requestContext, refUpdateResult.OldObjectId))
                    return true;
            }

            return false;
        }
예제 #4
0
        protected override IEnumerable <Notifications.INotification> CreateNotifications(IVssRequestContext requestContext, ReviewerVoteNotification ev, int maxLines)
        {
            var repositoryService = requestContext.GetService <ITeamFoundationGitRepositoryService>();
            var identityService   = requestContext.GetService <ITeamFoundationIdentityService>();
            var commonService     = requestContext.GetService <ICommonStructureService>();

            var identity = identityService.ReadIdentity(requestContext, IdentitySearchFactor.Identifier, ev.Reviewer.Descriptor.Identifier);

            using (ITfsGitRepository repository = repositoryService.FindRepositoryById(requestContext, ev.RepositoryId))
            {
                var pullRequestService = requestContext.GetService <ITeamFoundationGitPullRequestService>();
                TfsGitPullRequest pullRequest;
                if (pullRequestService.TryGetPullRequestDetails(requestContext, repository, ev.PullRequestId, out pullRequest))
                {
                    string repoUri      = repository.GetRepositoryUri();
                    var    creator      = identityService.ReadIdentities(requestContext, new[] { pullRequest.Creator }).First();
                    var    reviewers    = identityService.ReadIdentities(requestContext, pullRequest.Reviewers.Select(r => r.Reviewer).ToArray());
                    var    notification = new Notifications.PullRequestReviewerVoteNotification()
                    {
                        TeamProjectCollection = requestContext.ServiceHost.Name,
                        CreatorUniqueName     = creator.UniqueName,
                        Vote              = ev.ReviewerVote,
                        UniqueName        = identity.UniqueName,
                        DisplayName       = identity.DisplayName,
                        ProjectName       = commonService.GetProject(requestContext, ev.TeamProjectUri).Name,
                        RepoUri           = repoUri,
                        RepoName          = ev.RepositoryName,
                        PrId              = pullRequest.PullRequestId,
                        PrUrl             = $"{repoUri}/pullrequest/{ev.PullRequestId}#view=discussion",
                        PrTitle           = pullRequest.Title,
                        TeamNames         = GetUserTeamsByProjectUri(requestContext, ev.TeamProjectUri, ev.Reviewer.Descriptor),
                        SourceBranch      = new Notifications.GitRef(pullRequest.SourceBranchName),
                        TargetBranch      = new Notifications.GitRef(pullRequest.TargetBranchName),
                        ReviewerUserNames = reviewers.Select(r => r.UniqueName)
                    };
                    yield return(notification);
                }
                else
                {
                    throw new TfsNotificationRelayException("Unable to get pull request " + ev.PullRequestId);
                }
            }
        }
예제 #5
0
        protected override IEnumerable <INotification> CreateNotifications(IVssRequestContext requestContext, PushNotification pushNotification, int maxLines)
        {
            var repositoryService = requestContext.GetService <ITeamFoundationGitRepositoryService>();
            var commonService     = requestContext.GetService <CommonStructureService>();
            var commitService     = requestContext.GetService <ITeamFoundationGitCommitService>();
            var identityService   = requestContext.GetService <TeamFoundationIdentityService>();

            var identity  = identityService.ReadIdentity(requestContext, IdentitySearchFactor.Identifier, pushNotification.Pusher.Identifier);
            var teamNames = GetUserTeamsByProjectUri(requestContext, pushNotification.TeamProjectUri, pushNotification.Pusher);

            using (ITfsGitRepository repository = repositoryService.FindRepositoryById(requestContext, pushNotification.RepositoryId))
            {
                var pushRow = new PushRow()
                {
                    UniqueName  = pushNotification.AuthenticatedUserName,
                    DisplayName = identity.DisplayName,
                    RepoName    = pushNotification.RepositoryName,
                    RepoUri     = repository.GetRepositoryUri(),
                    ProjectName = commonService.GetProject(requestContext, pushNotification.TeamProjectUri).Name,
                    IsForcePush = Settings.IdentifyForcePush && pushNotification.IsForceRequired(requestContext, repository)
                };
                var notification = new GitPushNotification(requestContext.ServiceHost.Name, pushRow.ProjectName,
                                                           pushRow.RepoName, pushNotification.AuthenticatedUserName, teamNames,
                                                           pushNotification.RefUpdateResults.Where(r => r.Succeeded).Select(r => new GitRef(r)));
                notification.Add(pushRow);
                notification.TotalLineCount++;

                var refLookup   = new Dictionary <Sha1Id, List <GitRef> >();
                var deletedRefs = new List <GitRef>();
                var oldCommits  = new HashSet <TfsGitCommit>(new TfsGitObjectEqualityComparer());
                var unknowns    = new List <TfsGitRefUpdateResult>();

                // Associate refs (branch, lightweight and annotated tag) with corresponding commit
                foreach (var refUpdateResult in pushNotification.RefUpdateResults.Where(r => r.Succeeded))
                {
                    var          newObjectId = refUpdateResult.NewObjectId;
                    TfsGitCommit commit      = null;

                    if (newObjectId.IsEmpty)
                    {
                        deletedRefs.Add(new GitRef(refUpdateResult));
                        continue;
                    }

                    TfsGitObject gitObject = repository.LookupObject(newObjectId);

                    if (gitObject.ObjectType == WebApi.GitObjectType.Commit)
                    {
                        commit = gitObject as TfsGitCommit;
                    }
                    else if (gitObject.ObjectType == WebApi.GitObjectType.Tag)
                    {
                        var tag = (TfsGitTag)gitObject;
                        commit = tag.TryResolveToCommit();
                    }

                    if (commit != null)
                    {
                        List <GitRef> refs;
                        if (!refLookup.TryGetValue(commit.ObjectId, out refs))
                        {
                            refs = new List <GitRef>();
                            refLookup.Add(commit.ObjectId, refs);
                        }
                        refs.Add(new GitRef(refUpdateResult));

                        if (!pushNotification.IncludedCommits.Contains(commit.ObjectId))
                        {
                            oldCommits.Add(commit);
                        }
                    }
                    else
                    {
                        unknowns.Add(refUpdateResult);
                    }
                }

                notification.TotalLineCount += pushNotification.IncludedCommits.Count() + oldCommits.Count + unknowns.Count;

                // Add new commits with refs
                var pushCommits = pushNotification.IncludedCommits.Select(commitId => (TfsGitCommit)repository.LookupObject(commitId)).OrderByDescending(c => c.GetCommitter().Time);
                foreach (var commit in pushCommits.TakeWhile(c => notification.Count < maxLines))
                {
                    notification.Add(CreateCommitRow(requestContext, commitService, repository, commit, CommitRowType.Commit, pushNotification, refLookup));
                }

                // Add updated refs to old commits
                foreach (TfsGitCommit gitCommit in oldCommits.OrderByDescending(c => c.GetCommitter().Time).TakeWhile(c => notification.Count < maxLines))
                {
                    notification.Add(CreateCommitRow(requestContext, commitService, repository, gitCommit, CommitRowType.RefUpdate, pushNotification, refLookup));
                }

                // Add deleted refs if any
                if (deletedRefs.Any() && notification.Count < maxLines)
                {
                    notification.Add(new DeleteRow()
                    {
                        Refs = deletedRefs
                    });
                }

                // Add "unknown" refs
                foreach (var refUpdateResult in unknowns.TakeWhile(c => notification.Count < maxLines))
                {
                    var          newObjectId = refUpdateResult.NewObjectId;
                    TfsGitObject gitObject   = repository.LookupObject(newObjectId);
                    notification.Add(new RefUpdateRow()
                    {
                        NewObjectId = newObjectId,
                        ObjectType  = gitObject.ObjectType,
                        Refs        = new[] { new GitRef(refUpdateResult) }
                    });
                }

                yield return(notification);
            }
        }
예제 #6
0
        public static bool IsForceRequired(this PushNotification pushNotification, IVssRequestContext requestContext, ITfsGitRepository repository)
        {
            foreach (var refUpdateResult in pushNotification.RefUpdateResults.Where(r => r.Succeeded))
            {
                // Don't bother with new or deleted refs
                if (refUpdateResult.OldObjectId.IsEmpty || refUpdateResult.NewObjectId.IsEmpty)
                {
                    continue;
                }

                TfsGitObject gitObject = repository.LookupObject(refUpdateResult.NewObjectId);
                if (gitObject.ObjectType != GitObjectType.Commit)
                {
                    continue;
                }
                TfsGitCommit gitCommit = (TfsGitCommit)gitObject;

                if (!gitCommit.IsDescendantOf(requestContext, refUpdateResult.OldObjectId))
                {
                    return(true);
                }
            }

            return(false);
        }
예제 #7
0
        protected override PolicyEvaluationResult EvaluateInternal(IVssRequestContext requestContext, PushNotification push)
        {
            var repositoryService = requestContext.GetService <ITeamFoundationGitRepositoryService>();

            var newBranches = push.RefUpdateResults.Where(r => r.OldObjectId == Sha1Id.Empty && r.Name.StartsWith(Constants.BranchPrefix));
            var branch      = newBranches.SingleOrDefault(b => b.Name == Constants.BranchPrefix + "master");

            if (branch != null)
            {
                using (ITfsGitRepository repository = repositoryService.FindRepositoryById(requestContext, push.RepositoryId))
                {
                    TfsGitCommit commit = (TfsGitCommit)repository.LookupObject(branch.NewObjectId);
                    if (commit != null)
                    {
                        var tree        = commit.GetTree();
                        var treeEntries = tree.GetTreeEntries();
                        if (treeEntries.Any())
                        {
                            bool includesGitignore     = false;
                            bool includesGitattributes = false;
                            foreach (var entry in treeEntries)
                            {
                                if (entry.ObjectType == GitObjectType.Blob && entry.Name.Equals(".gitignore", StringComparison.OrdinalIgnoreCase))
                                {
                                    includesGitignore = true;
                                }

                                if (entry.ObjectType == GitObjectType.Blob && entry.Name.Equals(".gitattributes", StringComparison.OrdinalIgnoreCase))
                                {
                                    using (var reader = new StreamReader(entry.Object.GetContent()))
                                    {
                                        var gitattributesContents = reader.ReadToEnd();
                                        // Make sure .gitattributes file has a '* text=auto' line for eol normalization
                                        if (!Regex.IsMatch(gitattributesContents, @"^\*\s+text=auto\s*$", RegexOptions.Multiline))
                                        {
                                            Logger.Log("pushNotification:", push);
                                            var statusMessage = $".gitattributes is missing '* text=auto'. See {Settings.DocsBaseUrl}/guidelines/scm/git-conventions/#mandatory-files.";
                                            Logger.Log(statusMessage);
                                            return(new PolicyEvaluationResult(false, push.Pusher, statusMessage));
                                        }

                                        includesGitattributes = true;
                                    }
                                }
                            }

                            if (!includesGitignore || !includesGitattributes)
                            {
                                Logger.Log("pushNotification:", push);
                                var statusMessage = $"Mandatory files missing. See {Settings.DocsBaseUrl}/guidelines/scm/git-conventions/#mandatory-files.";
                                Logger.Log(statusMessage);
                                return(new PolicyEvaluationResult(false, push.Pusher, statusMessage));
                            }
                        }
                        else
                        {
                            Logger.Log("Commit without tree entries: " + branch.NewObjectId);
                        }
                    }
                    else
                    {
                        Logger.Log("Unable to find commit " + branch.NewObjectId);
                    }
                }
            }

            return(new PolicyEvaluationResult(true));
        }
예제 #8
0
        protected override IEnumerable <INotification> CreateNotifications(IVssRequestContext requestContext,
                                                                           DiscussionsNotification args, int maxLines)
        {
            var locationService   = requestContext.GetService <ILocationService>();
            var linkingService    = requestContext.GetService <TeamFoundationLinkingService>();
            var hyperlinkService  = requestContext.GetService <TswaServerHyperlinkService>();
            var identityService   = requestContext.GetService <ITeamFoundationIdentityService>();
            var commonService     = requestContext.GetService <ICommonStructureService>();
            var discussionService = requestContext.GetService <ITeamFoundationDiscussionService>();

            var notifications = new List <INotification>();

            foreach (var thread in args.Threads)
            {
                if (thread.Comments == null)
                {
                    continue;                          // e.g. when a comment is deleted
                }
                var artifactId = LinkingUtilities.DecodeUri(thread.ArtifactUri);

                int discussionId = thread.DiscussionId <= 0 ? thread.Comments[0].DiscussionId : thread.DiscussionId;

                if (artifactId.ArtifactType.Equals("Commit", StringComparison.OrdinalIgnoreCase))
                {
                    var repositoryService = requestContext.GetService <ITeamFoundationGitRepositoryService>();
                    var commitService     = requestContext.GetService <ITeamFoundationGitCommitService>();

                    Guid   projectId;
                    Guid   repositoryId;
                    Sha1Id commitId;
                    GitCommitArtifactId.Decode(artifactId, out projectId, out repositoryId, out commitId);

                    using (ITfsGitRepository repository = repositoryService.FindRepositoryById(requestContext, repositoryId))
                    {
                        var    project   = commonService.GetProject(requestContext, projectId);
                        var    repoUri   = repository.GetRepositoryUri();
                        var    commitUri = repoUri + "/commit/" + commitId.ToHexString();
                        string itemPath;
                        if (thread.Properties.TryGetValue <string>("Microsoft.TeamFoundation.Discussion.ItemPath", out itemPath))
                        {
                            commitUri += string.Format("#path={0}&discussionId={1}&_a=contents", Uri.EscapeDataString(itemPath), discussionId);
                        }

                        var commitManifest = commitService.GetCommitManifest(requestContext, repository, commitId);
                        var pushData       = commitService.GetPushDataForPushIds(requestContext, repository.RepoId.RepoId, new[] { commitManifest.PushId }).FirstOrDefault();
                        var pusher         = identityService.ReadIdentities(requestContext, new[] { pushData.PusherId }).FirstOrDefault();

                        foreach (var comment in thread.Comments)
                        {
                            var commenter = identityService.ReadIdentities(requestContext, new[] { Guid.Parse(comment.Author.Id) }).First();

                            var notification = new Notifications.CommitCommentNotification()
                            {
                                TeamProjectCollection = requestContext.ServiceHost.Name,
                                PusherUniqueName      = pusher?.UniqueName,
                                UniqueName            = commenter.UniqueName,
                                DisplayName           = comment.Author.DisplayName,
                                ProjectName           = project.Name,
                                RepoUri   = repoUri,
                                RepoName  = repository.Name,
                                CommitId  = commitId,
                                CommitUri = commitUri,
                                Comment   = TextHelper.Truncate(comment.Content, Settings.DiscussionCommentMaxLength),
                                TeamNames = GetUserTeamsByProjectUri(requestContext, project.Uri, commenter.Descriptor),
                            };

                            notifications.Add(notification);
                        }
                    }
                }
                if (artifactId.Tool.Equals("CodeReview", StringComparison.OrdinalIgnoreCase))
                {
                    var pullRequestService = requestContext.GetService <ITeamFoundationGitPullRequestService>();
                    var repositoryService  = requestContext.GetService <ITeamFoundationGitRepositoryService>();

                    Guid projectId;
                    int  pullRequestId = PullRequestArtifactHelper.GetPullRequestId(requestContext, thread.ArtifactUri, out projectId);

                    var pullRequest = pullRequestService.GetPullRequestDetails(requestContext, pullRequestId);

                    using (ITfsGitRepository repository = repositoryService.FindRepositoryById(requestContext, pullRequest.RepositoryId))
                    {
                        var    project = commonService.GetProject(requestContext, projectId);
                        string repoUri = repository.GetRepositoryUri();
                        var    creator = identityService.ReadIdentities(requestContext, new[] { pullRequest.Creator }).FirstOrDefault();

                        foreach (var comment in thread.Comments)
                        {
                            var commenter = identityService.ReadIdentities(requestContext, new[] { Guid.Parse(comment.Author.Id) }).First();

                            var notification = new Notifications.PullRequestCommentNotification()
                            {
                                TeamProjectCollection = requestContext.ServiceHost.Name,
                                CreatorUniqueName     = creator?.UniqueName,
                                UniqueName            = commenter.UniqueName,
                                DisplayName           = commenter.DisplayName,
                                ProjectName           = project.Name,
                                RepoUri      = repoUri,
                                RepoName     = repository.Name,
                                PrId         = pullRequest.PullRequestId,
                                PrUrl        = $"{repoUri}/pullrequest/{pullRequest.PullRequestId}#view=discussion",
                                PrTitle      = pullRequest.Title,
                                TeamNames    = GetUserTeamsByProjectUri(requestContext, project.Uri, commenter.Descriptor),
                                SourceBranch = new GitRef(pullRequest.SourceBranchName),
                                TargetBranch = new GitRef(pullRequest.TargetBranchName),
                                Comment      = TextHelper.Truncate(comment.Content, Settings.DiscussionCommentMaxLength)
                            };

                            notifications.Add(notification);
                        }
                    }
                }
                else if (artifactId.ArtifactType.Equals("Changeset", StringComparison.OrdinalIgnoreCase))
                {
                    var versionControlService = requestContext.GetService <TeamFoundationVersionControlService>();

                    var uri         = new VersionControlIntegrationUri(thread.ArtifactUri);
                    var changesetId = int.Parse(uri.ArtifactName);
                    var reader      = versionControlService.QueryChangeset(requestContext, changesetId, true, false, false);
                    var changeset   = reader.Current <Changeset>();

                    var    changesetUrl = hyperlinkService.GetChangesetDetailsUrl(changesetId).AbsoluteUri;
                    string baseUrl      = String.Format("{0}/{1}/",
                                                        locationService.GetAccessMapping(requestContext, "PublicAccessMapping").AccessPoint,
                                                        requestContext.ServiceHost.Name);

                    string       itemPath           = string.Empty;
                    string       projectName        = string.Empty;
                    const string projectNamePattern = @"^\$\/([^\/]*)\/";

                    if (thread.Properties != null && thread.Properties.TryGetValue <string>("Microsoft.TeamFoundation.Discussion.ItemPath", out itemPath))
                    {
                        changesetUrl += string.Format("#path={0}&discussionId={1}&_a=contents", Uri.EscapeDataString(itemPath), discussionId);
                        Match match = Regex.Match(itemPath, projectNamePattern);
                        if (match.Success)
                        {
                            projectName = match.Groups[1].Value;
                        }
                    }
                    else
                    {
                        // This assumes changeset doesn't span multiple projects.
                        var serverItem = changeset.Changes.FirstOrDefault()?.Item.ServerItem;
                        if (serverItem != null)
                        {
                            Match match = Regex.Match(serverItem, projectNamePattern);
                            if (match.Success)
                            {
                                projectName = match.Groups[1].Value;
                            }
                        }
                    }

                    var commiter = identityService.ReadIdentity(requestContext, IdentitySearchFactor.AccountName, changeset.Committer);

                    foreach (var comment in thread.Comments)
                    {
                        var commenter = identityService.ReadIdentities(requestContext, new[] { Guid.Parse(comment.Author.Id) }).First();

                        var notification = new Notifications.ChangesetCommentNotification()
                        {
                            TeamProjectCollection = requestContext.ServiceHost.Name,
                            CreatorUniqueName     = commiter?.UniqueName,
                            UniqueName            = commenter.UniqueName,
                            DisplayName           = commenter.DisplayName,
                            ProjectUrl            = baseUrl + projectName,
                            ProjectName           = projectName,
                            ChangesetId           = changesetId,
                            ChangesetUrl          = changesetUrl,
                            TeamNames             = GetUserTeamsByProjectName(requestContext, projectName, commenter.Descriptor),
                            SourcePath            = itemPath,
                            Comment = TextHelper.Truncate(comment.Content, Settings.DiscussionCommentMaxLength)
                        };

                        notifications.Add(notification);
                    }
                }
            }

            return(notifications);
        }