public static SemanticReleaseNotes GenerateReleaseNotes(Context context,
            IRepository gitRepo, IIssueTracker issueTracker, SemanticReleaseNotes previousReleaseNotes,
            Categories categories, TaggedCommit tagToStartFrom, ReleaseInfo currentReleaseInfo)
        {
            var releases = ReleaseFinder.FindReleases(gitRepo, tagToStartFrom, currentReleaseInfo);
            var findIssuesSince =
                IssueStartDateBasedOnPreviousReleaseNotes(gitRepo, previousReleaseNotes)
                ??
                tagToStartFrom.Commit.Author.When;

            var closedIssues = issueTracker.GetClosedIssues(context.IssueTracker, findIssuesSince).ToArray();

            var semanticReleases = (
                from release in releases
                let releaseNoteItems = closedIssues
                    .Where(i => (release.When == null || i.DateClosed < release.When) && (release.PreviousReleaseDate == null || i.DateClosed > release.PreviousReleaseDate))
                    .Select(i => new ReleaseNoteItem(i.Title, i.Id, i.HtmlUrl, i.Labels, i.DateClosed, i.Contributors))
                    .ToList<IReleaseNoteLine>()
                let beginningSha = release.FirstCommit == null ? null : release.FirstCommit.Substring(0, 10)
                let endSha = release.LastCommit == null ? null : release.LastCommit.Substring(0, 10)
                select new SemanticRelease(release.Name, release.When, releaseNoteItems, new ReleaseDiffInfo
                {
                    BeginningSha = beginningSha,
                    EndSha = endSha,
                    //DiffUrlFormat = issueTracker.DiffUrlFormat
                })).ToList();

            return new SemanticReleaseNotes(semanticReleases, categories).Merge(previousReleaseNotes);
        }
        public string ToString(Categories categories)
        {
            var formattedcategories = FormatCategories(Tags, categories);
            var issueNum = IssueNumber == null ? null : String.Format(" [{0}]", IssueNumber);
            var url = HtmlUrl == null ? null : String.Format("({0})", HtmlUrl);
            var contributors = Contributors == null || Contributors.Length == 0 ?
                string.Empty : " contributed by " + String.Join(", ", Contributors.Select(r => String.Format("{0} ([{1}]({2}))", r.Name, r.Username, r.Url)));

            return string.Format(" - {1}{2}{4}{0}{5}{3}", Title, issueNum, url, formattedcategories,
                Title.TrimStart().StartsWith("-") ? null : " - ",
                contributors).Replace("  ", " ").Replace("- -", "-");
        }
        public async Task<SemanticReleaseNotes> GenerateReleaseNotesAsync(SemanticReleaseNotes releaseNotesToUpdate)
        {
            var gitRepository = new Repository(Repository.Discover(_generationParameters.WorkingDirectory));
            IIssueTracker issueTracker;
            if (_generationParameters.IssueTracker.Type.HasValue)
            {
                issueTracker = IssueTrackerFactory.CreateIssueTracker(new IssueTrackerSettings(_generationParameters.IssueTracker.Server,
                        _generationParameters.IssueTracker.Type.Value)
                    {
                        Project = _generationParameters.IssueTracker.ProjectId,
                        Authentication = _generationParameters.IssueTracker.Authentication.ToIssueTrackerSettings()
                    });
            }
            else
            {
                if (!TryRemote(gitRepository, "upstream", _generationParameters, out issueTracker) &&
                    !TryRemote(gitRepository, "origin", _generationParameters, out issueTracker))
                {
                    throw new Exception("Unable to guess issue tracker through remote, specify issue tracker type on the command line");
                }
            }

            var categories = new Categories(_generationParameters.Categories, _generationParameters.AllLabels);
            var tagToStartFrom = _generationParameters.AllTags
                ? gitRepository.GetFirstCommit()
                : gitRepository.GetLastTaggedCommit() ?? gitRepository.GetFirstCommit();
            var currentReleaseInfo = gitRepository.GetCurrentReleaseInfo();
            if (!string.IsNullOrEmpty(_generationParameters.Version))
            {
                currentReleaseInfo.Name = _generationParameters.Version;
                currentReleaseInfo.When = DateTimeOffset.Now;
            }
            else
            {
                currentReleaseInfo.Name = "vNext";
            }

            var releaseNotes = await GenerateReleaseNotesAsync(
                _generationParameters, gitRepository, issueTracker,
                releaseNotesToUpdate, categories,
                tagToStartFrom, currentReleaseInfo);

            return releaseNotes;
        }
        private string FormatCategories(string[] tags, Categories categories)
        {
            var taggedCategories = categories.AllLabels ? Tags : new[] { Tags.FirstOrDefault(t => categories.AvailableCategories.Any(c => c.Equals(t, StringComparison.InvariantCultureIgnoreCase))) };

            if(taggedCategories == null || (taggedCategories.Length == 1 && string.IsNullOrEmpty(taggedCategories[0])))
            {
                return null;
            }

            for (int i = 0; i < taggedCategories.Length; i++)
            {
                if ("bug".Equals(taggedCategories[i], StringComparison.InvariantCultureIgnoreCase))
                {
                    taggedCategories[i] = "fix";
                }
                taggedCategories[i] = string.Concat(" +", taggedCategories[i].Replace(" ", "-"));
            }

            return string.Join(string.Empty, taggedCategories);
        }
        public SemanticReleaseNotes GenerateReleaseNotes()
        {
            var context = _context;

            using (var gitRepoContext = GetRepository(context, _fileSystem))
            {
                // Remote repo's require some additional preparation before first use.
                if (gitRepoContext.IsRemote)
                {
                    gitRepoContext.PrepareRemoteRepoForUse(context.Repository.Branch);
                    if (!string.IsNullOrWhiteSpace(context.OutputFile))
                    {
                        gitRepoContext.CheckoutFilesIfExist(context.OutputFile);
                    }
                }

                var gitRepo = gitRepoContext.Repository;

                if (context.IssueTracker == null)
                {
                    // TODO: Write auto detection mechanism which is better than this
                    throw new GitReleaseNotesException("Feature to automatically detect issue tracker must be written");
                    //var firstOrDefault = _issueTrackers.FirstOrDefault(i => i.Value.RemotePresentWhichMatches);
                    //if (firstOrDefault.Value != null)
                    //{
                    //    issueTracker = firstOrDefault.Value;
                    //}
                }

                var issueTracker = _issueTrackerFactory.CreateIssueTracker(context, gitRepo);
                if (issueTracker == null)
                {
                    throw new GitReleaseNotesException("Failed to create issue tracker from context, cannot continue");
                }

                var releaseFileWriter = new ReleaseFileWriter(_fileSystem);
                string outputFile = null;
                var previousReleaseNotes = new SemanticReleaseNotes();

                var outputPath = gitRepo.Info.Path;
                var outputDirectory = new DirectoryInfo(outputPath);
                if (outputDirectory.Name == ".git")
                {
                    outputPath = outputDirectory.Parent.FullName;
                }

                if (!string.IsNullOrEmpty(context.OutputFile))
                {
                    outputFile = Path.IsPathRooted(context.OutputFile)
                        ? context.OutputFile
                        : Path.Combine(outputPath, context.OutputFile);
                    previousReleaseNotes = new ReleaseNotesFileReader(_fileSystem, outputPath).ReadPreviousReleaseNotes(outputFile);
                }

                var categories = new Categories(context.Categories, context.AllLabels);
                var tagToStartFrom = context.AllTags
                    ? GitRepositoryInfoFinder.GetFirstCommit(gitRepo)
                    : GitRepositoryInfoFinder.GetLastTaggedCommit(gitRepo) ?? GitRepositoryInfoFinder.GetFirstCommit(gitRepo);
                var currentReleaseInfo = GitRepositoryInfoFinder.GetCurrentReleaseInfo(gitRepo);
                if (!string.IsNullOrEmpty(context.Version))
                {
                    currentReleaseInfo.Name = context.Version;
                    currentReleaseInfo.When = DateTimeOffset.Now;
                }

                var releaseNotes = GenerateReleaseNotes(
                    context, gitRepo, issueTracker,
                    previousReleaseNotes, categories,
                    tagToStartFrom, currentReleaseInfo);

                var releaseNotesOutput = releaseNotes.ToString();
                releaseFileWriter.OutputReleaseNotesFile(releaseNotesOutput, outputFile);

                return releaseNotes;
            }
        }
 public SemanticReleaseNotes(IEnumerable<SemanticRelease> releaseNoteItems, Categories categories)
 {
     this.categories = categories;
     Releases = releaseNoteItems.ToArray();
 }
 public SemanticReleaseNotes()
 {
     categories = new Categories();
     Releases = new SemanticRelease[0];
 }
        public static async Task<SemanticReleaseNotes> GenerateReleaseNotesAsync(ReleaseNotesGenerationParameters generationParameters,
            IRepository gitRepo, IIssueTracker issueTracker, SemanticReleaseNotes previousReleaseNotes,
            Categories categories, TaggedCommit tagToStartFrom, ReleaseInfo currentReleaseInfo)
        {
            var releases = ReleaseFinder.FindReleases(gitRepo, tagToStartFrom, currentReleaseInfo);

            var findIssuesSince =
                IssueStartDateBasedOnPreviousReleaseNotes(gitRepo, previousReleaseNotes)
                ??
                tagToStartFrom.Commit.Author.When;

            var filter = new IssueTrackerFilter
            {
                Since = findIssuesSince,
                IncludeOpen = false
            };

            var closedIssues = (await issueTracker.GetIssuesAsync(filter)).ToArray();

            // As discussed here: https://github.com/GitTools/GitReleaseNotes/issues/85

            var semanticReleases = new Dictionary<string, SemanticRelease>();

            foreach (var issue in closedIssues)
            {
                // 1) Include all issues from the issue tracker that are assigned to this release
                foreach (var fixVersion in issue.FixVersions)
                {
                    if (!fixVersion.IsReleased)
                    {
                        continue;
                    }

                    if (!semanticReleases.ContainsKey(fixVersion.Name))
                    {
                        semanticReleases.Add(fixVersion.Name, new SemanticRelease(fixVersion.Name, fixVersion.ReleaseDate));
                    }

                    var semanticRelease = semanticReleases[fixVersion.Name];

                    var releaseNoteItem = new ReleaseNoteItem(issue.Title, issue.Id, issue.Url, issue.Labels,
                        issue.DateClosed, new Contributor[] { /*TODO: implement*/ });

                    semanticRelease.ReleaseNoteLines.Add(releaseNoteItem);
                }

                // 2) Get closed issues from the issue tracker that have no fixversion but are closed between the last release and this release
                if (issue.FixVersions.Count == 0)
                {
                    foreach (var release in releases)
                    {
                        if (issue.DateClosed.HasValue &&
                            issue.DateClosed.Value > release.PreviousReleaseDate &&
                            (release.When == null || issue.DateClosed <= release.When))
                        {
                            if (!semanticReleases.ContainsKey(release.Name))
                            {
                                var beginningSha = release.FirstCommit != null ? release.FirstCommit.Substring(0, 10) : null;
                                var endSha = release.LastCommit != null ? release.LastCommit.Substring(0, 10) : null;

                                semanticReleases.Add(release.Name, new SemanticRelease(release.Name, release.When, new ReleaseDiffInfo
                                {
                                    BeginningSha = beginningSha,
                                    EndSha = endSha,
                                    // TODO DiffUrlFormat = context.Repository.DiffUrlFormat
                                }));
                            }

                            var semanticRelease = semanticReleases[release.Name];

                            var releaseNoteItem = new ReleaseNoteItem(issue.Title, issue.Id, issue.Url, issue.Labels,
                                issue.DateClosed, issue.Contributors);

                            semanticRelease.ReleaseNoteLines.Add(releaseNoteItem);
                        }
                    }
                }
            }

            // 3) Remove any duplicates
            foreach (var semanticRelease in semanticReleases.Values)
            {
                var handledIssues = new HashSet<string>();

                for (var i = 0; i < semanticRelease.ReleaseNoteLines.Count; i++)
                {
                    var releaseNoteLine = semanticRelease.ReleaseNoteLines[i] as ReleaseNoteItem;
                    if (releaseNoteLine == null)
                    {
                        continue;
                    }

                    if (handledIssues.Contains(releaseNoteLine.IssueNumber))
                    {
                        semanticRelease.ReleaseNoteLines.RemoveAt(i--);
                        continue;
                    }

                    handledIssues.Add(releaseNoteLine.IssueNumber);
                }
            }

            var semanticReleaseNotes = new SemanticReleaseNotes(semanticReleases.Values, categories);
            var mergedReleaseNotes = semanticReleaseNotes.Merge(previousReleaseNotes);
            return mergedReleaseNotes;
        }
 public SemanticReleaseNotes(IEnumerable <SemanticRelease> releaseNoteItems, Categories categories)
 {
     this.categories = categories;
     releases        = releaseNoteItems.ToArray();
 }
 public SemanticReleaseNotes()
 {
     categories = new Categories();
     releases   = new SemanticRelease[0];
 }
        public SemanticReleaseNotes GenerateReleaseNotes()
        {
            var context = _context;

            using (var gitRepoContext = GetRepository(context))
            {
                // Remote repo's require some additional preparation before first use.
                if (gitRepoContext.IsRemote)
                {
                    gitRepoContext.PrepareRemoteRepoForUse(context.Repository.Branch);
                    if (!string.IsNullOrWhiteSpace(context.OutputFile))
                    {
                        gitRepoContext.CheckoutFilesIfExist(context.OutputFile);
                    }
                }

                var gitRepo = gitRepoContext.Repository;

                CreateIssueTrackers(gitRepo, context);

                IIssueTracker issueTracker = null;
                if (context.IssueTracker == null)
                {
                    var firstOrDefault = _issueTrackers.FirstOrDefault(i => i.Value.RemotePresentWhichMatches);
                    if (firstOrDefault.Value != null)
                    {
                        issueTracker = firstOrDefault.Value;
                    }
                }

                if (issueTracker == null)
                {
                    if (!_issueTrackers.ContainsKey(context.IssueTracker.Value))
                    {
                        throw new GitReleaseNotesException("{0} is not a known issue tracker", context.IssueTracker.Value);
                    }

                    issueTracker = _issueTrackers[context.IssueTracker.Value];
                }

                if (!issueTracker.VerifyArgumentsAndWriteErrorsToLog())
                {
                    throw new GitReleaseNotesException("Argument verification failed");
                }

                var    fileSystem           = new FileSystem.FileSystem();
                var    releaseFileWriter    = new ReleaseFileWriter(fileSystem);
                string outputFile           = null;
                var    previousReleaseNotes = new SemanticReleaseNotes();

                var outputPath      = gitRepo.Info.Path;
                var outputDirectory = new DirectoryInfo(outputPath);
                if (outputDirectory.Name == ".git")
                {
                    outputPath = outputDirectory.Parent.FullName;
                }

                if (!string.IsNullOrEmpty(context.OutputFile))
                {
                    outputFile = Path.IsPathRooted(context.OutputFile)
                        ? context.OutputFile
                        : Path.Combine(outputPath, context.OutputFile);
                    previousReleaseNotes = new ReleaseNotesFileReader(fileSystem, outputPath).ReadPreviousReleaseNotes(outputFile);
                }

                var categories     = new Categories(context.Categories, context.AllLabels);
                var tagToStartFrom = context.AllTags
                    ? GitRepositoryInfoFinder.GetFirstCommit(gitRepo)
                    : GitRepositoryInfoFinder.GetLastTaggedCommit(gitRepo) ?? GitRepositoryInfoFinder.GetFirstCommit(gitRepo);
                var currentReleaseInfo = GitRepositoryInfoFinder.GetCurrentReleaseInfo(gitRepo);
                if (!string.IsNullOrEmpty(context.Version))
                {
                    currentReleaseInfo.Name = context.Version;
                    currentReleaseInfo.When = DateTimeOffset.Now;
                }

                var releaseNotes = GenerateReleaseNotes(
                    gitRepo, issueTracker,
                    previousReleaseNotes, categories,
                    tagToStartFrom, currentReleaseInfo,
                    issueTracker.DiffUrlFormat);

                var releaseNotesOutput = releaseNotes.ToString();
                releaseFileWriter.OutputReleaseNotesFile(releaseNotesOutput, outputFile);

                return(releaseNotes);
            }
        }