{# TODO: move to configuration for user to modify #}
{% set section_heading_translations = {
    'feat': 'features',
    'fix': 'bug fixes',
    'perf': 'performance improvements',
    'docs': 'documentation',
    'build': 'build system',
    'refactor': 'refactoring',
    'test': 'testing',
    'ci': 'continuous integration',
    'chore': 'chores',
    'style': 'code style',
  }
%}

{% set section_heading_order = section_heading_translations.values() %}

{% set emoji_map = {
    'breaking': '💥',
    'features': '✨',
    'bug fixes': '🪲',
    'performance improvements': '⚡',
    'documentation': '📖',
    'build system': '⚙️',
    'refactoring': '♻️',
    'testing': '✅',
    'continuous integration': '🤖',
    'chores': '🧹',
    'code style': '🎨',
    'unknown': '❗',
    'release_note': '💡',
} %}

{#
  MACRO: format a post-paragraph link reference in RST
#}{%  macro format_link_reference(link, label)
%}{{    ".. _%s: %s" | format(label, link)
}}{%  endmacro
%}


{#
  MACRO: Capitalize the first letter of a string only
#}{%  macro capitalize_first_letter_only(sentence)
%}{{    (sentence[0] | upper) ~ sentence[1:]
}}{%  endmacro
%}


{#
  MACRO: format commit summary line
#}{%  macro format_commit_summary_line(commit)
%}{#    # Check for Parsing Error
#}{%    if commit.error is undefined
%}{#
   #      # Add any message links to the commit summary line
#}{%      set summary_line = commit_msg_links(commit)
%}{#
#}{%      if commit.scope
%}{%        set summary_line = "**%s**: %s" | format(commit.scope, summary_line)
%}{%      endif
%}{#
   #      # Return the modified summary_line
#}{{      summary_line
}}{#
#}{%    else
%}{#      # Return the first line of the commit if there was a Parsing Error
#}{{      (commit.commit.message | string).split("\n", maxsplit=1)[0]
}}{%    endif
%}{%  endmacro
%}


{#
  MACRO: Create & return an non-inline RST link from a commit message
  - Returns empty string if no PR/MR identifier is found
#}{%  macro extract_pr_link_reference(commit)
%}{%    if commit.error is undefined
%}{%      set summary_line = commit.descriptions[0]
%}{#
#}{%      if commit.linked_merge_request != ""
%}{#        # Create a PR/MR reference url
#}{{        format_link_reference(
              commit.linked_merge_request | pull_request_url,
              "PR" ~ commit.linked_merge_request,
            )
}}{%      endif
%}{%    endif
%}{%  endmacro
%}

{#
  MACRO: Extract issue references from a parsed commit object
  - Stores the issue urls in the namespace object
#}{%  macro extract_issue_link_references(ns, commit)
%}{%    set issue_urls = []
%}{#
#}{%    if commit.linked_issues is defined and commit.linked_issues | length > 0
%}{%      for issue_num in commit.linked_issues
%}{#        # Create an issue reference url
#}{%        set _ = issue_urls.append(
              format_link_reference(
                issue_num | issue_url,
                issue_num,
              )
            )
%}{%      endfor
%}{%    endif
%}{#
   #    # Store the issue urls in the namespace object
#}{%    set ns.urls = issue_urls
%}{%  endmacro
%}

{#
  MACRO: formats a commit message for a non-inline RST link for a commit hash and/or PR/MR
#}{%  macro commit_msg_links(commit)
%}{%    if commit.error is undefined
%}{#
   #      # Initialize variables
#}{%      set closes_statement = ""
%}{%      set link_references = []
%}{%      set summary_line = capitalize_first_letter_only(
            commit.descriptions[0] | safe
          )
%}{#
#}{%      if commit.linked_issues | length > 0
%}{%        set closes_statement = ", closes `%s`_" | format(
              commit.linked_issues | join("`_, `")
            )
%}{%      endif
%}{#
#}{%      if commit.linked_merge_request != ""
%}{#        # TODO: breaking change v10, remove summary line replacers as PSR will do it for us
#}{%        set summary_line = summary_line | replace("(pull request ", "(") | replace("(" ~ commit.linked_merge_request ~ ")", "") | trim
%}{#
   #        # Add PR references with a link to the PR
#}{%        set _ = link_references.append("`PR%s`_" | format(commit.linked_merge_request))
%}{%      endif
%}{#
          # DEFAULT: Always include the commit hash as a link
#}{%      set _ = link_references.append("`%s`_" | format(commit.short_hash))
%}{#
#}{%      set formatted_links = ""
%}{%      if link_references | length > 0
%}{%        set formatted_links = " (%s)" | format(link_references | join(", "))
%}{%      endif
%}{#
          # Return the modified summary_line
#}{{      summary_line ~ closes_statement ~ formatted_links
}}{%    endif
%}{%  endmacro
%}


{# MACRO: generate a heading underline that matches the exact length of the header #}
{%    macro generate_heading_underline(header, underline_char)
%}{%    set header_underline = []
%}{%    for _ in header
%}{%      set __ = header_underline.append(underline_char)
%}{%    endfor
%}{#    # Print out the header underline
#}{{    header_underline | join
}}{%  endmacro
%}


{#
  MACRO: format the breaking changes description by:
  - Capitalizing the description
  - Adding an optional scope prefix
#}{%  macro format_breaking_changes_description(commit)
%}{%    set ns = namespace(full_description="")
%}{#
#}{%    if commit.error is undefined
%}{%      for paragraph in commit.breaking_descriptions
%}{%        if paragraph | trim | length > 0
%}{#
#}{%          set paragraph_text = capitalize_first_letter_only(paragraph) | trim | safe
%}{#
#}{%          set ns.full_description = [
                ns.full_description,
                paragraph_text
              ] | join("\n\n")
%}{#
#}{%        endif
%}{%      endfor
%}{#
#}{%      set ns.full_description = ns.full_description | trim
%}{#
#}{%      if commit.scope
%}{%        set ns.full_description = "**%s**: %s" | format(
              commit.scope, ns.full_description
            )
%}{%      endif
%}{%    endif
%}{#
#}{{    ns.full_description
}}{%  endmacro
%}


{#
  MACRO: format the release notice by:
  - Capitalizing the description
  - Adding an optional scope prefix
#}{%  macro format_release_notice(commit)
%}{%    set ns = namespace(full_description="")
%}{#
#}{%    if commit.error is undefined
%}{%      for paragraph in commit.release_notices
%}{%        if paragraph | trim | length > 0
%}{#
#}{%          set paragraph_text = capitalize_first_letter_only(paragraph) | trim | safe
%}{#
#}{%          set ns.full_description = [
                ns.full_description,
                paragraph_text
              ] | join("\n\n")
%}{#
#}{%        endif
%}{%      endfor
%}{#
#}{%      set ns.full_description = ns.full_description | trim
%}{#
#}{%      if commit.scope
%}{%        set ns.full_description = "**%s**: %s" | format(
              commit.scope, ns.full_description
            )
%}{%      endif
%}{%    endif
%}{#
#}{{    ns.full_description
}}{%  endmacro
%}


{#
   MACRO: order commits alphabetically by scope and attribute
   - Commits are sorted based on scope and then the attribute alphabetically
   - Commits without scope are placed first and sorted alphabetically by the attribute
   - parameter: ns (namespace) object with a commits list
   - parameter: attr (string) attribute to sort by
   - returns None but modifies the ns.commits list in place
#}{%  macro order_commits_alphabetically_by_scope_and_attr(ns, attr)
%}{%    set ordered_commits = []
%}{#
   #    # Eliminate any ParseError commits from input set
#}{%    set filtered_commits = ns.commits | rejectattr("error", "defined") | list
%}{#
   #    # grab all commits with no scope and sort alphabetically by attr
#}{%    for commit in filtered_commits | rejectattr("scope") | sort(attribute=attr)
%}{%      set _ = ordered_commits.append(commit)
%}{%     endfor
%}{#
   #    # grab all commits with a scope and sort alphabetically by the scope and then attr
#}{%    for commit in filtered_commits | selectattr("scope") | sort(attribute=(['scope', attr] | join(",")))
%}{%      set _ = ordered_commits.append(commit)
%}{%    endfor
%}{#
   #    # Return the ordered commits
#}{%    set ns.commits = ordered_commits
%}{%  endmacro
%}


{#
  MACRO: apply smart ordering of commits objects based on alphabetized summaries and then scopes
  - Commits are sorted based on the commit type and the commit message
  - Commits are grouped by the commit type
  - parameter: ns (namespace) object with a commits list
  - returns None but modifies the ns.commits list in place
#}{%  macro apply_alphabetical_ordering_by_descriptions(ns)
%}{%    set _ = order_commits_alphabetically_by_scope_and_attr(ns, 'descriptions.0')
%}{%  endmacro
%}


{#
  MACRO: apply smart ordering of commits objects based on alphabetized breaking changes and then scopes
  - Commits are sorted based on the commit type and the commit message
  - Commits are grouped by the commit type
  - parameter: ns (namespace) object with a commits list
  - returns None but modifies the ns.commits list in place
#}{%  macro apply_alphabetical_ordering_by_brk_descriptions(ns)
%}{%    set _ = order_commits_alphabetically_by_scope_and_attr(ns, 'breaking_descriptions.0')
%}{%  endmacro
%}


{#
  MACRO: apply smart ordering of commits objects based on alphabetized release notices and then scopes
  - Commits are sorted based on the commit type and the commit message
  - Commits are grouped by the commit type
  - parameter: ns (namespace) object with a commits list
  - returns None but modifies the ns.commits list in place
#}{%  macro apply_alphabetical_ordering_by_release_notices(ns)
%}{%    set _ = order_commits_alphabetically_by_scope_and_attr(ns, 'release_notices.0')
%}{%  endmacro
%}
