Skip to content

build ¤

The module responsible for building the data.

Classes:

  • Changelog

    The main changelog class.

  • Section

    A list of commits grouped by section_type.

  • Version

    A class to represent a changelog version.

Functions:

Changelog ¤

Changelog(
    repository: str | Path,
    *,
    provider: (
        ProviderRefParser | type[ProviderRefParser] | None
    ) = None,
    convention: ConventionType | None = None,
    parse_provider_refs: bool = False,
    parse_trailers: bool = False,
    sections: list[str] | None = None,
    bump_latest: bool = False,
    bump: str | None = None,
    zerover: bool = True,
    filter_commits: str | None = None,
    versioning: Literal["semver", "pep440"] = "semver"
)

The main changelog class.

Parameters:

  • repository (str | Path) –

    The repository (directory) for which to build the changelog.

  • provider (ProviderRefParser | type[ProviderRefParser] | None, default: None ) –

    The provider to use (github.com, gitlab.com, etc.).

  • convention (ConventionType | None, default: None ) –

    The commit convention to use (angular, etc.).

  • parse_provider_refs (bool, default: False ) –

    Whether to parse provider-specific references in the commit messages.

  • parse_trailers (bool, default: False ) –

    Whether to parse Git trailers in the commit messages.

  • sections (list[str] | None, default: None ) –

    The sections to render (features, bug fixes, etc.).

  • bump_latest (bool, default: False ) –

    Deprecated, use bump="auto" instead. Whether to try and bump latest version to guess new one.

  • bump (str | None, default: None ) –

    Whether to try and bump to a given version.

  • zerover (bool, default: True ) –

    Keep major version at zero, even for breaking changes.

  • filter_commits (str | None, default: None ) –

    The Git revision-range used to filter commits in git-log (e.g: v1.0.1..).

Methods:

  • get_log

    Get the git log output.

  • get_remote_url

    Get the git remote URL for the repository.

  • parse_commits

    Parse the output of 'git log' into a list of commits.

  • run_git

    Run a git command in the chosen repository.

Source code in src/git_changelog/build.py
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
def __init__(
    self,
    repository: str | Path,
    *,
    provider: ProviderRefParser | type[ProviderRefParser] | None = None,
    convention: ConventionType | None = None,
    parse_provider_refs: bool = False,
    parse_trailers: bool = False,
    sections: list[str] | None = None,
    bump_latest: bool = False,
    bump: str | None = None,
    zerover: bool = True,
    filter_commits: str | None = None,
    versioning: Literal["semver", "pep440"] = "semver",
):
    """Initialization method.

    Arguments:
        repository: The repository (directory) for which to build the changelog.
        provider: The provider to use (github.com, gitlab.com, etc.).
        convention: The commit convention to use (angular, etc.).
        parse_provider_refs: Whether to parse provider-specific references in the commit messages.
        parse_trailers: Whether to parse Git trailers in the commit messages.
        sections: The sections to render (features, bug fixes, etc.).
        bump_latest: Deprecated, use `bump="auto"` instead. Whether to try and bump latest version to guess new one.
        bump: Whether to try and bump to a given version.
        zerover: Keep major version at zero, even for breaking changes.
        filter_commits: The Git revision-range used to filter commits in git-log (e.g: `v1.0.1..`).
    """
    self.repository: str | Path = repository
    self.parse_provider_refs: bool = parse_provider_refs
    self.parse_trailers: bool = parse_trailers
    self.zerover: bool = zerover
    self.filter_commits: str | None = filter_commits

    # set provider
    if not isinstance(provider, ProviderRefParser):
        remote_url = self.get_remote_url()
        split = remote_url.split("/")
        provider_url = "/".join(split[:3])
        namespace, project = "/".join(split[3:-1]), split[-1]
        if callable(provider):
            provider = provider(namespace, project, url=provider_url)
        elif "github" in provider_url:
            provider = GitHub(namespace, project, url=provider_url)
        elif "gitlab" in provider_url:
            provider = GitLab(namespace, project, url=provider_url)
        elif "bitbucket" in provider_url:
            provider = Bitbucket(namespace, project, url=provider_url)
        else:
            provider = None
        self.remote_url: str = remote_url
    self.provider = provider

    # set convention
    if isinstance(convention, str):
        try:
            convention = self.CONVENTION[convention]()
        except KeyError:
            print(  # noqa: T201
                f"git-changelog: no such convention available: {convention}, using default convention",
                file=sys.stderr,
            )
            convention = BasicConvention()
    elif convention is None:
        convention = BasicConvention()
    elif not isinstance(convention, CommitConvention) and issubclass(convention, CommitConvention):
        convention = convention()
    self.convention: CommitConvention = convention

    # set sections
    sections = (
        [self.convention.TYPES[section] for section in sections] if sections else self.convention.DEFAULT_RENDER
    )
    self.sections = sections

    # get version parser based on selected versioning scheme
    self.version_parser, self.version_bumper = {
        "semver": (parse_semver, bump_semver),
        "pep440": (parse_pep440, bump_pep440),
    }[versioning]

    # get git log and parse it into list of commits
    self.raw_log: str = self.get_log()
    self.commits: list[Commit] = self.parse_commits()
    self.tag_commits: list[Commit] = [commit for commit in self.commits[1:] if commit.tag]
    self.tag_commits.insert(0, self.commits[0])

    # apply dates to commits and group them by version
    v_list, v_dict = self._group_commits_by_version()
    self.versions_list = v_list
    self.versions_dict = v_dict

    # TODO: remove at some point
    if bump_latest:
        warnings.warn(
            "`bump_latest=True` is deprecated in favor of `bump='auto'`",
            DeprecationWarning,
            stacklevel=1,
        )
        if bump is None:
            bump = "auto"
    if bump:
        self._bump(bump)

get_log ¤

get_log() -> str

Get the git log output.

Returns:

  • str

    The output of the git log command, with a particular format.

Source code in src/git_changelog/build.py
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
def get_log(self) -> str:
    """Get the `git log` output.

    Returns:
        The output of the `git log` command, with a particular format.
    """
    if self.filter_commits:
        try:
            return self.run_git("log", "--date=unix", "--format=" + self.FORMAT, self.filter_commits)
        except CalledProcessError as e:
            raise ValueError(
                f"An error ocurred. Maybe the provided git-log revision-range is not valid: '{self.filter_commits}'",
            ) from e

    # No revision-range provided. Call normally
    return self.run_git("log", "--date=unix", "--format=" + self.FORMAT)

get_remote_url ¤

get_remote_url() -> str

Get the git remote URL for the repository.

Returns:

  • str

    The origin remote URL.

Source code in src/git_changelog/build.py
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
def get_remote_url(self) -> str:
    """Get the git remote URL for the repository.

    Returns:
        The origin remote URL.
    """
    remote = "remote." + os.environ.get("GIT_CHANGELOG_REMOTE", "origin") + ".url"
    git_url = self.run_git("config", "--default", "", "--get", remote).rstrip("\n")
    if git_url.startswith("git@"):
        git_url = git_url.replace(":", "/", 1).replace("git@", "https://", 1)
    if git_url.endswith(".git"):
        git_url = git_url[:-4]

    # Remove credentials from the URL.
    if git_url.startswith(("http://", "https://")):
        # (addressing scheme, network location, path, query, fragment identifier)
        urlparts = list(urlsplit(git_url))
        urlparts[1] = urlparts[1].split("@", 1)[-1]
        git_url = urlunsplit(urlparts)

    return git_url

parse_commits ¤

parse_commits() -> list[Commit]

Parse the output of 'git log' into a list of commits.

The commits build a Git commit graph by referencing their parent commits. Commits are ordered from newest to oldest.

Returns:

Source code in src/git_changelog/build.py
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
def parse_commits(self) -> list[Commit]:
    """Parse the output of 'git log' into a list of commits.

    The commits build a Git commit graph by referencing their parent commits.
    Commits are ordered from newest to oldest.

    Returns:
        The list of commits.
    """
    lines = self.raw_log.split("\n")
    size = len(lines) - 1  # Don't count last blank line.
    pos = 0

    commits_map: dict[str, Commit] = {}

    while pos < size:
        # Build message body.
        nbl_index = 10
        body = []
        while lines[pos + nbl_index] != self.MARKER:
            body.append(lines[pos + nbl_index].strip("\r"))
            nbl_index += 1

        # Build commit object.
        commit = Commit(
            commit_hash=lines[pos],
            author_name=lines[pos + 1],
            author_email=lines[pos + 2],
            author_date=lines[pos + 3],
            committer_name=lines[pos + 4],
            committer_email=lines[pos + 5],
            committer_date=lines[pos + 6],
            refs=lines[pos + 7],
            parent_hashes=lines[pos + 8],
            commits_map=commits_map,
            subject=lines[pos + 9],
            body=body,
            parse_trailers=self.parse_trailers,
            version_parser=self.version_parser,
        )

        pos += nbl_index + 1

        # Expand commit object with provider parsing.
        if self.provider:
            commit.update_with_provider(self.provider, parse_refs=self.parse_provider_refs)

        # Set the commit url based on remote_url (could be wrong).
        elif self.remote_url:
            commit.url = self.remote_url + "/commit/" + commit.hash

        # Expand commit object with convention parsing.
        if self.convention:
            commit.update_with_convention(self.convention)

        commits_map[commit.hash] = commit

    return list(commits_map.values())

run_git ¤

run_git(*args: str) -> str

Run a git command in the chosen repository.

Parameters:

  • *args (str, default: () ) –

    Arguments passed to the git command.

Returns:

  • str

    The git command output.

Source code in src/git_changelog/build.py
298
299
300
301
302
303
304
305
306
307
def run_git(self, *args: str) -> str:
    """Run a git command in the chosen repository.

    Arguments:
        *args: Arguments passed to the git command.

    Returns:
        The git command output.
    """
    return check_output(["git", *args], cwd=self.repository).decode("utf8")  # noqa: S603,S607

Section ¤

Section(
    section_type: str = "",
    commits: list[Commit] | None = None,
)

A list of commits grouped by section_type.

Parameters:

  • section_type (str, default: '' ) –

    The section section_type.

  • commits (list[Commit] | None, default: None ) –

    The list of commits.

Source code in src/git_changelog/build.py
73
74
75
76
77
78
79
80
81
def __init__(self, section_type: str = "", commits: list[Commit] | None = None):
    """Initialization method.

    Arguments:
        section_type: The section section_type.
        commits: The list of commits.
    """
    self.type: str = section_type
    self.commits: list[Commit] = commits or []

Version ¤

Version(
    tag: str = "",
    date: date | None = None,
    sections: list[Section] | None = None,
    commits: list[Commit] | None = None,
    url: str = "",
    compare_url: str = "",
)

A class to represent a changelog version.

Parameters:

  • tag (str, default: '' ) –

    The version tag.

  • date (date | None, default: None ) –

    The version date.

  • sections (list[Section] | None, default: None ) –

    The version sections.

  • commits (list[Commit] | None, default: None ) –

    The version commits.

  • url (str, default: '' ) –

    The version URL.

  • compare_url (str, default: '' ) –

    The version 'compare' URL.

Methods:

  • add_commit

    Register the given commit and add it to the relevant section based on its message convention.

Attributes:

Source code in src/git_changelog/build.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
def __init__(
    self,
    tag: str = "",
    date: datetime.date | None = None,
    sections: list[Section] | None = None,
    commits: list[Commit] | None = None,
    url: str = "",
    compare_url: str = "",
):
    """Initialization method.

    Arguments:
        tag: The version tag.
        date: The version date.
        sections: The version sections.
        commits: The version commits.
        url: The version URL.
        compare_url: The version 'compare' URL.
    """
    self.tag = tag
    self.date = date

    self.sections_list: list[Section] = sections or []
    self.sections_dict: dict[str, Section] = {section.type: section for section in self.sections_list}
    self.commits: list[Commit] = commits or []
    self.url: str = url
    self.compare_url: str = compare_url
    self.previous_version: Version | None = None
    self.next_version: Version | None = None
    self.planned_tag: str | None = None

is_major property ¤

is_major: bool

Tell if this version is a major one.

Returns:

  • bool

    Whether this version is major.

is_minor property ¤

is_minor: bool

Tell if this version is a minor one.

Returns:

  • bool

    Whether this version is minor.

typed_sections property ¤

typed_sections: list[Section]

Return typed sections only.

Returns:

untyped_section property ¤

untyped_section: Section | None

Return untyped section if any.

Returns:

  • Section | None

    The untyped section if any.

add_commit ¤

add_commit(commit: Commit) -> None

Register the given commit and add it to the relevant section based on its message convention.

Parameters:

  • commit (Commit) –

    The git commit.

Source code in src/git_changelog/build.py
154
155
156
157
158
159
160
161
162
163
164
165
166
167
def add_commit(self, commit: Commit) -> None:
    """Register the given commit and add it to the relevant section based on its message convention.

    Arguments:
        commit: The git commit.
    """
    self.commits.append(commit)
    commit.version = self.tag or "HEAD"
    if commit_type := commit.convention.get("type"):
        if commit_type not in self.sections_dict:
            section = Section(section_type=commit_type)
            self.sections_list.append(section)
            self.sections_dict[commit_type] = section
        self.sections_dict[commit_type].commits.append(commit)

bump ¤

bump(
    version: str,
    part: Literal["major", "minor", "patch"] = "patch",
    *,
    zerover: bool = True
) -> str

Bump a version. Deprecated, use bump_semver instead.

Parameters:

  • version (str) –

    The version to bump.

  • part (Literal['major', 'minor', 'patch'], default: 'patch' ) –

    The part of the version to bump (major, minor, or patch).

  • zerover (bool, default: True ) –

    Keep major version at zero, even for breaking changes.

Returns:

  • str

    The bumped version.

Source code in src/git_changelog/build.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
def bump(version: str, part: Literal["major", "minor", "patch"] = "patch", *, zerover: bool = True) -> str:
    """Bump a version. Deprecated, use [`bump_semver`][git_changelog.versioning.bump_semver] instead.

    Arguments:
        version: The version to bump.
        part: The part of the version to bump (major, minor, or patch).
        zerover: Keep major version at zero, even for breaking changes.

    Returns:
        The bumped version.
    """
    warnings.warn(
        "This function is deprecated in favor of `git_changelog.versioning.bump_semver`",
        DeprecationWarning,
        stacklevel=2,
    )
    return bump_semver(version, part, zerover=zerover)

parse_version ¤

parse_version(version: str) -> tuple[SemVerVersion, str]

Parse a version. Deprecated, use bump_semver instead.

Parameters:

  • version (str) –

    The version to parse.

Returns:

  • semver_version ( SemVerVersion ) –

    The semantic version.

  • prefix ( str ) –

    The version prefix.

Source code in src/git_changelog/build.py
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
def parse_version(version: str) -> tuple[SemVerVersion, str]:
    """Parse a version. Deprecated, use [`bump_semver`][git_changelog.versioning.parse_semver] instead.

    Arguments:
        version: The version to parse.

    Returns:
        semver_version: The semantic version.
        prefix: The version prefix.
    """
    warnings.warn(
        "This function is deprecated in favor of `git_changelog.versioning.parse_semver`",
        DeprecationWarning,
        stacklevel=2,
    )
    return parse_semver(version)