Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add JIRA issues parsing #96

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,12 @@ Generate a changelog using a specific provider (GitHub/GitLab/BitBucket):
git-changelog --provider github
```

Generate a changelog with a list of JIRA issues addressed per version:

```bash
git-changelog --jira-url https://<subdomain>.atlassian.net/browse/<project>-%
```

Author's favorite, from Python:

```python
Expand Down
16 changes: 16 additions & 0 deletions src/git_changelog/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,19 @@ def is_minor(self) -> bool:
"""
return bool(self.tag.split(".", 2)[2])

@property
def jira_issues(self) -> dict[str, str]:
"""List the JIRA issues associated to this version.

Returns:
A dictionnary of all the JIRA issues referenced in this version's commits and their URLs.
"""
return {
key: url
for commit in self.commits
for key, url in commit.convention.get("jira_issues", {}).items()
}

def add_commit(self, commit: Commit) -> None:
"""Register the given commit and add it to the relevant section based on its message convention.

Expand Down Expand Up @@ -204,6 +217,7 @@ def __init__(
zerover: bool = True,
filter_commits: str | None = None,
versioning: Literal["semver", "pep440"] = "semver",
jira_info: dict[str, str] | None = None,
):
"""Initialization method.

Expand All @@ -224,6 +238,7 @@ def __init__(
self.parse_trailers: bool = parse_trailers
self.zerover: bool = zerover
self.filter_commits: str | None = filter_commits
self.jira_info: dict[str, str] | None = jira_info

# set provider
if not isinstance(provider, ProviderRefParser):
Expand Down Expand Up @@ -384,6 +399,7 @@ def parse_commits(self) -> list[Commit]:
body=body,
parse_trailers=self.parse_trailers,
version_parser=self.version_parser,
jira_info=self.jira_info,
)

pos += nbl_index + 1
Expand Down
20 changes: 19 additions & 1 deletion src/git_changelog/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
".config/git-changelog.toml",
str(Path(user_config_dir()) / "git-changelog.toml"),
]
JIRA_URL_REGEX = r"^(?P<base_url>https://\w+.atlassian.net/browse/)(?P<project>\w+)-%$"
"""Default configuration files read by git-changelog."""

DEFAULT_SETTINGS: dict[str, Any] = {
Expand Down Expand Up @@ -109,6 +110,13 @@ def _comma_separated_list(value: str) -> list[str]:
return value.split(",")


def _jira_info(value: str) -> dict[str, str]:
m = re.match(JIRA_URL_REGEX, value)
if m is None:
raise argparse.ArgumentTypeError("Invalid JIRA URL")
return m.groupdict()


class _ParseDictAction(argparse.Action):
def __call__(
self,
Expand All @@ -124,7 +132,6 @@ def __call__(
key, value = values.split("=", 1)
getattr(namespace, self.dest)[key] = value


providers: dict[str, type[ProviderRefParser]] = {
"github": GitHub,
"gitlab": GitLab,
Expand Down Expand Up @@ -385,6 +392,15 @@ def get_parser() -> argparse.ArgumentParser:
help="Pass additional key/value pairs to the template. Option can be used multiple times. "
"The key/value pairs are accessible as 'jinja_context' in the template.",
)
parser.add_argument(
"-J",
"--jira-url",
action="store",
type=_jira_info,
dest="jira_info",
help="A template JIRA URL used to parse commit messages and find addressed issues. "
"The template URL must be formatted as 'https://<subdomain>.atlassian.net/browse/<project>-%%'.",
)
parser.add_argument(
"-V",
"--version",
Expand Down Expand Up @@ -546,6 +562,7 @@ def build_and_render(
filter_commits: str | None = None,
jinja_context: dict[str, Any] | None = None,
versioning: Literal["pep440", "semver"] = "semver",
jira_info: dict[str, str] | None = None,
) -> tuple[Changelog, str]:
"""Build a changelog and render it.

Expand Down Expand Up @@ -617,6 +634,7 @@ def build_and_render(
zerover=zerover,
filter_commits=filter_commits,
versioning=versioning,
jira_info=jira_info,
)

# remove empty versions from changelog data
Expand Down
27 changes: 23 additions & 4 deletions src/git_changelog/commit.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ def __init__(
parent_hashes: str | list[str] = "",
commits_map: dict[str, Commit] | None = None,
version_parser: Callable[[str], tuple[ParsedVersion, str]] | None = None,
jira_info: dict[str, str] | None = None,
):
"""Initialization method.

Expand Down Expand Up @@ -195,6 +196,7 @@ def __init__(

self.text_refs: dict[str, list[Ref]] = {}
self.convention: dict[str, Any] = {}
self.jira_info = jira_info

# YORE: Bump 3: Replace `_Trailers()` with `[]` within line.
self.trailers: list[tuple[str, str]] = _Trailers()
Expand Down Expand Up @@ -281,7 +283,7 @@ class CommitConvention(ABC):
DEFAULT_RENDER: ClassVar[list[str]]

@abstractmethod
def parse_commit(self, commit: Commit) -> dict[str, str | bool]:
def parse_commit(self, commit: Commit) -> dict[str, Any]:
"""Parse the commit to extract information.

Arguments:
Expand All @@ -292,6 +294,17 @@ def parse_commit(self, commit: Commit) -> dict[str, str | bool]:
"""
raise NotImplementedError

@staticmethod
def _parse_jira_issues(commit: Commit, message: str) -> dict[str, str]:
if commit.jira_info is None:
return {}

jira_regex = re.compile(rf"\b{commit.jira_info['project']}-[0-9]+\b", re.I | re.MULTILINE)
return {
issue.upper(): f"{commit.jira_info['base_url']}{issue.upper()}"
for issue in jira_regex.findall(message)
}

@classmethod
def _format_sections_help(cls) -> str:
reversed_map = defaultdict(list)
Expand Down Expand Up @@ -343,18 +356,20 @@ class BasicConvention(CommitConvention):
TYPES["remove"],
]

def parse_commit(self, commit: Commit) -> dict[str, str | bool]: # noqa: D102
def parse_commit(self, commit: Commit) -> dict[str, Any]: # noqa: D102
commit_type = self.parse_type(commit.subject)
message = "\n".join([commit.subject, *commit.body])
is_major = self.is_major(message)
is_minor = not is_major and self.is_minor(commit_type)
is_patch = not any((is_major, is_minor))
jira_issues = self._parse_jira_issues(commit, message)

return {
"type": commit_type,
"is_major": is_major,
"is_minor": is_minor,
"is_patch": is_patch,
"jira_issues": jira_issues,
}

def parse_type(self, commit_subject: str) -> str:
Expand Down Expand Up @@ -429,12 +444,13 @@ class AngularConvention(CommitConvention):
TYPES["perf"],
]

def parse_commit(self, commit: Commit) -> dict[str, str | bool]: # noqa: D102
def parse_commit(self, commit: Commit) -> dict[str, Any]: # noqa: D102
subject = self.parse_subject(commit.subject)
message = "\n".join([commit.subject, *commit.body])
is_major = self.is_major(message)
is_minor = not is_major and self.is_minor(subject["type"])
is_patch = not any((is_major, is_minor))
jira_issues = self._parse_jira_issues(commit, message)

return {
"type": subject["type"],
Expand All @@ -443,6 +459,7 @@ def parse_commit(self, commit: Commit) -> dict[str, str | bool]: # noqa: D102
"is_major": is_major,
"is_minor": is_minor,
"is_patch": is_patch,
"jira_issues": jira_issues,
}

def parse_subject(self, commit_subject: str) -> dict[str, str]:
Expand Down Expand Up @@ -493,12 +510,13 @@ class ConventionalCommitConvention(AngularConvention):
rf"^(?P<type>({'|'.join(TYPES.keys())}))(?:\((?P<scope>.+)\))?(?P<breaking>!)?: (?P<subject>.+)$",
)

def parse_commit(self, commit: Commit) -> dict[str, str | bool]: # noqa: D102
def parse_commit(self, commit: Commit) -> dict[str, Any]: # noqa: D102
subject = self.parse_subject(commit.subject)
message = "\n".join([commit.subject, *commit.body])
is_major = self.is_major(message) or subject.get("breaking") == "!"
is_minor = not is_major and self.is_minor(subject["type"])
is_patch = not any((is_major, is_minor))
jira_issues = self._parse_jira_issues(commit, message)

return {
"type": subject["type"],
Expand All @@ -507,4 +525,5 @@ def parse_commit(self, commit: Commit) -> dict[str, str | bool]: # noqa: D102
"is_major": is_major,
"is_minor": is_minor,
"is_patch": is_patch,
"jira_issues": jira_issues,
}
6 changes: 6 additions & 0 deletions src/git_changelog/templates/angular.md.jinja
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@
{%- endwith %}
{%- endif %}
{%- endfor %}
{%- if version.jira_issues|length > 0 %}
### JIRA issues
{% for issue_key, issue_url in version.jira_issues.items() %}
- [{{ issue_key }}]({{ issue_url }})
{%- endfor %}
{% endif %}
{%- if not (version.tag or version.planned_tag) %}
<!-- insertion marker -->{% endif %}
{% endmacro -%}
Expand Down
6 changes: 6 additions & 0 deletions src/git_changelog/templates/keepachangelog.md.jinja
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@
{%- endwith %}
{%- endif %}
{%- endfor %}
{%- if version.jira_issues|length > 0 %}
### JIRA issues
{% for issue_key, issue_url in version.jira_issues.items() %}
- [{{ issue_key }}]({{ issue_url }})
{%- endfor %}
{% endif %}
{%- if not (version.tag or version.planned_tag) %}
<!-- insertion marker -->{% endif %}
{% endmacro -%}
Expand Down
Loading