Scroll to navigation

PYTHON-SEMANTIC-RELEASE(1) python-semantic-release PYTHON-SEMANTIC-RELEASE(1)

NAME

python-semantic-release - python-semantic-release Documentation

Automatic Semantic Versioning for Python projects. This is a Python implementation of semantic-release for JS by Stephan Bönnemann. If you find this topic interesting you should check out his talk from JSConf Budapest.

The general idea is to be able to detect what the next version of the project should be based on the commits. This tool will use that to automate the whole release, upload to an artifact repository and post changelogs to GitHub. You can run the tool on a CI service, or just run it locally.

INSTALLATION

python3 -m pip install python-semantic-release
semantic-release --help


Python Semantic Release is also available from conda-forge or as a GitHub Action. Read more about the setup and configuration in our getting started guide.

DOCUMENTATION CONTENTS

Commands

All commands accept a -h/--help option, which displays the help text for the command and exits immediately.

semantic-release does not allow interspersed arguments and options, which means that the options for semantic-release are not necessarily accepted one of the subcommands. In particular, the --noop and -v/--verbose flags must be given to the top-level semantic-release command, before the name of the subcommand.

For example:

Incorrect:

semantic-release version --print --noop -vv


Correct:

semantic-release -vv --noop version --print


With the exception of semantic-release and semantic-release generate-config, all commands require that you have set up your project's configuration. To help with this step, semantic-release generate-config can create the default configuration for you, which will allow you to tweak it to your needs rather than write it from scratch.

semantic-release

Options:

--version

Display the version of Python Semantic Release and exit

--noop

Use this flag to see what semantic-release intends to do without making changes to your project. When using this option, semantic-release can be run as many times as you wish without any side-effects.

-v/--verbose

Can be supplied more than once. Controls the verbosity of semantic-releases logging output (default level is WARNING, use -v for INFO and -vv for DEBUG).

-c/--config [FILE]

Specify the configuration file which Python Semantic Release should use. This can be any of the supported formats valid for -f/--format [FORMAT]

Default: pyproject.toml

SEE ALSO:

Configuration



--strict

Enable Strict Mode. This will cause a number of conditions to produce a non-zero exit code when passed, where they would otherwise have produced an exit code of 0. Enabling this allows, for example, certain conditions to cause failure of a CI pipeline, while omitting this flag would allow the pipeline to continue to run.

SEE ALSO:

Strict Mode



semantic-release version

Detect the semantically correct next version that should be applied to your project.

By default:

  • Write this new version to the project metadata locations specified in the configuration file
  • Build the project using build_command, if specified
  • Create a new commit with these locations and any other assets configured to be included in a release
  • Tag this commit according the configured format, with a tag that uniquely identifies the version being released
  • Push the new tag and commit to the remote for the repository
  • Create a release (if supported) in the remote VCS for this tag



Changelog generation is done identically to the way it is done in semantic-release changelog, but this command additionally ensures the updated changelog is included in the release commit that is made.

SEE ALSO:

  • semantic-release changelog
  • Version Change Reports
  • tag_format
  • assets
  • version_toml
  • version_variables



Options:

--print

Print the next version that will be applied, respecting the other command line options that are supplied, and exit. This flag is useful if you just want to see what the next version will be. Note that instead of printing nothing at all, if no release will be made, the current version is printed.

For example, you can experiment with which versions would be applied using the other command line options:

semantic-release version --print
semantic-release version --patch --print
semantic-release version --prerelease --print


--print-tag

Same as the --print flag but prints the complete tag name (ex. v1.0.0 or py-v1.0.0) instead of the raw version number (1.0.0).

--print-last-released

Print the last released version based on the Git tags. This flag is useful if you just want to see the released version without determining what the next version will be. Note if the version can not be found nothing will be printed.

--print-last-released-tag

Same as the --print-last-released flag but prints the complete tag name (ex. v1.0.0 or py-v1.0.0) instead of the raw version number (1.0.0).

--major/--minor/--patch/--prerelease

Force the next version to increment the major, minor or patch digits, or the prerelease revision, respectively. These flags are optional but mutually exclusive, so only one may be supplied, or none at all. Using these flags overrides the usual calculation for the next version; this can be useful, say, when a project wants to release its initial 1.0.0 version.

WARNING:

Using these flags will override the configured value of prerelease (configured in your Release Group), regardless of your configuration or the current version.

To produce a prerelease with the appropriate digit incremented you should also supply the --as-prerelease flag. If you do not, using these flags will force a full (non-prerelease) version to be created.



For example, suppose your project's current version is 0.2.1-rc.1. The following shows how these options can be combined with --as-prerelease to force different versions:

semantic-release version --prerelease --print
# 0.2.1-rc.2
semantic-release version --patch --print
# 0.2.2
semantic-release version --minor --print
# 0.3.0
semantic-release version --major --print
# 1.0.0
semantic-release version --minor --as-prerelease --print
# 0.3.0-rc.1
semantic-release version --prerelease --as-prerelease --print
# 0.2.1-rc.2


These options are forceful overrides, but there is no action required for subsequent releases performed using the usual calculation algorithm.

Supplying --prerelease will cause Python Semantic Release to scan your project history for any previous prereleases with the same major, minor and patch versions as the latest version and the same prerelease token as the one passed by command-line or configuration. If one is not found, --prerelease will produce the next version according to the following format:

f"{latest_version.major}.{latest_version.minor}.{latest_version.patch}-{prerelease_token}.1"


However, if Python Semantic Release identifies a previous prerelease version with the same major, minor and patch digits as the latest version, and the same prerelease token as the one supplied by command-line or configuration, then Python Semantic Release will increment the revision found on that previous prerelease version in its new version.

For example, if "0.2.1-rc.1" and already exists as a previous version, and the latest version is "0.2.1", invoking the following command will produce "0.2.1-rc.2":

semantic-release version --prerelease --prerelease-token "rc" --print


WARNING:

This is true irrespective of the branch from which "0.2.1-rc.1" was released from. The check for previous prereleases "leading up to" this normal version is intended to help prevent collisions in git tags to an extent, but isn't foolproof. As the example shows it is possible to release a prerelease for a normal version that's already been released when using this flag, which would in turn be ignored by tools selecting versions by SemVer precedence rules.


SEE ALSO:

  • Configuration
  • branches



--as-prerelease

After performing the normal calculation of the next version, convert the resulting next version to a prerelease before applying it. As with --major/--minor/--patch/--prerelease, this option is a forceful override, but no action is required to resume calculating versions as normal on the subsequent releases. The main distinction between --prerelease and --as-prerelease is that the latter will not force a new version if one would not have been released without supplying the flag.

This can be useful when making a single prerelease on a branch that would typically release normal versions.

If not specified in --prerelease-token [VALUE], the prerelease token is idenitified using the Multibranch Release Configuration

See the examples alongside --major/--minor/--patch/--prerelease for how to use this flag.

--prerelease-token [VALUE]

Force the next version to use the value as the prerelease token. This overrides the configured value if one is present. If not used during a release producing a prerelease version, this option has no effect.

--build-metadata [VALUE]

If given, append the value to the newly calculated version. This can be used, for example, to attach a run number from a CI service or a date to the version and tag that are created.

This value can also be set using the environment variable PSR_BUILD_METADATA

For example, assuming a project is currently at version 1.2.3:

$ semantic-release version --minor --print
1.3.0
$ semantic-release version --minor --print --build-metadata "run.12345"
1.3.0+run.12345


--commit/--no-commit

Whether or not to perform a git commit on modifications to source files made by semantic-release during this command invocation, and to run git tag on this new commit with a tag corresponding to the new version.

If --no-commit is supplied, it may disable other options derivatively; please see below.

Default: --commit

SEE ALSO:

tag_format



--tag/--no-tag

Whether or not to perform a git tag to apply a tag of the corresponding to the new version during this command invocation. This option manages the tag application separate from the commit handled by the --commit option.

If --no-tag is supplied, it may disable other options derivatively; please see below.

Default: --tag

--changelog/--no-changelog

Whether or not to update the changelog file with changes introduced as part of the new version released.

Default: --changelog

SEE ALSO:

  • changelog
  • Version Change Reports



--push/--no-push

Whether or not to push new commits and/or tags to the remote repository.

Default: --no-push if --no-commit and --no-tag is also supplied, otherwise push is the default.

--vcs-release/--no-vcs-release

Whether or not to create a "release" in the remote VCS service, if supported. Currently releases in GitHub and Gitea remotes are supported. If releases aren't supported in a remote VCS, this option will not cause a command failure, but will produce a warning.

Default: --no-vcs-release if --no-push is supplied (including where this is implied by supplying only --no-commit), otherwise --vcs-release

--skip-build

If passed, skip execution of the build_command after version stamping and changelog generation.

semantic-release publish

Publish a distribution to a VCS release. Uploads using publish

SEE ALSO:

  • publish
  • build_command



Options:

--tag

The tag associated with the release to publish to. If not given or set to "latest", then Python Semantic Release will examine the Git tags in your repository to identify the latest version, and attempt to publish to a Release corresponding to this version.

Default: "latest"

semantic-release generate-config

Generate default configuration for semantic-release, to help you get started quickly. You can inspect the defaults, write to a file and then edit according to your needs. For example, to append the default configuration to your pyproject.toml file, you can use the following command:

$ semantic-release generate-config -f toml --pyproject >> pyproject.toml


If your project doesn't already leverage TOML files for configuration, it might better suit your project to use JSON instead:

$ semantic-release generate-config -f json


If you would like to add JSON configuration to a shared file, e.g. package.json, you can then simply add the output from this command as a top-level key to the file.

Note: Because there is no "null" or "nil" concept in TOML (see the relevant GitHub issue), configuration settings which are None by default are omitted from the default configuration.

SEE ALSO:

Configuration



Options:

-f/--format [FORMAT]

The format that the default configuration should be generated in. Valid choices are toml and json (case-insensitive).

Default: toml

--pyproject

If used alongside --format json, this option has no effect. When using --format=toml, if specified the configuration will sit under a top-level key of tool.semantic_release to comply with PEP 518; otherwise, the configuration will sit under a top-level key of semantic_release.

semantic-release changelog

Generate and optionally publish a changelog for your project. The changelog is generated based on a template which can be customized.

Python Semantic Release uses Jinja as its templating engine; as a result templates need to be written according to the Template Designer Documentation.

SEE ALSO:

  • changelog
  • environment
  • Version Change Reports



Options:

--post-to-release-tag [TAG]

If supplied, attempt to find a release in the remote VCS corresponding to the Git tag TAG, and post the generated changelog to that release. If the tag exists but no corresponding release is found in the remote VCS, then Python Semantic Release will attempt to create one.

If using this option, the relevant authentication token must be supplied via the relevant environment variable. For more information, see Creating VCS Releases.

Strict Mode

Strict Mode is enabled by use of the strict parameter to the main command for Python Semantic Release. Strict Mode alters the behaviour of Python Semantic Release when certain conditions are encountered that prevent Python Semantic Release from performing an action. Typically, this will result in a warning becoming an error, or a different exit code (0 vs non-zero) being produced when Python Semantic Release exits early.

For example:

#!/usr/bin/bash
set -euo pipefail
git checkout $NOT_A_RELEASE_BRANCH
pip install \

black \
isort \
twine \
pytest \
python-semantic-release isort . # sort imports black . # format the code pytest # test the code semantic-release --strict version # ERROR - not a release branch twine upload dist/* # publish the code


Using Strict Mode with the --strict flag ensures this simple pipeline will fail while running semantic-release, as the non-zero exit code will cause it to stop when combined with the -e option.

Without Strict Mode, the semantic-release command will exit with code 0, causing the above pipeline to continue.

The specific effects of enabling Strict Mode are detailed below.

Non-Release Branches

When running in Strict Mode, invoking Python Semantic Release on a non-Release branch will cause an error with a non-zero exit code. This means that you can prevent an automated script from running further against branches you do not want to release from, for example in multibranch CI pipelines.

Running without Strict Mode will allow subsequent steps in the pipeline to also execute, but be aware that certain actions that Python Semantic Release may perform for you will likely not have been carried out, such as writing to files or creating a git commit in your repository.

SEE ALSO:

Multibranch Releases



Version Already Released/No Release To Be Made

When Strict Mode is not enabled and Python Semantic Release identifies that no release needs to be made, it will exit with code 0. You can cause Python Semantic Release to raise an error if no release needs to be made by enabling Strict Mode.

Configuration

Configuration is read from a file which can be specified using the \\-\\-config option to semantic-release. Python Semantic Release currently supports a configuration in either TOML or JSON format, and will attempt to auto-detect and parse either format.

When using a JSON-format configuration file, Python Semantic Release looks for its settings beneath a top-level semantic_release key; when using a TOML-format configuration file, Python Semantic Release first checks for its configuration under the table [tool.semantic_release] (in line with the convention for Python tools to require their configuration under the top-level tool table in their pyproject.toml file), followed by [semantic_release], which may be more desirable if using a file other than the default pyproject.toml for configuration.

The examples on this page are given in TOML format, however there is no limitation on using JSON instead. In fact, if you would like to convert any example below to its JSON equivalent, the following commands will do this for you (in Bash):

export TEXT="<the TOML to convert>"
cat <<EOF | python3
import tomlkit, json
print(json.dumps(tomlkit.loads('''$TEXT'''), indent=4))
EOF


A note on null

In TOML, there is no such thing as a "null" or "nil" value, and this isn't planned as a language feature according to the relevant GitHub issue. In Python Semantic Release, options which default to None are inferred from the relevant configuration settings not being present at all in your configuration. Because of this limitation, it's currently not possible to explicitly specify those settings as "null" in TOML-format configuration. Technically it is possible in JSON-format configuration, but it's recommended to keep consistency and just omit the relevant settings.

Environment Variables

Some settings are best pulled from environment variables rather than being stored in plaintext in your configuration file. Python Semantic Release can be configured to look for an environment variable value to use for a given setting, but this feature is not available for all settings. In order to use an environment variable for a setting, you must indicate in your configuration file the name of the environment variable to use.

The traditional and most common use case for environment variable use is for passing authentication tokens to Python Semantic Release. You do NOT want to hard code your authentication token in your configuration file, as this is a security risk. A plaintext token in your configuration file could be exposed to anyone with access to your repository, including long after its deleted if a token is in your git history. Instead, define the name of the environment variable which contains your remote.token, such as GH_TOKEN, in your configuration file, and Python Semantic Release will do the rest, as seen below.

[semantic_release.remote.token]
env = "GH_TOKEN"


Given basic TOML syntax compatibility, this is equivalent to:

[semantic_release.remote]
token = { env = "GH_TOKEN" }


The general format for specifying that some configuration should be sourced from an environment variable is:

[semantic_release.variable]
env = "ENV_VAR"
default_env = "FALLBACK_ENV_VAR"
default = "default value"


  • env represents the environment variable that Python Semantic Release will search for
  • default_env is a fallback environment variable to read in case the variable specified by env is not set. This is optional - if not specified then no fallback will be used.
  • default is a default value to use in case the environment variable specified by env is not set. This is optional - if default is not specified then the environment variable specified by env is considered required.


semantic_release settings

The following sections outline all the definitions and descriptions of each supported configuration setting. If there are type mis-matches, PSR will throw validation errors upon load. If a setting is not provided, than PSR will fill in the value with the default value.

Python Semantic Release expects a root level key to start the configuration definition. Make sure to use the correct root key dependending on the configuration format you are using.

NOTE:

If you are using pyproject.toml, this heading should include the tool prefix as specified within PEP 517, resulting in [tool.semantic_release].


NOTE:

If you are using a releaserc.toml, use [semantic_release] as the root key


NOTE:

If you are using a releaserc.json, semantic_release must be the root key in the top level dictionary.



----



allow_zero_version

Introduced in v9.2.0

Type: bool

This flag controls whether or not Python Semantic Release will use version numbers aligning with the 0.x.x pattern.

If set to true and starting at 0.0.0, a minor bump would set the next version as 0.1.0 whereas a patch bump would set the next version as 0.0.1. A breaking change (ie. major bump) would set the next version as 1.0.0 unless the major_on_zero is set to false.

If set to false, Python Semantic Release will consider the first possible version to be 1.0.0, regardless of patch, minor, or major change level. Additionally, when allow_zero_version is set to false, the major_on_zero setting is ignored.

Default: true


----



assets

Type: list[str]

One or more paths to additional assets that should committed to the remote repository in addition to any files modified by writing the new version.

Default: []


----



branches

This setting is discussed in more detail at Multibranch Releases

Default:

[semantic_release.branches.main]
match = "(main|master)"
prerelease_token = "rc"
prerelease = false



----



build_command

Type: Optional[str]

Command to use to build the current project during semantic-release version.

Python Semantic Release will execute the build command in the OS default shell with a subset of environment variables. PSR provides the variable NEW_VERSION in the environment with the value of the next determined version. The following table summarizes all the environment variables that are passed on to the build_command runtime if they exist in the parent process.

If you would like to pass additional environment variables to your build command, see build_command_env.

Variable Name Description
CI Pass-through true if exists in process env, unset otherwise
BITBUCKET_CI true if Bitbucket CI variables exist in env, unset otherwise
GITHUB_ACTIONS Pass-through true if exists in process env, unset otherwise
GITEA_ACTIONS Pass-through true if exists in process env, unset otherwise
GITLAB_CI Pass-through true if exists in process env, unset otherwise
HOME Pass-through HOME of parent process
NEW_VERSION Semantically determined next version (ex. 1.2.3)
PATH Pass-through PATH of parent process
PSR_DOCKER_GITHUB_ACTION Pass-through true if exists in process env, unset otherwise
VIRTUAL_ENV Pass-through VIRTUAL_ENV if exists in process env, unset otherwise

In addition, on windows systems these environment variables are passed:

Variable Name Description
ALLUSERSAPPDATA Pass-through ALLUSERAPPDATA if exists in process env, unset otherwise
ALLUSERSPROFILE Pass-through ALLUSERSPPPROFILE if exists in process env, unset otherwise
APPDATA Pass-through APPDATA if exists in process env, unset otherwise
COMMONPROGRAMFILES Pass-through COMMONPROGRAMFILES if exists in process env, unset otherwise
COMMONPROGRAMFILES(X86) Pass-through COMMONPROGRAMFILES(X86) if exists in process env, unset otherwise
DEFAULTUSERPROFILE Pass-through DEFAULTUSERPROFILE if exists in process env, unset otherwise
HOMEPATH Pass-through HOMEPATH if exists in process env, unset otherwise
PATHEXT Pass-through PATHEXT if exists in process env, unset otherwise
PROFILESFOLDER Pass-through PROFILESFOLDER if exists in process env, unset otherwise
PROGRAMFILES Pass-through PROGRAMFILES if exists in process env, unset otherwise
PROGRAMFILES(X86) Pass-through PROGRAMFILES(X86) if exists in process env, unset otherwise
SYSTEM Pass-through SYSTEM if exists in process env, unset otherwise
SYSTEM16 Pass-through SYSTEM16 if exists in process env, unset otherwise
SYSTEM32 Pass-through SYSTEM32 if exists in process env, unset otherwise
SYSTEMDRIVE Pass-through SYSTEMDRIVE if exists in process env, unset otherwise
SYSTEMROOT Pass-through SYSTEMROOT if exists in process env, unset otherwise
TEMP Pass-through TEMP if exists in process env, unset otherwise
TMP Pass-through TMP if exists in process env, unset otherwise
USERPROFILE Pass-through USERPROFILE if exists in process env, unset otherwise
USERSID Pass-through USERSID if exists in process env, unset otherwise
WINDIR Pass-through WINDIR if exists in process env, unset otherwise

Default: None (not specified)


----



build_command_env

Introduced in v9.7.2

Type: Optional[list[str]]

List of environment variables to include or pass-through on to the build command that executes during semantic-release version.

This configuration option allows the user to extend the list of environment variables from the table above in build_command. The input is a list of strings where each individual string handles a single variable definition. There are two formats accepted and are detailed in the following table:

FORMAT Description
VAR_NAME Detects value from the PSR process environment, and passes value to build_command process
VAR_NAME=value Sets variable name to value inside of build_command process

NOTE:

Although variable name capitalization is not required, it is recommended as to be in-line with the POSIX-compliant recommendation for shell variable names.


Default: None (not specified)


----



changelog

This section outlines the configuration options available that modify changelog generation.

NOTE:

pyproject.toml: [tool.semantic_release.changelog]

releaserc.toml: [semantic_release.changelog]

releaserc.json: { "semantic_release": { "changelog": {} } }




----



changelog_file

WARNING:

Deprecated in v9.11.0. This setting has been moved to changelog.default_templates.changelog_file for a more logical grouping. This setting will be removed in a future major release.


Type: str

Specify the name of the changelog file that will be created. This file will be created or overwritten (if it previously exists) with the rendered default template included with Python Semantic Release.

Depending on the file extension of this setting, the changelog will be rendered in the format designated by the extension. PSR, as of v9.11.0, provides a default changelog template in both Markdown (.md) and reStructuredText (.rst) formats. If the file extension is not recognized, the changelog will be rendered in Markdown format, unless the output_format setting is set.

If you are using the template_dir setting for providing customized templates, this setting is not used. See template_dir for more information.

Default: "CHANGELOG.md"


----



default_templates

NOTE:

This section of the configuration contains options which customize or modify the default changelog templates included with PSR.

pyproject.toml: [tool.semantic_release.changelog.default_templates]

releaserc.toml: [semantic_release.changelog.default_templates]

releaserc.json: { "semantic_release": { "changelog": { "default_templates": {} } } }




----



changelog_file

Introduced in v9.11.0.

Type: str

Specify the name of the changelog file that will be created. This file will be created or overwritten (if it previously exists) with the rendered default template included with Python Semantic Release.

Depending on the file extension of this setting, the changelog will be rendered in the format designated by the extension. PSR, as of v9.11.0, provides a default changelog template in both Markdown (.md) and reStructuredText (.rst) formats. If the file extension is not recognized, the changelog will be rendered in Markdown format, unless the output_format setting is set.

If you are using the template_dir setting for providing customized templates, this setting is not used. See template_dir for more information.

Default: "CHANGELOG.md"


----



mask_initial_release

Introduced in v9.14.0

Type: bool

This option toggles the behavior of the changelog and release note templates to mask the release details specifically for the first release. When set to true, the first version release notes will be masked with a generic message as opposed to the usual commit details. When set to false, the release notes will be generated as normal.

The reason for this setting is to improve clarity to your audience. It conceptually does NOT make sense to have a list of changes (i.e. a Changelog) for the first release since nothing has been published yet, therefore in the eyes of your consumers what change is there to document?

The message details can be found in the first_release.md.j2 and first_release.rst.j2 templates of the default changelog template directory.

Default: false

SEE ALSO:

Using the Default Changelog




----



output_format

Introduced in v9.10.0

Type: Literal["md", "rst"]

This setting is used to specify the output format the default changelog template will use when rendering the changelog. PSR supports both Markdown (md) and reStructuredText (rst) formats.

This setting will take presendence over the file extension of the changelog_file setting. If this setting is omitted, the file extension of the changelog_file setting will be used to determine the output format. If the file extension is not recognized, the output format will default to Markdown.

Default: "md"

SEE ALSO:

changelog_file




----



environment

NOTE:

This section of the configuration contains options which customize the template environment used to render templates such as the changelog. Most options are passed directly to the jinja2.Environment constructor, and further documentation one these parameters can be found there.
pyproject.toml: [tool.semantic_release.changelog.environment]

releaserc.toml: [semantic_release.changelog.environment]

releaserc.json: { "semantic_release": { "changelog": { "environment": {} } } }






----



autoescape

Type: Union[str, bool]

If this setting is a string, it should be given in module:attr form; Python Semantic Release will attempt to dynamically import this string, which should represent a path to a suitable callable that satisfies the following:

As of Jinja 2.4 this can also be a callable that is passed the template name and has to return true or false depending on autoescape should be enabled by default.


The result of this dynamic import is passed directly to the jinja2.Environment constructor.

If this setting is a boolean, it is passed directly to the jinja2.Environment constructor.

Default: false


----



block_start_string

Type: str

This setting is passed directly to the jinja2.Environment constructor.

Default: "{%"


----



block_end_string

Type: str

This setting is passed directly to the jinja2.Environment constructor.

Default: "%}"


----



comment_start_string

Type: str

This setting is passed directly to the jinja2.Environment constructor.

Default: {#


----



comment_end_string

Type: str

This setting is passed directly to the jinja2.Environment constructor.

Default: "#}"


----



extensions

Type: list[str]

This setting is passed directly to the jinja2.Environment constructor.

Default: []


----



keep_trailing_newline

Type: bool

This setting is passed directly to the jinja2.Environment constructor.

Default: false


----



line_comment_prefix

Type: Optional[str]

This setting is passed directly to the jinja2.Environment constructor.

Default: None (not specified)


----



line_statement_prefix

Type: Optional[str]

This setting is passed directly to the jinja2.Environment constructor.

Default: None (not specified)


----



lstrip_blocks

Type: bool

This setting is passed directly to the jinja2.Environment constructor.

Default: false


----



newline_sequence

Type: Literal["\n", "\r", "\r\n"]

This setting is passed directly to the jinja2.Environment constructor.

Default: "\n"


----



trim_blocks

Type: bool

This setting is passed directly to the jinja2.Environment constructor.

Default: false


----



variable_start_string

Type: str

This setting is passed directly to the jinja2.Environment constructor.

Default: "{{"


----



variable_end_string

Type: str

This setting is passed directly to the jinja2.Environment constructor.

Default: "}}"


----



exclude_commit_patterns

Type: list[str]

Any patterns specified here will be excluded from the commits which are available to your changelog. This allows, for example, automated commits to be removed if desired. Python Semantic Release also removes its own commits from the Changelog via this mechanism; therefore if you change the automated commit message that Python Semantic Release uses when making commits, you may wish to add the old commit message pattern here.

The patterns in this list are treated as regular expressions.

Default: []


----



mode

Introduced in v9.10.0

Type: Literal["init", "update"]

This setting is a flag that is ultimately passed into the changelog context environment. It sets the value of context.changelog_mode to a string value of either init or update.

When used with the provided changelog template, it will determine the behavior of how the changelog is written. When the mode is set to init, the changelog file will be written from scratch, overwriting any existing changelog file. This is the v8 and v9 default behavior.

When the mode is set to update, the changelog file will look for the insertion_flag value in the changelog file (defined by changelog_file) and insert the new version information at that location.

If you are using a custom template directory, the context.changelog_mode value will exist in the changelog context but it is up to your implementation to determine if and/or how to use it.

Default: init

SEE ALSO:

Using the Default Changelog




----



insertion_flag

Introduced in v9.10.0

Type: str

A string that will be used to identify where the new version should be inserted into the changelog file (as defined by changelog_file) when the changelog mode is set to update.

When the changelog mode is set to init, this string will be included as part of the header of the changelog file to initialize the changelog with a format that will be condusive for future version insertions.

If you modify this value in your config, you will need to manually update any saved changelog file to match the new insertion flag if you use the update mode. In init mode, the changelog file will be overwritten as normal.

In v9.11.0, the insertion_flag default value became more dynamic with the introduction of an reStructuredText template. The default value will be set depending on the output_format setting. The default flag values are:

Output Format Default Insertion Flag
Markdown (md) <!-- version list -->
reStructuredText ..\n version list

Default: various, see above


----



template_dir

Type: str

When files exist within the specified directory, they will be used as templates for the changelog rendering process. Regardless if the directory includes a changelog file, the provided directory will be rendered and files placed relative to the root of the project directory.

No default changelog template or release notes template will be used when this directory exists and the directory is not empty. If the directory is empty, the default changelog template will be used.

This option is discussed in more detail at Version Change Reports

Default: "templates"


----



commit_author

Type: str

Author used in commits in the format name <email>.

NOTE:

If you are using the built-in GitHub Action, the default value is set to github-actions <actions@github.com>. You can modify this with the git_committer_name and git_committer_email inputs.


SEE ALSO:

GitHub Actions



Default: semantic-release <semantic-release>


----



commit_message

Type: str

Commit message to use when making release commits. The message can use {version} as a format key, in which case the version being released will be formatted into the message.

If at some point in your project's lifetime you change this, you may wish to consider, adding the old message pattern(s) to exclude_commit_patterns.

Default: "{version}\n\nAutomatically generated by python-semantic-release"


----



commit_parser

Type: str

Specify which commit parser Python Semantic Release should use to parse the commits within the Git repository.

  • angular - AngularCommitParser
  • emoji - EmojiCommitParser
  • scipy - ScipyCommitParser
  • tag - TagCommitParser (deprecated in v9.12.0)


You can set any of the built-in parsers by their keyword but you can also specify your own commit parser in module:attr form.

For more information see Commit Parsing.

Default: "angular"


----



commit_parser_options

Type: dict[str, Any]

These options are passed directly to the parser_options method of the commit parser, without validation or transformation.

For more information, see Parser Options.

The default value for this setting depends on what you specify as commit_parser. The table below outlines the expections from commit_parser value to default options value.

commit_parser Default commit_parser_options
"angular" -> 0.0 3.5 [semantic_release.commit_parser_options] allowed_types = [ "build", "chore", "ci", "docs", "feat", "fix", "perf", "style", "refactor", "test" ] minor_types = ["feat"] patch_types = ["fix", "perf"] 168u 168u
"emoji" -> 0.0 3.5 [semantic_release.commit_parser_options] major_tags = [":boom:"] minor_tags = [ ":sparkles:", ":children_crossing:", ":lipstick:", ":iphone:", ":egg:", ":chart_with_upwards_trend:" ] patch_tags = [ ":ambulance:", ":lock:", ":bug:", ":zap:", ":goal_net:", ":alien:", ":wheelchair:", ":speech_balloon:", ":mag:", ":apple:", ":penguin:", ":checkered_flag:", ":robot:", ":green_apple:" ] 168u 168u
"scipy" -> 0.0 3.5 [semantic_release.commit_parser_options] allowed_tags = [ "API", "DEP", "ENH", "REV", "BUG", "MAINT", "BENCH", "BLD", "DEV", "DOC", "STY", "TST", "REL", "FEAT", "TEST", ] major_tags = ["API",] minor_tags = ["DEP", "DEV", "ENH", "REV", "FEAT"] patch_tags = ["BLD", "BUG", "MAINT"] 168u 168u
"tag" -> 0.0 3.5 [semantic_release.commit_parser_options] minor_tag = ":sparkles:" patch_tag = ":nut_and_bolt:" 168u 168u
"module:class" -> **module:class.parser_options()

Default: ParserOptions { ... }, where ... depends on commit_parser as indicated above.


----



logging_use_named_masks

Type: bool

Whether or not to replace secrets identified in logging messages with named masks identifying which secrets were replaced, or use a generic string to mask them.

Default: false


----



major_on_zero

Type: bool

This flag controls whether or not Python Semantic Release will increment the major version upon a breaking change when the version matches 0.y.z. This value is set to true by default, where breaking changes will increment the 0 major version to 1.0.0 like normally expected.

If set to false, major (breaking) releases will increment the minor digit of the version while the major version is 0, instead of the major digit. This allows for continued breaking changes to be made while the major version remains 0.

From the Semantic Versioning Specification:

Major version zero (0.y.z) is for initial development. Anything MAY change at any time. The public API SHOULD NOT be considered stable.


When you are ready to release a stable version, set major_on_zero to true and run Python Semantic Release again. This will increment the major version to 1.0.0.

When allow_zero_version is set to false, this setting is ignored.

Default: true


----



no_git_verify

Introduced in v9.8.0

Type: bool

This flag is passed along to git upon performing a git commit during semantic-release version.

When true, it will bypass any git hooks that are set for the repository when Python Semantic Release makes a version commit. When false, the commit is performed as normal. This option has no effect when there are not any git hooks configured nor when the --no-commit option is passed.

Default: false


----



publish

This section defines configuration options that modify semantic-release publish.

NOTE:

pyproject.toml: [tool.semantic_release.publish]

releaserc.toml: [semantic_release.publish]

releaserc.json: { "semantic_release": { "publish": {} } }




----



dist_glob_patterns

Type: list[str]

Upload any files matching any of these globs to your VCS release. Each item in this list should be a string containing a Unix-style glob pattern.

Default: ["dist/*"]


----



upload_to_vcs_release

Type: bool

If set to true, upload any artifacts matched by the dist_glob_patterns to the release created in the remote VCS corresponding to the latest tag. Artifacts are only uploaded if release artifact uploads are supported by the VCS type.

Default: true


----



remote

The remote configuration is a group of settings that configure PSR's integration with remote version control systems.

NOTE:

pyproject.toml: [tool.semantic_release.remote]

releaserc.toml: [semantic_release.remote]

releaserc.json: { "semantic_release": { "remote": {} } }




----



api_domain

Type: Optional[str | Dict['env', str]]

The hosting domain for the API of your remote HVCS if different than the domain. Generally, this will be used to specify a separate subdomain that is used for API calls rather than the primary domain (ex. api.github.com).

Most on-premise HVCS installations will NOT use this setting! Whether or not this value is used depends on the HVCS configured (and your server administration) in the remote.type setting and used in tadem with the remote.domain setting.

When using a custom remote.domain and a HVCS remote.type that is configured with a separate domain or sub-domain for API requests, this value is used to configure the location of API requests that are sent from PSR.

Most on-premise or self-hosted HVCS environments will use a path prefix to handle inbound API requests, which means this value will ignored.

PSR knows the expected api domains for known cloud services and their associated api domains which means this value is not necessary to explicitly define for services as bitbucket.org, and github.com.

Including the protocol schemes, such as https://, for the API domain is optional. Secure HTTPS connections are assumed unless the setting of remote.insecure is true.

Default: None


----



domain

Type: Optional[str | Dict['env', str]]

The host domain for your HVCS server. This setting is used to support on-premise installations of HVCS providers with custom domain hosts.

If you are using the official domain of the associated remote.type, this value is not required. PSR will use the default domain value for the remote.type when not specified. For example, when remote.type="github" is specified the default domain of github.com is used.

Including the protocol schemes, such as https://, for the domain value is optional. Secure HTTPS connections are assumed unless the setting of remote.insecure is true.

This setting also supports reading from an environment variable for ease-of-use in CI pipelines. See Environment Variable for more information. Depending on the remote.type, the default environment variable for the default domain's CI pipeline environment will automatically be checked so this value is not required in default environments. For example, when remote.type="gitlab" is specified, PSR will look to the CI_SERVER_URL environment variable when remote.domain is not specified.

Default: None

SEE ALSO:

remote.api_domain




----



ignore_token_for_push

Type: bool

If set to true, ignore the authentication token when pushing changes to the remote. This is ideal, for example, if you already have SSH keys set up which can be used for pushing.

Default: false


----



insecure

Introduced in v9.4.2

Type: bool

Insecure is used to allow non-secure HTTP connections to your HVCS server. If set to true, any domain value passed will assume http:// if it is not specified and allow it. When set to false (implicitly or explicitly), it will force https:// communications.

When a custom domain or api_domain is provided as a configuration, this flag governs the protocol scheme used for those connections. If the protocol scheme is not provided in the field value, then this insecure option defines whether HTTP or HTTPS is used for the connection. If the protocol scheme is provided in the field value, it must match this setting or it will throw an error.

The purpose of this flag is to prevent any typos in provided domain and api_domain values that accidently specify an insecure connection but allow users to toggle the protection scheme off when desired.

Default: false


----



name

Type: str

Name of the remote to push to using git push -u $name <branch_name>

Default: "origin"


----



token

Type: Optional[str | Dict['env', str]]

Environment Variable from which to source the authentication token for the remote VCS. Common examples include "GH_TOKEN", "GITLAB_TOKEN" or "GITEA_TOKEN", however, you may choose to use a custom environment variable if you wish.

NOTE:

By default, this is a mandatory environment variable that must be set before using any functionality that requires authentication with your remote VCS. If you are using this token to enable push access to the repository, it must also be set before attempting to push.

If your push access is enabled via SSH keys instead, then you do not need to set this environment variable in order to push the version increment, changelog and modified source code assets to the remote using semantic-release version. However, you will need to disable release creation using the --vcs-release/--no-vcs-release option, among other options, in order to use Python Semantic Release without configuring the environment variable for your remote VCS authentication token.



The default value for this setting depends on what you specify as remote.type. Review the table below to see what the default token value will be for each remote type.

remote.type Default remote.token
"github" -> { env = "GH_TOKEN" }
"gitlab" -> { env = "GITLAB_TOKEN" }
"gitea" -> { env = "GITEA_TOKEN" }
"bitbucket" -> { env = "BITBUCKET_TOKEN" }

Default: { env = "<envvar name>" }, where <envvar name> depends on remote.type as indicated above.


----



type

Type: Literal["bitbucket", "gitea", "github", "gitlab"]

The type of the remote VCS. Currently, Python Semantic Release supports "github", "gitlab", "gitea" and "bitbucket". Not all functionality is available with all remote types, but we welcome pull requests to help improve this!

Default: "github"


----



url

Type: Optional[str | Dict['env', str]]

An override setting used to specify the remote upstream location of git push.

Not commonly used! This is used to override the derived upstream location when the desired push location is different than the location the repository was cloned from.

This setting will override the upstream location url that would normally be derived from the remote.name location of your git repository.

Default: None


----



tag_format

Type: str

Specify the format to be used for the Git tag that will be added to the repo during a release invoked via semantic-release version. The format string is a regular expression, which also must include the format keys below, otherwise an exception will be thrown. It may include any of the optional format keys, in which case the contents described will be formatted into the specified location in the Git tag that is created.

For example, "(dev|stg|prod)-v{version}" is a valid tag_format matching tags such as:

  • dev-v1.2.3
  • stg-v0.1.0-rc.1
  • prod-v2.0.0+20230701

This format will also be used for parsing tags already present in the repository into semantic versions; therefore if the tag format changes at some point in the repository's history, historic versions that no longer match this pattern will not be considered as versions.

Format Key Mandatory Contents
{version} Yes The new semantic version number, for example 1.2.3, or 2.1.0-alpha.1+build.1234

Tags which do not match this format will not be considered as versions of your project.

Default: "v{version}"


----



version_toml

Type: list[str]

Similar to version_variables, but allows the version number to be identified safely in a toml file like pyproject.toml, with each entry using dotted notation to indicate the key for which the value represents the version:

[semantic_release]
version_toml = [

"pyproject.toml:tool.poetry.version", ]


Default: []


----



version_variables

Type: list[str]

Each entry represents a location where the version is stored in the source code, specified in file:variable format. For example:

[semantic_release]
version_variables = [

"src/semantic_release/__init__.py:__version__",
"docs/conf.py:version", ]


Each version variable will be transformed into a Regular Expression that will be used to substitute the version number in the file. The replacement algorithm is ONLY a pattern match and replace. It will NOT evaluate the code nor will PSR understand any internal object structures (ie. file:object.version will not work).

IMPORTANT:

The Regular Expression expects a version value to exist in the file to be replaced. It cannot be an empty string or a non-semver compliant string. If this is the very first time you are using PSR, we recommend you set the version to 0.0.0. This may become more flexible in the future with resolution of issue #941.


Given the pattern matching nature of this feature, the Regular Expression is able to support most file formats as a variable declaration in most languages is very similar. We specifically support Python, YAML, and JSON as these have been the most common requests. This configuration option will also work regardless of file extension because its only a pattern match.

NOTE:

This will also work for TOML but we recommend using version_toml for TOML files as it actually will interpret the TOML file and replace the version number before writing the file back to disk.


WARNING:

If the file (ex. JSON) you are replacing has two of the same variable name in it, this pattern match will not be able to differentiate between the two and will replace both. This is a limitation of the pattern matching and not a bug.


Default: []

Commit Parsing

One of the core components of Python Semantic Release (PSR) is the commit parser. The commit parser is responsible for parsing a Project's Git Repository commit history to extract insights about project changes and make decisions based on this insight.

The primary decision that PSR makes based on the commit history is whether or not to release a new version of the project, and if so, what version number to release. This decision is made based on the commit message descriptions of the change impact introduced by the commit. The change impact describes the impact to the end consumers of the project. Depending on the type of change, the version number will be incremented according to the Semantic Versioning specification (semver). It is the commit parser's job to extract the change impact from the commit message to determine the severity of the changes and then subsequently determine the semver level that the version should be bumped to for the next release.

The commit parser is also responsible for interpreting other aspects of the commit message which can be used to generate a helpful and detailed changelog. This includes extracting the type of change, the scope of the change, any breaking change descriptions, any linked pull/merge request numbers, and any linked issue numbers.

PSR provides several built-in commit parsers to handle a variety of different commit message styles. If the built-in parsers do not meet your needs, you can write your own custom parser to handle your specific commit message style.

WARNING:

PSR's built-in commit parsers are designed to be flexible enough to provide a convenient way to generate the most effective changelogs we can, which means some features are added beyond the scope of the original commit message style guidelines.

Other tools may not follow the same conventions as PSR's guideline extensions, so if you plan to use any similar programs in tadem with PSR, you should be aware of the differences in feature support and fall back to the official format guidelines if necessary.




----



Built-in Commit Parsers

The following parsers are built in to Python Semantic Release:

  • AngularCommitParser
  • EmojiCommitParser
  • ScipyCommitParser
  • TagCommitParser (deprecated in v9.12.0)


----



Angular Commit Parser

A parser that is designed to parse commits formatted according to the Angular Commit Style Guidelines. The parser is implemented with the following logic in relation to how PSR's core features:

  • Version Bump Determination: This parser extracts the commit type from the subject line of the commit (the first line of a commit messsage). This type is matched against the configuration mapping to determine the level bump for the specific commit. If the commit type is not found in the configuration mapping, the commit is considered a non-conformative commit and will return it as a ParseError object and ultimately a commit of type "unknown". The configuration mapping contains lists of commit types that correspond to the level bump for each commit type. Some commit types are still valid do not trigger a level bump, such as "chore" or "docs". You can also configure the default level bump commit_parser_options.default_level_bump if desired. To trigger a major release, the commit message body must contain a paragraph that begins with BREAKING CHANGE:. This will override the level bump determined by the commit type.
  • Changelog Generation: PSR will group commits in the changelog by the commit type used in the commit message. The commit type shorthand is converted to a more human-friendly section heading and then used as the version section title of the changelog and release notes. Under the section title, the parsed commit descriptions are listed out in full. If the commit includes an optional scope, then the scope is prefixed on to the first line of the commit description. If a commit has any breaking change prefixed paragraphs in the commit message body, those paragraphs are separated out into a "Breaking Changes" section in the changelog (Breaking Changes section is available from the default changelog in v9.15.0). Each breaking change paragraph is listed in a bulleted list format across the entire version. A single commit is allowed to have more than one breaking change prefixed paragraph (as opposed to the Angular Commit Style Guidelines). Commits with an optional scope and a breaking change will have the scope prefixed on to the breaking change paragraph. Parsing errors will return a ParseError object and ultimately a commit of type "unknown". Unknown commits are consolidated into an "Unknown" section in the changelog by the default template. To remove unwanted commits from the changelog that normally are placed in the "unknown" section, consider the use of the configuration option changelog.exclude_commit_patterns to ignore those commit styles.
  • Pull/Merge Request Identifier Detection: This parser implements PSR's Common Linked Merge Request Detection to identify and extract pull/merge request numbers. The parser will return a string value if a pull/merge request number is found in the commit message. If no pull/merge request number is found, the parser will return an empty string. Feature available in v9.13.0+.
  • Linked Issue Identifier Detection: This parser implements PSR's Common Issue Identifier Detection to identify and extract issue numbers. The parser will return a tuple of issue numbers as strings if any are found in the commit message. If no issue numbers are found, the parser will return an empty tuple. Feature available in v9.15.0+.

Limitations:

  • Squash commits are not currently supported. This means that the level bump for a squash commit is only determined by the subject line of the squash commit. Our default changelog template currently writes out the entire commit message body in the changelog in order to provide the full detail of the changes. Track the implementation of this feature with the issues #733, #1085, and PR#1112.
  • Commits with the revert type are not currently supported. Track the implementation of this feature in the issue #402.

If no commit parser options are provided via the configuration, the parser will use PSR's built-in defaults.


----



Emoji Commit Parser

A parser that is designed to parse commits formatted to the Gitmoji Specification with a few additional features that the specification does not cover but provide similar functionality expected from a Semantic Release tool. As the Gitmoji Specification describes, the emojis can be specified in either the unicode format or the shortcode text format. See the Gitmoji Specification for the pros and cons for which format to use, but regardless, the configuration options must match the format used in the commit messages. The parser is implemented with the following logic in relation to how PSR's core features:

  • Version Bump Determination: This parser only looks for emojis in the subject line of the commit (the first line of a commit messsage). If more than one emoji is found, the emoji configured with the highest priority is selected for the change impact for the specific commit. The emoji with the highest priority is the one configured in the major configuration option, followed by the minor, and patch in descending priority order. If no emoji is found in the subject line, the commit is classified as other and will default to the level bump defined by the configuration option commit_parser_options.default_level_bump.
  • Changelog Generation: PSR will group commits in the changelog by the emoji type used in the commit message. The emoji is used as the version section title and the commit descriptions are listed under that section. No emojis are removed from the commit message so each will be listed in the changelog and release notes. When more than one emoji is found in the subject line of a commit, the emoji with the highest priority is the one that will influence the grouping of the commit in the changelog. Commits containing no emojis or non-configured emojis are consolidated into an "Other" section. To remove unwanted commits from the changelog that would normally be added into the "other" section, consider the use of the configuration option changelog.exclude_commit_patterns to ignore those commit styles.
  • Pull/Merge Request Identifier Detection: This parser implements PSR's Common Linked Merge Request Detection to identify and extract pull/merge request numbers. The parser will return a string value if a pull/merge request number is found in the commit message. If no pull/merge request number is found, the parser will return an empty string. Feature available in v9.13.0+.
  • Linked Issue Identifier Detection: [Disabled by default] This parser implements PSR's Common Issue Identifier Detection to identify and extract issue numbers. The parser will return a tuple of issue numbers as strings if any are found in the commit message. If no issue numbers are found, the parser will return an empty tuple. This feature is disabled by default since it is not a part of the Gitmoji Specification but can be enabled by setting the configuration option commit_parser_options.parse_linked_issues to true. Feature available in v9.15.0+.

If no commit parser options are provided via the configuration, the parser will use PSR's built-in defaults.


----



Scipy Commit Parser

A parser that is designed to parse commits formatted according to the Scipy Commit Style Guidlines. This is essentially a variation of the Angular Commit Style Guidelines with all different commit types. Because of this small variance, this parser only extends our Angular Commit Parser parser with pre-defined scipy commit types in the default Scipy Parser Options and all other features are inherited.

If no commit parser options are provided via the configuration, the parser will use PSR's built-in defaults.


----



Tag Commit Parser

WARNING:

This parser was deprecated in v9.12.0. It will be removed in a future release.


The original parser from v1.0.0 of Python Semantic Release. Similar to the emoji parser above, but with less features.

If no commit parser options are provided via the configuration, the parser will use PSR's built-in defaults.


----



Common Linked Merge Request Detection

Introduced in v9.13.0

All of the PSR built-in parsers implement common pull/merge request identifier detection logic to extract pull/merge request numbers from the commit message regardless of the VCS platform. The parsers evaluate the subject line for a paranthesis-enclosed number at the end of the line. PSR's parsers will return a string value if a pull/merge request number is found in the commit message. If no pull/merge request number is found, the parsers will return an empty string.

Examples:

All of the following will extract a MR number of "x123", where 'x' is the character prefix

1.
BitBucket: Merged in feat/my-awesome-feature (pull request #123)
2.
GitHub: feat: add new feature (#123)
3.
GitLab: fix: resolve an issue (!123)


----



Common Issue Identifier Detection

Introduced in v9.15.0

All of the PSR built-in parsers implement common issue identifier detection logic, which is similar to many VCS platforms such as GitHub, GitLab, and BitBucket. The parsers will look for common issue closure text prefixes in the Git Trailer format in the commit message to identify and extract issue numbers. The detection logic is not strict to any specific issue tracker as we try to provide a flexible approach to identifying issue numbers but in order to be flexible, it is required to the use the Git Trailer format with a colon (:) as the token separator.

PSR attempts to support all variants of issue closure text prefixes, but not all will work for your VCS. PSR supports the following case-insensitive prefixes and their conjugations (plural, present, & past tense):

  • close (closes, closing, closed)
  • fix (fixes, fixing, fixed)
  • resolve (resolves, resolving, resolved)
  • implement (implements, implementing, implemented)

PSR also allows for a more flexible approach to identifying more than one issue number without the need of extra git trailors (although PSR does support multiple git trailors). PSR support various list formats which can be used to identify more than one issue in a list. This format will not necessarily work on your VCS. PSR currently support the following list formats:

  • comma-separated (ex. Closes: #123, #456, #789)
  • space-separated (ex. resolve: #123 #456 #789)
  • semicolon-separated (ex. Fixes: #123; #456; #789)
  • slash-separated (ex. close: #123/#456/#789)
  • ampersand-separated (ex. Implement: #123 & #789)
  • and-separated (ex. Resolve: #123 and #456 and #789)
  • mixed (ex. Closed: #123, #456, and #789 or Fixes: #123, #456 & #789)

All the examples above use the most common issue number prefix (#) but PSR is flexible to support other prefixes used by VCS platforms or issue trackers such as JIRA (ex. ABC-###).

The parsers will return a tuple of issue numbers as strings if any are found in the commit message. Strings are returned to ensure that the any issue number prefix characters are preserved (ex. #123 or ABC-123). If no issue numbers are found, the parsers will return an empty tuple.

References:

  • BitBucket: Resolving Issues Automatically
  • GitHub: Linking Issue to PR
  • GitLab: Default Closing Patterns


----



Customization

Each of the built-in parsers can be customized by providing overrides in the commit_parser_options setting of the configuration file. This can be used to toggle parsing features on and off or to add, modify, or remove the commit types that are used to determine the level bump for a commit. Review the API documentation for the specific parser's options class to see what changes to the default behavior can be made.


----



Custom Parsers

Custom parsers can be written to handle commit message styles that are not covered by the built-in parsers or by option customization of the built-in parsers.

Python Semantic Release provides several building blocks to help you write your parser. To maintain compatibility with how Python Semantic Release will invoke your parser, you should use the appropriate object as described below, or create your own object as a subclass of the original which maintains the same interface. Type parameters are defined where appropriate to assist with static type-checking.

The commit_parser option, if set to a string which does not match one of Python Semantic Release's built-in commit parsers, will be used to attempt to dynamically import a custom commit parser class. As such you will need to ensure that your custom commit parser is import-able from the environment in which you are running Python Semantic Release. The string should be structured in the standard module:attr format; for example, to import the class MyCommitParser from the file custom_parser.py at the root of your repository, you should specify "commit_parser=custom_parser:MyCommitParser" in your configuration, and run the semantic-release command line interface from the root of your repository. Equally you can ensure that the module containing your parser class is installed in the same virtual environment as semantic-release. If you can run python -c "from $MODULE import $CLASS" successfully, specifying commit_parser="$MODULE:$CLASS" is sufficient. You may need to set the PYTHONPATH environment variable to the directory containing the module with your commit parser.

Tokens

The tokens built into Python Semantic Release's commit parsing mechanism are inspired by both the error-handling mechanism in Rust's error handling and its implementation in black. It is documented that catching exceptions in Python is slower than the equivalent guard implemented using if/else checking when exceptions are actually caught, so although try/except blocks are cheap if no exception is raised, commit parsers should always return an object such as ParseError instead of raising an error immediately. This is to avoid catching a potentially large number of parsing errors being caught as the commit history of a repository is being parsed. Python Semantic Release does not raise an exception if a commit cannot be parsed.

Python Semantic Release uses ParsedCommit as the return type of a successful parse operation, and ParseError as the return type from an unsuccessful parse of a commit. You should review the API documentation linked to understand the fields available on each of these objects.

It is important to note, the ParseError implements an additional method, raise_error. This method raises a CommitParseError with the message contained in the error field, as a convenience.

In Python Semantic Release, the type semantic_release.commit_parser.token.ParseResult is defined as ParseResultType[ParsedCommit, ParseError], as a convenient shorthand.

ParseResultType is a generic type, which is the Union of its two type parameters. One of the types in this union should be the type returned on a successful parse of the commit, while the other should be the type returned on an unsuccessful parse of the commit.

A custom parser result type, therefore, could be implemented as follows:

  • MyParsedCommit subclasses ParsedCommit
  • MyParseError subclasses ParseError
  • MyParseResult = ParseResultType[MyParsedCommit, MyParseError]

Internally, Python Semantic Release uses isinstance() to determine if the result of parsing a commit was a success or not, so you should check that your custom result and error types return True from isinstance(<object>, ParsedCommit) and isinstance(<object>, ParseError) respectively.

While it's not advisable to remove any of the fields that are available in the built-in token types, currently only the bump field of the successful result type is used to determine how the version should be incremented as part of this release. However, it's perfectly possible to add additional fields to your tokens which can be populated by your parser; these fields will then be available on each commit in your changelog template, so you can make additional information available.

Parser Options

To provide options to the commit parser which is configured in the configuration file, Python Semantic Release includes a ParserOptions class. Each parser built into Python Semantic Release has a corresponding "options" class, which subclasses ParserOptions.

The configuration in commit_parser_options is passed to the "options" class which is specified by the configured commit_parser - more information on how this is specified is below.

The "options" class is used to validate the options which are configured in the repository, and to provide default values for these options where appropriate.

If you are writing your own parser, you should accompany it with an "options" class which accepts the appropriate keyword arguments. This class' __init__ method should store the values that are needed for parsing appropriately.

Commit Parsers

The commit parsers that are built into Python Semantic Release implement an instance method called parse, which takes a single parameter commit of type git.objects.commit.Commit, and returns the type ParseResultType.

To be compatible with Python Semantic Release, a commit parser must subclass CommitParser. A subclass must implement the following:

  • A class-level attribute parser_options, which must be set to ParserOptions or a subclass of this.
  • An __init__ method which takes a single parameter, options, that should be of the same type as the class' parser_options attribute.
  • A method, parse, which takes a single parameter commit that is of type git.objects.commit.Commit, and returns ParseResult, or a subclass of this.

By default, the constructor for CommitParser will set the options parameter on the options attribute of the parser, so there is no need to override this in order to access self.options during the parse method. However, if you have any parsing logic that needs to be done only once, it may be a good idea to perform this logic during parser instantiation rather than inside the parse method. The parse method will be called once per commit in the repository's history during parsing, so the effect of slow parsing logic within the parse method will be magnified significantly for projects with sizeable Git histories.

Commit Parsers have two type parameters, "TokenType" and "OptionsType". The first is the type which is returned by the parse method, and the second is the type of the "options" class for this parser.

Therefore, a custom commit parser could be implemented via:

class MyParserOptions(semantic_release.ParserOptions):

def __init__(self, message_prefix: str) -> None:
self.prefix = message_prefix * 2 class MyCommitParser(
semantic_release.CommitParser[semantic_release.ParseResult, MyParserOptions] ):
def parse(self, commit: git.objects.commit.Commit) -> semantic_release.ParseResult:
...


Version Change Reports

When using the semantic-release version and semantic-release changelog commands, Python Semantic Release (PSR) will generate a changelog and release notes for your project automatically in the default configuration. The changelog is rendered using the Jinja template engine, and in the default configuration, PSR will use a built-in template file to render the changelog at the file location defined by the changelog_file setting.

Through the use of the templating engine & the template_dir configuration setting, you can customize the appearance of your changelog and release notes content. You may also generate a set of files using your custom template directory and the templates will be rendered relative to the root of your repository.

Because PSR uses a third-party library, Jinja, as its template engine, we do not include all the syntax within our documentation but rather you should refer to the Template Designer Documentation for guidance on how to customize the appearance of your release files. If you would like to customize the template environment itself, then certain options are available to you via changelog environment configuration.

If you do not want to use the changelog generation features, you can disable changelog generation entirely during the semantic-release version command by providing the --no-changelog command-line option.

Using the Default Changelog

If you don't provide any custom templates in the changelog.template_dir, the default changelog templates will be used to render the changelog.

PSR provides two default changelog output formats:

1.
Markdown (.md), default
2.
reStructuredText (.rst), available since v9.11.0

Both formats are kept in sync with one another to display the equivalent information in the respective format. The default changelog template is located in the data/templates/ directory within the PSR package. The templates are written in modular style (ie. multiple files) and during the render proccess are ultimately combined together to render the final changelog output. The rendering start point is the CHANGELOG.{FORMAT_EXT}.j2 underneath the respective format directory.

PSR provides a few configuration options to customize the default changelog output and can be found under the changelog.default_templates section as well as some common configuration options under the changelog section.

To toggle the output format, you only need to set the changelog.default_templates.changelog_file file name to include the desired file extension (.md or .rst). If you would like a different extension for the resulting changelog file, but would like to still have control over the template format, you can set the changelog.default_templates.output_format configuration setting to the desired format.

A common and highly-recommended configuration option is the changelog.exclude_commit_patterns setting which allows the user to define regular expressions that will exclude commits from the changelog output. This is useful to filter out change messages that are not relevant to your external consumers (ex. ci and test in the angular commit convention) and only include the important changes that impact the consumer of your software.

Another important configuration option is the changelog.mode setting which determines the behavior of the changelog generation. There are 2 modes that available that described in detail below.

1.
Initialization Mode when mode = "init".
2.
Update Mode when mode = "update".

Initialization Mode

When using the initialization mode, the changelog file will be created from scratch using the entire git history and overwrite any existing changelog file. This is the default behavior introduced in v8.0.0. This is useful when you are trying to convert over to Python Semantic Release for the first time or when you want to automatically update the entire format of your changelog file.

WARNING:

If you have an existing changelog in the location you have configured with the changelog.changelog_file setting, PSR will overwrite the contents of this file on each release.

Please make sure to refer to Migrating an Existing Changelog.



Update Mode

NOTE:

Introduced in v9.10.0.


When using the update mode, only the change information from the last release will be prepended into the existing changelog file (defined by the changelog.changelog_file). This mimics the behavior that was used in versions prior to v8.0.0 before the conversion to a templating engine but now uses the Jinja to accomplish the update. This mode is best suited for managing changes over the lifetime of your project when you may have a need to make manual changes or adjustments to the changelog and its not easily recreated with a template.

How It Works

In order to insert the new release information into an existing changelog file, your changelog file must have an insertion flag to indicate where the new release information should be inserted. The default template will read in your existing changelog file, split the content based on the insertion flag, and then recombine the content (including the insertion flag) with the new release information added after the insertion flag.

The insertion flag is customizable through the changelog.insertion_flag setting. Generally, your insertion flag should be unique text to your changelog file to avoid any unexpected behavior. See the examples below.

In the case where the insertion flag is NOT found in the existing changelog file, the changelog file will be re-written without any changes.

If there is no existing changelog file found, then the changelog file will be initialized from scratch as if the mode was set to init, except the changelog.insertion_flag will be included into the newly created changelog file.

TIP:

We have accomplished changelog updating through the use of the Jinja templating and addtional context filters and context variables. This is notable because in the case that you want to customize your changelog template, you now can use the same logic to enable changelog updates of your custom template!


SEE ALSO:

Migrating an Existing Changelog.



Example

Given your existing changelog looks like the following with a changelog.insertion_flag set to <!-- version list -->, when you run the semantic-release version command, the new release information will be inserted after the insertion flag.

Before

# CHANGELOG
<!-- version list -->
## 1.0.0
- Initial Release


After

# CHANGELOG
<!-- version list -->
## v1.1.0
### Feature
- feat: added a new feature
### Fix
- fix: resolved divide by zero error
## 1.0.0
- Initial Release


Configuration Examples

1.
Goal: Configure an updating reStructuredText changelog with a custom insertion flag within pyproject.toml.

[tool.semantic_release.changelog]
mode = "update"
insertion_flag = "..\n    All versions below are listed in reverse chronological order"
[tool.semantic_release.changelog.default_templates]
changelog_file = "CHANGELOG.rst"
output_format = "rst"  # optional because of the file extension


2.
Goal: Configure an updating Markdown changelog with custom file name and default insertion flag within a separate config file releaserc.json.

{

"semantic_release": {
"changelog": {
"mode": "update",
"default_templates": {
"changelog_file": "docs/HISTORY",
"output_format": "md"
}
}
} }


3.
Goal: Configure an initializing reStructuredText changelog with filtered angular commits patterns and merge commits within a custom config file releaserc.toml.

[semantic_release.changelog]
mode = "init"
default_templates = { changelog_file = "docs/CHANGELOG.rst" }
exclude_commit_patterns = [

'''chore(?:\([^)]*?\))?: .+''',
'''ci(?:\([^)]*?\))?: .+''',
'''refactor(?:\([^)]*?\))?: .+''',
'''style(?:\([^)]*?\))?: .+''',
'''test(?:\([^)]*?\))?: .+''',
'''build\((?!deps\): .+)''',
'''Merged? .*''', ]



Using the Default Release Notes

PSR has the capability to generate release notes as part of the publishing of a new version similar to the changelog. The release notes are generated using a Jinja template and posted to the your remote version control server (VCS) such as GitHub, GitLab, etc during the semantic-release version command. PSR provides a default built-in template out-of-the-box for generating release notes.

The difference between the changelog and release notes is that the release notes only contain the changes for the current release. Due to the modularity of the PSR templates, the format is identical to an individual version of the default changelog.

At this time, the default template for version release notes is only available in Markdown format for all VCS types.

SEE ALSO:

To personalize your release notes, see the Custom Release Notes section.



Custom Changelogs

If you would like to customize the appearance of your changelog, you can create your own custom templates and configure PSR to render your templates instead during the semantic-release version and semantic-release changelog commands.

To use a custom template, you need to create a directory within your repository and set the template_dir setting to the name of this directory. The default name is "templates".

Templates are identified by giving a .j2 extension to the template file. Any such templates have the .j2 extension removed from the target file. Therefore, to render an output file foo.csv, you should create a template called foo.csv.j2 within your template directory.

If you have additional files that you would like to render alongside your changelog, you can place these files within the template directory. A file within your template directory which does not end in .j2 will not be treated as a template; it will be copied to its target location without being rendered by the template engine.

TIP:

Hidden files within the template directory (i.e. filenames that begin with a period ".") are excluded from the rendering process. Hidden folders within the template directory are also excluded, along with all files and folders contained within them. This is useful for defining macros or other template components that should not be rendered individually.


TIP:

When initially starting out at customizing your own changelog templates, you should reference the default template embedded within PSR. The template directory is located at data/templates/ within the PSR package. Within our templates directory we separate out each type of commit parser (e.g. angular) and the content format type (e.g. markdown). You can copy this directory to your repository's templates directory and then customize the templates to your liking.


Directory Structure

When the templates are rendered, files within the templates directory tree are output to the location within your repository that has the same relative path to the root of your project as the relative path of the template within the templates directory.

Example

An example project has the following structure:

example-project/
├── src/
│   └── example_project/
│       └── __init__.py
└── ch-templates/

├── CHANGELOG.md.j2
├── .components/
│   └── authors.md.j2
├── .macros.j2
├── src/
│   └── example_project/
│   └── data/
│   └── data.json.j2
└── static/
└── config.cfg


And a custom templates folder configured via the following snippet in pyproject.toml:

[tool.semantic_release.changelog]
template_dir = "ch-templates"


After running a release with Python Semantic Release, the directory structure of the project will now look like this (excluding the template directory):

example-project/
├── CHANGELOG.md
├── src/
│   └── example_project/
│       ├── data/
│       │   └── data.json
│       └── __init__.py
└── static/

└── config.cfg


Importantly, note the following:

  • There is no top-level .macros file created, because hidden files are excluded from the rendering process.
  • There is no top-level .components directory created, because hidden folders and all files and folders contained within it are excluded from the rendering process.
  • The .components/authors.md.j2 file is not rendered directly, however, it is used as a component to the CHANGELOG.md.j2 via an include statement in the changelog template.
  • To render data files into the src/ folder, the path to which the template should be rendered has to be created within the ch-templates directory.
  • The ch-templates/static folder is created at the top-level of the project, and the file ch-templates/static/config.cfg is copied, not rendered to the new top-level static folder.

You may wish to leverage this behavior to modularize your changelog template, to define macros in a separate file, or to reference static data which you would like to avoid duplicating between your template environment and the remainder of your project.

Changelog Template Context

During the rendering of a directory tree, Python Semantic Release provides information about the history of the project available within the templating environment in order for it to be used to generate the changelog and other desired documents.

Important project information is provided to the templating environment through the global variable context or ctx for short. Within the template environment, the context object has the following attributes:

changelog_insertion_flag (str): the insertion flag used to determine where the new release information should be inserted into the changelog file. This value is passed directly from changelog.insertion_flag.

Introduced in v9.10.0.

Example Usage:

{%  set changelog_parts = prev_changelog_contents.split(

ctx.changelog_insertion_flag, maxsplit=1
) %}


changelog_mode (Literal["init", "update"]): the mode of the changelog generation currently being used. This can be used to determine different rendering logic. This value is passed directly from the changelog.mode configuration setting.

Introduced in v9.10.0.

Example Usage:

{%    if ctx.changelog_mode == "init"
%}{%    include ".changelog_init.md.j2"
%}{#
#}{%  elif ctx.changelog_mode == "update"
%}{%    include ".changelog_update.md.j2"
%}{#
#}{%  endif
%}


history (ReleaseHistory): the ReleaseHistory instance for the project (See the Release History section for more information).

Example Usage:

{%    set unreleased_commits = ctx.history.unreleased | dictsort
%}{%  for release in context.history.released.values()
%}{%    include ".versioned_changes.md.j2"
#}{%  endfor
%}


hvcs_type (str): the name of the VCS server type currently configured. This can be used to determine which filters are available or different rendering logic.

Introduced in v9.6.0.

Example Usage:

{%    if ctx.hvcs_type == "github"
%}{{   "29" | pull_request_url
}}{#
#}{%  elif ctx.hvcs_type == "gitlab"
%}{{    "29" | merge_request_url
}}{#
#}{%  endif
%}


mask_initial_release (bool): a boolean value indicating whether the initial release should be masked with a generic message. This value is passed directly from the changelog.default_templates.mask_initial_release configuration setting.

Introduced in v9.14.0.

Example Usage:

#}{%  if releases | length == 1 and ctx.mask_initial_release
%}{#    # On a first release, generate a generic message
#}{%    include ".components/first_release.md.j2"
%}{%  else
%}{#    # Not the first release
#}{%    include ".components/versioned_changes.md.j2"
%}{%  endif
%}


repo_name (str): the name of the current repository parsed from the Git url.

Example Usage:

{{ ctx.repo_name }}


example_repo


repo_owner (str): the owner of the current repository parsed from the Git url.

Example Usage:

{{ ctx.repo_owner }}


example_org


prev_changelog_file (str): the path to the previous changelog file that should be updated with the new release information. This value is passed directly from changelog.changelog_file.

Introduced in v9.10.0.

Example Usage:

{% set prev_changelog_contents = prev_changelog_file | read_file | safe %}



Release History

A ReleaseHistory object has two attributes: released and unreleased.

The unreleased attribute is of type Dict[str, List[ParseResult]]. Each commit in the current branch's commit history since the last release on this branch is grouped by the type attribute of the ParsedCommit returned by the commit parser, or if the parser returned a ParseError then the result is grouped under the "unknown" key.

For this reason, every element of ReleaseHistory.unreleased["unknown"] is a ParseError, and every element of every other value in ReleaseHistory.unreleased is of type ParsedCommit.

Typically, commit types will be "feature", "fix", "breaking", though the specific types are determined by the parser. For example, the EmojiCommitParser uses a textual representation of the emoji corresponding to the most significant change introduced in a commit (e.g. ":boom:") as the different commit types. As a template author, you are free to customize how these are presented in the rendered template.

NOTE:

If you are using a custom commit parser following the guide at Custom Parsers, your custom implementations of ParseResult, ParseError and ParsedCommit will be used in place of the built-in types.


The released attribute is of type Dict[Version, Release]. The keys of this dictionary correspond to each version released within this branch's history, and are of type Version. You can use the as_tag() method to render these as the Git tag that they correspond to inside your template.

A Release object has an elements attribute, which has the same structure as the unreleased attribute of a ReleaseHistory; that is, elements is of type Dict[str, List[ParseResult]], where every element of elements["unknown"] is a ParseError, and elements of every other value correspond to the type attribute of the ParsedCommit returned by the commit parser.

The commits represented within each ReleaseHistory.released[version].elements grouping are the commits which were made between version and the release corresponding to the previous version. That is, given two releases Version(1, 0, 0) and Version(1, 1, 0), ReleaseHistory.released[Version(1, 0, 0)].elements contains only commits made after the release of Version(1, 0, 0) up to and including the release of Version(1, 1, 0).

To maintain a consistent order of subsections in the changelog headed by the commit type, it's recommended to use Jinja's dictsort filter.

Each Release object also has the following attributes:

  • tagger: git.Actor: The tagger who tagged the release.
  • committer: git.Actor: The committer who made the release commit.
  • tagged_date: datetime: The date and time at which the release was tagged.

SEE ALSO:

  • Built-in Commit Parsers
  • Commit Parser Tokens
  • git.Actor
  • datetime.strftime Format Codes



Changelog Template Filters

In addition to the context variables, PSR seeds the template environment with a set of custom functions (commonly called filters in Jinja terminology) for use within the template. Filter's first argument is always piped (|) to the function while any additional arguments are passed in parentheses like normal function calls.

The filters provided vary based on the VCS configured and available features:

autofit_text_width (Callable[[textStr, maxWidthInt, indent_sizeInt], textStr]): given a text string, fit the text to the maximum width provided. This filter is useful when you want to wrap text to a specific width. The filter will attempt to break the text at word boundaries and will indent the text by the amount specified in the indent_size parameter.

Introduced in v9.12.0.

Example Usage:

{{ "This is a long string that needs to be wrapped to a specific width" | autofit_text_width(40, 4) }}


Markdown Output:

This is a long string that needs to be

wrapped to a specific width


convert_md_to_rst (Callable[[MdStr], RstStr]): given a markdown string, convert it to reStructuredText format. This filter is useful when building a reStructuredText changelog but your commit messages are in markdown format. It is utilized by the default RST changelog template. It is limited in its ability to convert all markdown to reStructuredText, but it handles most common cases (bold, italics, inline-raw, etc.) within commit messages.

Introduced in v9.11.0.

Example Usage:

{{  "\n* %s (`%s`_)\n" | format(

commit.message.rstrip() | convert_md_to_rst,
commit.short_hash,
) }}


create_server_url (Callable[[PathStr, AuthStr | None, QueryStr | None, FragmentStr | None], UrlStr]): when given a path, prepend the configured vcs server host and url scheme. Optionally you can provide, a auth string, a query string or a url fragment to be normalized into the resulting url. Parameter order is as described above respectively.

Introduced in v9.6.0.

Example Usage:

{{ "example/repo.git" | create_server_url }}
{{ "example/repo" | create_server_url(None, "results=1", "section-header") }}


Markdown Output:


create_repo_url (Callable[[RepoPathStr, QueryStr | None, FragmentStr | None], UrlStr]): when given a repository path, prepend the configured vcs server host, and repo namespace. Optionally you can provide, an additional query string and/or a url fragment to also put in the url. Parameter order is as described above respectively. This is similar to create_server_url but includes the repo namespace and owner automatically.

Introduced in v9.6.0.

Example Usage:

{{ "releases/tags/v1.0.0" | create_repo_url }}
{{ "issues" | create_repo_url("q=is%3Aissue+is%3Aclosed") }}


Markdown Output:


commit_hash_url (Callable[[hashStr], UrlStr]): given a commit hash, return a URL to the commit in the remote.

Introduced in v8.0.0.

Example Usage:

{{ commit.hexsha | commit_hash_url }}


Markdown Output:


compare_url (Callable[[StartRefStr, StopRefStr], UrlStr]): given a starting git reference and a ending git reference create a comparison url between the two references that can be opened on the remote

Introduced in v9.6.0.

Example Usage:

{{ "v1.0.0" | compare_url("v1.1.0") }}


Markdown Output:


issue_url (Callable[[IssueNumStr | IssueNumInt], UrlStr]): given an issue number, return a URL to the issue on the remote vcs. In v9.12.2, this filter was updated to handle a string that has leading prefix symbols (ex. #32) and will strip the prefix before generating the URL.

Introduced in v9.6.0, Modified in v9.12.2.

Example Usage:

{# Add Links to issues annotated in the commit message

# NOTE: commit.linked_issues is only available in v9.15.0 or greater
# #}{% for issue_ref in commit.linked_issues %}{{ "- [%s](%s)" | format(issue_ref, issue_ref | issue_url) }}{% endfor %}


Markdown Output:


merge_request_url (Callable[[MergeReqStr | MergeReqInt], UrlStr]): given a merge request number, return a URL to the merge request in the remote. This is an alias to the pull_request_url but only available for the VCS that uses the merge request terminology. In v9.12.2, this filter was updated to handle a string that has leading prefix symbols (ex. #29) and will strip the prefix before generating the URL.

Introduced in v9.6.0, Modified in v9.12.2.

Example Usage:

{{

"[%s](%s)" | format(
commit.linked_merge_request,
commit.linked_merge_request | merge_request_url
) }} {# commit.linked_merge_request is only available in v9.13.0 or greater #}


Markdown Output:


pull_request_url (Callable[[PullReqStr | PullReqInt], UrlStr]): given a pull request number, return a URL to the pull request in the remote. For remote vcs' that use merge request terminology, this filter is an alias to the merge_request_url filter function. In v9.12.2, this filter was updated to handle a string that has leading prefix symbols (ex. #29) and will strip the prefix before generating the URL.

Introduced in v9.6.0, Modified in v9.12.2.

Example Usage:

{# Create a link to the merge request associated with the commit

# NOTE: commit.linked_merge_request is only available in v9.13.0 or greater #}{{
"[%s](%s)" | format(
commit.linked_merge_request,
commit.linked_merge_request | pull_request_url
) }}


Markdown Output:


read_file (Callable[[str], str]): given a file path, read the file and return the contents as a string. This function was added specifically to enable the changelog update feature where it would load the existing changelog file into the templating environment to be updated.

Introduced in v9.10.0.

Example Usage:

{% set prev_changelog_contents = prev_changelog_file | read_file | safe %}



Availability of the documented filters can be found in the table below:

filter - hvcs_type bitbucket gitea github gitlab
autofit_text_width
convert_md_to_rst
create_server_url
create_repo_url
commit_hash_url
compare_url
issue_url
merge_request_url
pull_request_url
read_file

SEE ALSO:

Filters



Example

The following template is a simple example of how to render a changelog using the PSR template context to create a changelog in Markdown format.

Configuration: pyproject.toml

[tool.semantic_release.changelog]
template_dir = "templates"


Template: templates/CHANGELOG.md.j2

# CHANGELOG
{%    for version, release in ctx.history.released.items()
%}{{

"## %s (%s)" | format(version.as_tag(), release.tagged_date.strftime("%Y-%m-%d")) }}{% for type_, commits in release["elements"] if type_ != "unknown" | dictsort %}{{
"### %s" | format(type_ | title) }}{% for commit in commits %}{{
"* %s ([`%s`](%s))" | format(
commit.descriptions[0] | capitalize,
commit.hexsha[:7],
commit.hexsha | commit_hash_url,
) }}{% endfor %}{% endfor %}{% endfor %}


Result: CHANGELOG.md

# CHANGELOG
## v1.1.0 (2022-01-01)
### Feature
* Added a new feature ([`a1b2c3d`](https://github.com/example/repo/commit/a1b2c3d))
## v1.0.0 (2021-12-31)
### Fix
* Resolved divide by zero error ([`e4f5g6h`](https://github.com/example/repo/commit/e4f5g6h))


It is important to note that the template utilizes the context variable to extract the project history as well as the commit_hash_url filter to generate a URL to the remote VCS for each commit. Both of these are injected into the template environment by PSR.

Custom Release Notes

If you would like to customize the appearance of your release notes, you can add a hidden file named .release_notes.md.j2 at the root of your changelog.template_dir. This file will automatically be detected and used to render the release notes during the semantic-release version and semantic-release changelog commands.

A similar template rendering mechanism is used to render the release notes as is used for the changelog. There are minor differences in the context available to the release notes template but the template directory structure and modularity is maintained.

TIP:

When initially starting out at customizing your own release notes template, you should reference the default template embedded within PSR. The release notes template can be found in the directory data/templates/<parser>/md within the PSR package.


Release Notes Context

All of the changelog's template context is exposed to the Jinja template when rendering the release notes.

Additionally, the following two globals are available to the template:

  • release (Release): contains metadata about the content of the release, as parsed from commit logs

    Introduced in v8.0.0.

  • version (Version): contains metadata about the software version to be released and its git tag

    Introduced in v8.0.0.


Example

Below is an example template that can be used to render release notes (it's similar to GitHub's automatically generated release notes):

Configuration: pyproject.toml

[tool.semantic_release.changelog]
template_dir = "templates"


Template: templates/.release_notes.md.j2

## What's Changed
{%    for type_, commits in release["elements"] | dictsort
%}{%-   if type_ != "unknown"
%}{{

"### %s" | format(type_ | title) }}{% for commit in commits %}{{
"* %s by %s in [`%s`](%s)" | format(
commit.descriptions[0] | capitalize,
commit.commit.author.name,
commit.hexsha[:7],
commit.hexsha | commit_hash_url,
) }}{%- endfor %}{% endif %}{% endfor %}


Result: https://github.com/example/repo/releases/tag/v1.1.0

## What's Changed
### Feature
* Added a new feature by John Doe in [`a1b2c3d`](https://github.com/example/repo/commit/a1b2c3d)


Migrating an Existing Changelog

v9.10.0 or greater

Migrating an existing changelog is simple with Python Semantic Release! To preserve your existing changelog, follow these steps:

1.
Set the changelog.mode to "update" in your configuration file. This will ensure that only the new release information is added to your existing changelog file.
2.
Set the changelog.insertion_flag to a unique string. You may use the default value or set it to a unique string that is not present in your existing changelog file. This flag is used to determine where the new release information should be inserted into your existing changelog.
3.
Add the insertion flag to your changelog file. This must match the value you set in step 2. The insertion flag should be placed in the location above where you would like the new release information to be inserted.

NOTE:

If you are trying to convert an existing changelog to a new format, you will need to do most of the conversion manually (or rebuild via init and modify) and make sure to include your insertion flag into the format of the new changelog.


Prior to v9.10.0

If you have an existing changelog that you would like to preserve, you will need to add the contents of the changelog file to your changelog template - either directly or via Jinja's include tag.

If you would like only the history from your next release onwards to be rendered into the changelog in addition to the existing changelog, you can add an if statement based upon the versions in the keys of context.released.

Upgrading Templates

As PSR evolves, new features and improvements are added to the templating engine. If you have created your own custom templates, you may need to update them to take advantage of some new features. Below are some instructions on how to upgrade your templates to gain the benefits of the new features.

Incrementally Updating Changelog Template

NOTE:

This section is only relevant if you are upgrading from a version of PSR greater than v8.0.0 and prior to v9.10.0 and have created your own custom templates.


If you have previously created your own custom templates and would like to gain the benefits of the new updating changelog feature, you will need to make a few changes to your existing templates.

The following steps are a few suggestions to help upgrade your templates but primarily you should review the embedded default templates in the PSR package for a full example. You can find the default templates at data/templates/ directory.

1.
Add a conditional to check the changelog_mode. This will allow you to determine if you should render the entire changelog or just the new release information. See data/templates/*/md/CHANGELOG.md.j2 for reference.
2.
Use the new read_file filter to read in the existing changelog file ctx.prev_changelog_file. This will allow you to include the existing changelog content in your new changelog file. See data/templates/*/md/.components/changelog_update.md.j2 for reference.
3.
Split the changelog content based on the insertion flag. This will allow you to insert the new release information after the insertion flag (ctx.changelog_insertion_flag). See data/templates/*/md/.components/changelog_update.md.j2 for reference.
4.
Print the leading content before the insertion flag. This ensures you maintain any content that should be included before the new release information. See data/templates/*/md/.components/changelog_update.md.j2 for reference.
5.
Print your insertion flag. This is impartive to ensure that the resulting changelog can be updated in the future. See data/templates/*/md/.components/changelog_update.md.j2 for reference.
6.
Print the new release information. Be sure to consider both unreleased and released commits during this step because of the semantic-release changelog command that can be run at any time. See data/templates/*/md/.components/changelog_update.md.j2 for reference.
7.
Print the trailing content after the insertion flag. This ensures you maintain any content that should be included after the new release information. See data/templates/*/md/.components/changelog_update.md.j2 for reference.

TIP:

Modularity of your templates is key to handling both modes of changelog generation. Reference the default templates for examples on how we handle both modes and defensively handle numerous breaking scenarios.


TIP:

If you are having trouble upgrading your templates, please post a question on the PSR GitHub


Multibranch Releases

Python Semantic Release supports releases from multiple branches within your Git repository. You can elect to have a branch or set of branches create releases or prereleases. There are no restrictions enforced on how you set up your releases, but be aware that if you create new releases from multiple branches, or prereleases from multiple independent branches using the same prerelease token, there is a chance that Python Semantic Release will calculate the next version to be the same on more than one branch (leading to an error that a Git tag already exists).

NOTE:

A "prerelease token" is the string used to suffix onto the 3-digit form of a full semantic version. For example, in the version 1.2.3-beta.1, the prerelease token is "beta"

Typical strings used for pre-release tokens include "alpha", "beta", "dev" and "rc". These tend to indicate a level of maturity of the software associated with the version, but the specific meaning of each string is up to the project to decide.

Generally, it's good practice to maintain a single branch from which full releases are made, and one branch at a time for each type of prerelease (alpha, beta, rc, etc).



If you absolutely require tagging and (pre-)releases to take place from multiple branches where there's a risk that tags could conflict between branches, you can use the --build-metadata command line argument to attach additional information (such as the branch name) to the tag in order to uniquely distinguish it from any other tags that might be calculated against other branches. Such a situation may occur in the following scenario:


O ----------- O <---- feature-1
/ "feat: abc"
/
O -------- O --------------- O <---- main v1.0.0 v1.1.0
\
O ----------- O <---- feature-2
"feat: 123"


Suppose that Python Semantic Release has been configured to use the same prerelease token "alpha" for all feature-* branches, and the default tag format "v{version}". In this case, running a pre-release from branch feature-1 will recognise that since the last release, 1.1.0, a feature has been introduced and therefore the next tag to be applied to feature-1 will be v1.2.0-alpha.1.

However, suppose we then try to run a release against feature-2. This will also recognise that a feature has been introduced against the last released version of v1.1.0 and therefore will try to create the tag v1.2.0-alpha.1, leading to an error as this tag was already created against feature-1.

To get around this issue, you can pass the branch name as part of the build metadata:

semantic-release version --build-metadata $(git branch --show-current)


This would lead to the tag v1.2.0-alpha.1+feature-1 and v1.2.0-alpha.1+feature-2 being applied to branches feature-1 and feature-2, respectively. Note that "build metadata MUST be ignored" per the semver specification when comparing two versions, so these two prereleases would be considered equivalent semantic versions, but when merged to the branch configured to produce full releases (main), if released separately the changes from each branch would be released in two versions that would be considered different according to the semver specification.

NOTE:

If you have tags in your Git repository that are not valid semantic versions (which have then been formatted into your tag_format), these tags will be ignored for the purposes of calculating the next version.


Configuring Multibranch Releases

Within your configuration file, you can create one or more groups of branches ("release groups") that produce a certain type of release. Options are configured at the group level, and the group to use is chosen based on the current branch name against which Python Semantic Release is running.

Each release group is configured as a nested mapping under the tool.semantic_release.branches key in pyproject.toml, or the equivalent structure in other formats. the mapping requires a single key that is used as a name for the release group, which can help to identify it in log messages but has no effect on the behaviour of the release. For example, Python Semantic Release has only one release group by default with the name main.

Inside each release group, the following key-value pairs can be set:

Key Required Default Description
match Yes N/A A Python regular expression to match against the active branch's name. If the branch name matches the provided regular expression, then this release group is chosen to provide the other configuration settings available.
prerelease No false Whether or not branches in this release group should a prerelease instead of a full release
prerelease_token No rc If creating a prerelease, specify the string to be used as a prerelease token in any new versions created against this branch.

WARNING:

If two release groups have overlapping "match" patterns, i.e. a the name of a branch could theoretically match both patterns, then the release group which is defined first in your configuration file is used.

Because of this, it's recommended that you place release groups with more specific match patterns higher up in your configuration file than those with patterns that would match a broader range of branch names.



For example, suppose a project currently on version 1.22.4 is working on a new major version. The project wants to create a branch called 2.x.x against which they will develop the new major version, and they would like to create "release candidate" ("rc") prereleases from this branch. There are also a number of new features to integrate, and the project has agreed that all such branches should be named according to the convention next-{developer initials}-{issue number}, leading to branches named similarly to next-bc-prj-123. The project would like to release with tags that include some way to identify the branch and date on which the release was made from the tag.

This project would be able to leverage the following configuration to achieve the above requirements from their release configuration:

[tool.semantic_release.branches.main]
match = "(main|master)"
prerelease = false
[tool.semantic_release.branches."2.x.x"]
match = "2.x.x"
prerelease = true
prerelease_token = "rc"
[tool.semantic_release.branches."2.x.x New Features"]
match = "next-\\w+-prj-\\d+"
prerelease = true
prerelease_token = "alpha"


In a CI pipeline, the following command would allow attaching the date and branch name to the versions that are produced (note this example uses the UNIX date command):

semantic-release version \

--build-metadata "$(git branch --show-current).$(date +%Y%m%d)"


This would lead to versions such as 1.1.1+main.20221127 or 2.0.0-rc.4+2.x.x.20221201.

NOTE:

Remember that is always possible to override the release rules configured by using the --major/--minor/--patch/--prerelease and --as-prerelease flags.


Automatic Releases

The key point with using this package is to automate your releases and stop worrying about version numbers. Different approaches to automatic releases and publishing with the help of this package can be found below. Using a CI is the recommended approach.

Guides

Setting up python-semantic-release on Travis CI

This guide expects you to have activated the repository on Travis CI. If this is not the case, please refer to Travis documentation on how to do that.

1. Add python-semantic-release settings

See Configuration for details on how to configure Python Semantic Release. Make sure that at least you have set version_variables before continuing.

2. Add environment variables

You will need to set up an environment variable in Travis. An easy way to do that is to go to the settings page for your package and add it there. Make sure that the secret toggle is set correctly.

You need to set the GH_TOKEN environment variable with a personal access token for Github. It will need either repo or public_repo scope depending on whether the repository is private or public.

More information on how to set environment variables can be found on Travis documentation on environment variables.

3. Add travis configuration

The following should be added to your .travis.yml file.

after_success:
- git config --global user.name "semantic-release (via TravisCI)"
- git config --global user.email "semantic-release@travis"
- pip install python-semantic-release
- semantic-release version && semantic-release publish


The first line tells Travis that we want to run the listed tasks after a successful build. The two first lines in after_success will configure git so that python-semantic-release will be able to commit on Travis. The third installs the latest version of python-semantic-release. The last will run the publish command, which will publish a new version if the changes indicate that one is due.

4. Push some changes

You are now ready to release automatically on Travis CI on every change to your master branch.

Happy coding!

GitHub Actions

There are two official GitHub Actions for Python Semantic Release:

1.
This is the main action that runs the version CLI command. It is used to (1) determine the next version number, (2) stamp the version number, (3) run the build command, (4) build the changelog, (5) commit the changes, (6) tag the commit, (7) publish the commit & tag and lastly (8) create a GitHub release. For more information review the version command documentation and see below for the Action configuration options.

2.
This action is used to execute the publish CLI command. It is used to upload files, such as distribution artifacts and other assets, to a GitHub release.


NOTE:

These GitHub Actions are only simplified wrappers around the python-semantic-release CLI. Ultimately, they download and install the published package from PyPI so if you find that you are trying to do something more advanced or less common, you may need to install and use the CLI directly.


Python Semantic Release Action

The official Python Semantic Release GitHub Action is a GitHub Docker Action, which means at the beginning of the job it will build a Docker image that contains the Python Semantic Release package and its dependencies. It will then run the job step inside the Docker Container. This is done to ensure that the environment is consistent across all GitHub Runners regardless of platform. With this choice, comes some limitations of non-configurable options like a pre-defined python version, lack of installed build tools, and an inability to utilize caching.

The primary benefit of using the GitHub Action is that it is easy to set up and use for most projects. We handle a lot of the git configuration under the hood, so you don't have to handle it yourself. There are a plenty of customization options available which are detailed individually below.

Most importantly your project's configuration file will be used as normal, as your project will be mounted into the container for the action to use.

SEE ALSO:

action.yml: the code definition of the action


Inputs

GitHub Action inputs are used for select configuration and provide the necessary information to execute the action. The inputs are passed to the action using the with keyword in the workflow file. Many inputs will mirror the command line options available in the version command. This section outlines each supported input and its purpose.


----



build

Type: Literal["true", "false"]

Override whether the action should execute the build command or not. This option is equivalent to adding the command line switch --skip-build (when false) to the version command. If set to true, no command line switch is passed and the default behavior of the version is used.

Required: false

NOTE:

If not set or set to true, the default behavior is defined by the version command and any user configurations.


SEE ALSO:

--skip-build option for the version command.




----



build_metadata

Type: string

Explicitly set the build metadata of the version. This is equivalent to running the command:

semantic-release version --build-metadata <metadata>


Required: false

SEE ALSO:

--build-metadata [VALUE] option for the version command




----



changelog

Type: Literal["true", "false"]

Override whether the action should generate a changelog or not. This option is equivalent to adding either --changelog (on true) or --no-changelog (on false) to the version command.

Required: false

NOTE:

If not set, the default behavior is defined by the version command and any user configurations.


SEE ALSO:

--changelog/--no-changelog options for the version command




----



commit

Type: Literal["true", "false"]

Override whether the action should commit any changes to the local repository. Changes include the version stamps, changelog, and any other files that are modified and added to the index during the build command. This option is equivalent to adding either --commit (on true) or --no-commit (on false) to the version command.

Required: false

NOTE:

If not set, the default behavior is defined by the version command and any user configurations.


SEE ALSO:

--commit/--no-commit options for the version command




----



directory

If the project is not at the root of the repository (like in monorepos), you can specify a sub-directory to change into before running semantic-release.

Required: false

Default: .


----



force

Type: Literal["prerelease", "patch", "minor", "major"]

Force the next version to be a specific bump type. This is equivalent to running the command:

semantic-release version --<type>
# Ex: force a patch level version bump
semantic-release version --patch


Required: false

SEE ALSO:

--major/--minor/--patch/--prerelease options for the version command




----



git_committer_email

The email of the account used to commit. If customized, it must be associated with the provided token.

Required: false


----



git_committer_name

The name of the account used to commit. If customized, it must be associated with the provided token.

Required: false


----



github_token

The GitHub Token is essential for access to your GitHub repository to allow the push of commits & tags as well as to create a release. Not only do you need to provide the token as an input but you also need to ensure that the token has the correct permissions.

The token should have the following permissions:

  • id-token: write
  • contents: write

Required: true


----



prerelease

Force the version to be a prerelease version when set to true. This is equivalent to running the command:

semantic-release version --as-prerelease


Required: false

NOTE:

If not set, the default behavior is defined by the version command and any user configurations.


SEE ALSO:

--as-prerelease option for the version command




----



prerelease_token

Override any prerelease token in the configuration file with this value, if it is a pre-release. This will override the matching release branch configuration's prerelease_token value. If you always want it to be a prerelease then you must also set the prerelease input to true.

This option is equivalent to running the command:

semantic-release version --prerelease-token <token>


Required: false

NOTE:

If not set, the default behavior is defined by the version command and any user configurations.


SEE ALSO:

--prerelease-token [VALUE] option for the version command




----



push

Type: Literal["true", "false"]

Override whether the action should push any commits or tags from the local repository to the remote repository. This option is equivalent to adding either --push (on true) or --no-push (on false) to the version command.

Required: false

NOTE:

If not set, the default behavior is defined by the version command and any user configurations.


SEE ALSO:

--push/--no-push options for the version command




----



root_options

Additional options for the main semantic-release command, which will come before the version subcommand.

Example

- uses: python-semantic-release/python-semantic-release@v9.12.0

with:
root_options: "-vv --noop"


This configuration would cause the command to be semantic-release -vv --noop version, which would run the version command verbosely but in no-operation mode.



Required: false

Default: -v

SEE ALSO:

Options for the semantic-release command




----



ssh_public_signing_key

The public key associated with the private key used in signing a commit and tag.

Required: false


----



ssh_private_signing_key

The private key used to sign a commit and tag.

Required: false


----



tag

Type: Literal["true", "false"]

Override whether the action should create a version tag in the local repository. This option is equivalent to adding either --tag (on true) or --no-tag (on false) to the version command.

Required: false

NOTE:

If not set, the default behavior is defined by the version command and any user configurations.


SEE ALSO:

--tag/--no-tag options for the version command




----



vcs_release

Type: Literal["true", "false"]

Override whether the action should create a release on the VCS. This option is equivalent to adding either --vcs-release (on true) or --no-vcs-release (on false) to the version command.

Required: false

NOTE:

If not set, the default behavior is defined by the version command and any user configurations.


SEE ALSO:

--vcs-release/--no-vcs-release options for the version command




----



Outputs

The Python Semantic Release Action also provides outputs that can be used in subsequent steps of the workflow. These outputs are used to provide information about the release and any actions that were taken.


----



is_prerelease

Type: Literal["true", "false"]

A boolean value indicating whether the released version is a prerelease.


----



released

Type: Literal["true", "false"]

A boolean value indicating whether a release was made.


----



version

Type: string

The newly released SemVer version string if one was made, otherwise the current version.

Example: 1.2.3


----



tag

Type: string

The Git tag corresponding to the version output but in the tag format dictated by your configuration.

Example: v1.2.3


----



Python Semantic Release Publish Action

The official Python Semantic Release Publish Action is a GitHub Docker Action, which means at the beginning of the job it will build a Docker image that contains the Python Semantic Release package and its dependencies. It will then run the job step inside the Docker Container. This is done to ensure that the environment is consistent across all GitHub Runners regardless of platform. With this choice, comes some limitations of non-configurable options like a pre-defined python version, lack of additional 3rd party tools, and an inability to utilize caching.

The primary benefit of using the GitHub Action is that it is easy to set up and use for most projects. We handle some additional configuration under the hood, so you don't have to handle it yourself. We do however provide a few customization options which are detailed individually below.

Most importantly your project's configuration file will be used as normal, as your project will be mounted into the container for the action to use.

If you have issues with the action, please open an issue on the python-semantic-release/publish-action repository.

SEE ALSO:

action.yml: the code definition for the publish action



Inputs

GitHub Action inputs are used for select configuration and provide the necessary information to execute the action. The inputs are passed to the action using the with keyword in the workflow file. Many inputs will mirror the command line options available in the publish command and others will be specific to adjustment of the action environment. This section outlines each supported input and its purpose.


----



directory

If the project is not at the root of the repository (like in monorepos), you can specify a sub-directory to change into before running semantic-release.

Required: false

Default: .


----



github_token

The GitHub Token is essential for access to your GitHub repository to allow the publish of assets to a release. Not only do you need to provide the token as an input but you also need to ensure that the token has the correct permissions.

The token should have the following permissions:

contents: write: Required for modifying a GitHub Release

Required: true


----



root_options

Additional options for the main semantic-release command, which will come before the publish subcommand.

Example

- uses: python-semantic-release/publish-action@v9.8.9

with:
root_options: "-vv --noop"


This configuration would cause the command to be semantic-release -vv --noop publish, which would run the publish command verbosely but in no-operation mode.



Required: false

Default: -v

SEE ALSO:

Options for the semantic-release command




----



tag

Type: string

The tag corresponding to the GitHub Release that the artifacts should be published to. This option is equivalent to running the command:

semantic-release publish --tag <tag>


Python Semantic Release will automatically determine the latest release if no --tag option is provided.

Required: false

SEE ALSO:

--tag option for the publish command




----



Outputs

There are no outputs provided by the Python Semantic Release Publish Action at this time.

NOTE:

If you would like outputs to be provided by this action, please open an issue on the python-semantic-release/publish-action repository.



----



Examples

Common Workflow Example

The following is a common workflow example that uses both the Python Semantic Release Action and the Python Semantic Release Publish Action. This workflow will run on every push to the main branch and will create a new release upon a successful version determination. If a version is released, the workflow will then publish the package to PyPI and upload the package to the GitHub Release Assets as well.

name: Continuous Delivery
on:

push:
branches:
- main jobs:
release:
runs-on: ubuntu-latest
concurrency: release
permissions:
id-token: write
contents: write
steps:
# Note: we need to checkout the repository at the workflow sha in case during the workflow
# the branch was updated. To keep PSR working with the configured release branches,
# we force a checkout of the desired release branch but at the workflow sha HEAD.
- name: Setup | Checkout Repository at workflow sha
uses: actions/checkout@v4
with:
fetch-depth: 0
ref: ${{ github.sha }}
- name: Setup | Force correct release branch on workflow sha
run: |
git checkout -B ${{ github.ref_name }} ${{ github.sha }}
- name: Action | Semantic Version Release
id: release
# Adjust tag with desired version if applicable.
uses: python-semantic-release/python-semantic-release@v9.12.0
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
git_committer_name: "github-actions"
git_committer_email: "actions@users.noreply.github.com"
- name: Publish | Upload package to PyPI
uses: pypa/gh-action-pypi-publish@v1
if: steps.release.outputs.released == 'true'
- name: Publish | Upload to GitHub Release Assets
uses: python-semantic-release/publish-action@v9.8.9
if: steps.release.outputs.released == 'true'
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
tag: ${{ steps.release.outputs.tag }}


IMPORTANT:

The concurrency directive is used on the job to prevent race conditions of more than one release job in the case if there are multiple pushes to main in a short period of time.


WARNING:

You must set fetch-depth to 0 when using actions/checkout@v4, since Python Semantic Release needs access to the full history to build a changelog and at least the latest tags to determine the next version.


WARNING:

The GITHUB_TOKEN secret is automatically configured by GitHub, with the same permissions role as the user who triggered the workflow run. This causes a problem if your default branch is protected to specific users.

You can work around this by storing an administrator's Personal Access Token as a separate secret and using that instead of GITHUB_TOKEN. In this case, you will also need to pass the new token to actions/checkout (as the token input) in order to gain push access.



Version Overrides Example

In the case where you want to provide multiple command line options to the version command, you provide them through the with directive in the workflow file. In this example, we want to force a patch version bump, not produce a changelog, and provide specialized build metadata. As a regular CLI command, this would look like:

semantic-release version --patch --no-changelog --build-metadata abc123


The equivalent GitHub Action configuration would be:

# snippet
- name: Action | Semantic Version Release

# Adjust tag with desired version if applicable.
uses: python-semantic-release/python-semantic-release@v9.12.0
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
force: patch
changelog: false
build_metadata: abc123


Actions with Monorepos

While python-semantic-release does NOT have full monorepo support, if you have multiple projects stored within a single repository (or your project is not at the root of the repository), you can pass the directory input to the action to change directory before semantic-release execution.

For multiple packages, you would need to run the action multiple times, to release each project. The following example demonstrates how to release two projects in a monorepo.

The directory input directive is also available for the Python Semantic Release Publish Action.

- name: Release Project 1

uses: python-semantic-release/python-semantic-release@v9.12.0
with:
directory: ./project1
github_token: ${{ secrets.GITHUB_TOKEN }} - name: Release Project 2
uses: python-semantic-release/python-semantic-release@v9.12.0
with:
directory: ./project2
github_token: ${{ secrets.GITHUB_TOKEN }}


Publish with cronjobs

This is for you if for some reason you cannot publish from your CI or you would like releases to drop at a certain interval. Before you start, answer this: Are you sure you do not want a CI to release for you? (high version numbers are not a bad thing).

The guide below is for setting up scheduled publishing on a server. It requires that the user that runs the cronjob has push access to the repository and upload access to an artifact repository.

1.
Create a virtualenv:

virtualenv semantic_release -p `which python3`


2.
Install python-semantic-release:

pip install python-semantic-release



3. Clone the repositories you want to have scheduled publishing. 3. Put the following in publish:

VENV=semantic_release/bin
$VENV/pip install -U pip python-semantic-release > /dev/null
publish() {

cd $1
git stash -u # ensures that there is no untracked files in the directory
git fetch && git reset --hard origin/master
$VENV/semantic-release version && $VENV/semantic-release publish
cd .. } publish <package1> publish <package2>


4.
Add cronjob:

/bin/bash -c "cd <path> && source semantic_release/bin/activate && ./publish 2>&1 >> releases.log"



Troubleshooting

  • Check your configuration file for Configuration
  • Check your Git tags match your tag_format; tags using other formats are ignored during calculation of the next version.

Increasing Verbosity

If you are having trouble with Python Semantic Release or would like to see additional information about the actions that it is taking, you can use the top-level -v/--verbose option. This can be supplied multiple times to increase the logging verbosity of the semantic-release command or any of its subcommands during their execution. You can supply this as many times as you like, but supplying more than twice has no effect.

Supply -v/--verbose once for INFO output, and twice for DEBUG.

For example:

semantic-release -vv version --print


NOTE:

The -v/--verbose option must be supplied to the top-level semantic-release command, before the name of any sub-command.


WARNING:

The volume of logs when using DEBUG verbosity may be significantly increased, compared to INFO or the default WARNING, and as a result executing commands with semantic-release may be significantly slower than when using DEBUG.


NOTE:

The provided GitHub action sets the verbosity level to INFO by default.


Contributing

If you want to contribute that is awesome. Remember to be nice to others in issues and reviews.

Please remember to write tests for the cool things you create or fix.

Unsure about something? No worries, open an issue.

Commit messages

Since python-semantic-release is released with python-semantic-release we need the commit messages to adhere to the angular commit guidelines. If you are unsure how to describe the change correctly just try and ask about it in your pr. If we think it should be something else or there is a pull-request without tags we will help out in adding or changing them.

Releases

This package is released by python-semantic-release on each master build, thus if there are changes that should result in a new release it will happen if the build is green.

Development

Install this module and the development dependencies

pip install -e .[dev,mypy,test]


And if you'd like to build the documentation locally

pip install -e .[docs]
sphinx-autobuild --open-browser docs docs/_build/html


Testing

To test your modifications locally:

# Run type-checking, all tests across all supported Python versions
tox
# Run all tests for your current installed Python version (with full error output)
pytest -vv --comprehensive
# Run unit tests for your current installed Python version
pytest
# or
pytest -vv -m unit
# Run end-to-end tests for your current installed Python version (with full error output)
pytest -vv -m e2e [--comprehensive]


The --comprehensive flag is optional and will run all the variations of tests and it does take significantly longer to run.

Building

This project is designed to be versioned and built by itself using the tool.semantic_release configuration in pyproject.toml. The setting tool.semantic_release.build_command defines the command to run to build the package.

The following is a copy of the build_command setting which can be run manually to build the package locally:

pip install -e .[build]
python -m build .


Migrating from Python Semantic Release v7

Python Semantic Release 8.0.0 introduced a number of breaking changes. The internals have been changed significantly to better support highly-requested features and to streamline the maintenance of the project.

As a result, certain things have been removed, reimplemented differently, or now exhibit different behaviour to earlier versions of Python Semantic Release. This page is a guide to help projects to pip install python-semantic-release>=8.0.0 with fewer surprises.

Python Semantic Release GitHub Action

GitHub Action no longer publishes artefacts to PyPI or GitHub Releases

Python Semantic Release no longer uploads distributions to PyPI - see Repurposing of version and publish commands. If you are using Python Semantic Release to publish release notes and artefacts to GitHub releases, there is a new GitHub Action upload-to-gh-release which will perform this action for you.

This means the following workflows perform the same actions, and if you are using the former, you will need to modify your workflow to include the steps in the latter.

This workflow is written to use Python Semantic Release v7.33.5:

---
name: Semantic Release
on:

push:
branches:
- main jobs:
release:
runs-on: ubuntu-latest
concurrency: release
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
# This action uses Python Semantic Release v7
- name: Python Semantic Release
uses: python-semantic-release/python-semantic-release@v7.33.5
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
repository_username: __token__
repository_password: ${{ secrets.PYPI_TOKEN }}


The following workflow achieves the same result using Python Semantic Release v8, the upload-to-gh-release GitHub Action, and the pypa/gh-action-pypi-publish GitHub Action:

---
name: Semantic Release
on:

push:
branches:
- main jobs:
release:
runs-on: ubuntu-latest
concurrency: release
permissions:
id-token: write
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
# This action uses Python Semantic Release v8
- name: Python Semantic Release
id: release
uses: python-semantic-release/python-semantic-release@v8.7.0
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
- name: Publish package distributions to PyPI
uses: pypa/gh-action-pypi-publish@v1
# NOTE: DO NOT wrap the conditional in ${{ }} as it will always evaluate to true.
# See https://github.com/actions/runner/issues/1173
if: steps.release.outputs.released == 'true'
- name: Publish package distributions to GitHub Releases
uses: python-semantic-release/upload-to-gh-release@v8.7.0
if: steps.release.outputs.released == 'true'
with:
github_token: ${{ secrets.GITHUB_TOKEN }}


Removal of pypi_token, repository_username and repository_password inputs

Since the library no longer supports publishing to PyPI, the pypi_token, repository_username and repository_password inputs of the GitHub action have all been removed. See the above section for how to publish to PyPI using the official GitHub Action from the Python Packaging Authority (PyPA).

Rename additional_options to root_options

Because the purposes of the semantic-release version and semantic-release publish commands have changed, the GitHub action now performs both commands in sequence. For this reason, and because the usage of the CLI has changed, additional_options has been renamed to root_options to reflect the fact that the options are for the main semantic-release command group.

Commands

Repurposing of version and publish commands

Python Semantic Release's primary purpose is to enable automation of correct semantic versioning for software projects. Over the years, this automation has been extended to include other actions such as building/publishing the project and its artefacts to artefact repositories, creating releases in remote version control systems, and writing changelogs.

In Python Semantic Release <8.0.0, the publish command was a one-stop-shop for performing every piece of automation provided. This has been changed - the version command now handles determining the next version, applying the changes to the project metadata according to the configuration, writing a changelog, and committing/pushing changes to the remote Git repository. It also handles creating a release in the remote VCS. It does not publish software artefacts to remote repositories such as PyPI; the rationale behind this decision is simply that under the hood, Python Semantic Release used twine to upload artefacts to package indexes such as PyPI, and it's recommended to use twine directly via the command-line. From the twine documentation:

Twine is a command-line tool for interacting with PyPI securely over HTTPS.


As a result Python Semantic Release no longer depends on twine internals.

The publish command now handles publishing software artefacts to releases in the remote version control system.

To achieve a similar flow of logic such as

1.
Determine the next version
2.
Write this version to the configured metadata locations
3.
Write the changelog
4.
Push the changes to the metadata and changelog to the remote repository
5.
Create a release in the remote version control system
6.
Build a wheel
7.
Publish the wheel to PyPI
8.
Publish the distribution artifacts to the release in the remote VCS



You should run:

semantic-release version
twine upload dist/*  # or whichever path your distributions are placed in
semantic-release publish


With steps 1-6 being handled by the semantic-release version command, step 7 being left to the developer to handle, and lastly step 8 to be handled by the semantic-release publish command.

Removal of -D/--define command-line option

It is no longer possible to override arbitrary configuration values using the -D/ --define option. You should provide the appropriate values via a configuration file using -c/--config [FILE] or via the available command-line options.

This simplifies the command-line option parsing significantly and is less error-prone, which has resulted in previous issues (e.g. #600) with overrides on the command-line. Some of the configuration values expected by Python Semantic Release use complex data types such as lists or nested structures, which would be tedious and error-prone to specify using just command-line options.

Removal of CI verifications

Prior to v8, Python Semantic Release would perform some prerequisite verification of environment variables before performing any version changes using the publish command. It's not feasible for Python Semantic Release to verify any possible CI environment fully, and these checks were only triggered if certain environment variables were set - they wouldn't fail locally.

These checks previously raised :py:class:semantic_release.CiVerificationError, and were the only place in which this custom exception was used. Therefore, this exception has also been removed from Python Semantic Release in v8.

If you were relying on this functionality, it's recommended that you add the following shell commands before invoking semantic-release to verify your environment:

NOTE:

In the following, $RELEASE_BRANCH refers to the git branch against which you run your releases using Python Semantic Release. You will need to ensure it is set properly (e.g. via export RELEASE_BRANCH=main and/or replace the variable with the branch name you want to verify the CI environment for.


Travis

Condition: environment variable TRAVIS=true

Replacement:

if ! [[

$TRAVIS_BRANCH == $RELEASE_BRANCH && \
$TRAVIS_PULL_REQUEST == 'false'
]]; then
exit 1 fi


Semaphore

Condition: environment variable SEMAPHORE=true

Replacement:

if ! [[

$BRANCH_NAME == $RELEASE_BRANCH && \
$SEMAPHORE_THREAD_RESULT != 'failed' && \
-n $PULL_REQUEST_NUMBER
]]; then
exit 1 fi


Frigg

Condition: environment variable FRIGG=true

Replacement:

if ! [[

$FRIGG_BUILD_BRANCH == $RELEASE_BRANCH && \
-n $FRIGG_PULL_REQUEST
]]; then
exit 1 fi


Circle CI

Condition: environment variable CIRCLECI=true

Replacement:

if ! [[

$CIRCLE_BRANCH == $RELEASE_BRANCH && \
-n $CI_PULL_REQUEST
]]; then
exit 1 fi


GitLab CI

Condition: environment variable GITLAB_CI=true

Replacement:

if ! [[ $CI_COMMIT_REF_NAME == $RELEASE_BRANCH ]]; then

exit 1 fi


Condition: environment variable BITBUCKET_BUILD_NUMBER is set

Replacement:

if ! [[

$BITBUCKET_BRANCH == $RELEASE_BRANCH && \
-n $BITBUCKET_PR_ID
]]; then
exit 1 fi


Jenkins

Condition: environment variable JENKINS_URL is set

Replacement:

if [[ -z $BRANCH_NAME ]]; then

BRANCH_NAME=$BRANCH_NAME elif [[ -z $GIT_BRANCH ]]; then
BRANCH_NAME=$GIT_BRANCH fi if ! [[
$BRANCH_NAME == $RELEASE_BRANCH && \
-n $CHANGE_ID
]]; then
exit 1 fi


Removal of Build Status Checking

Prior to v8, Python Semantic Release contained a configuration option, check_build_status, which would attempt to prevent a release being made if it was possible to identify that a corresponding build pipeline was failing. For similar reasons to those motivating the removal of CI Checks, this feature has also been removed.

If you are leveraging this feature in Python Semantic Release v7, the following bash commands will replace the functionality, and you can add these to your pipeline. You will need to install jq and curl to run these commands; they can be easily installed through your system's package manager, for example on Ubuntu:

sudo apt update && sudo apt upgrade
sudo apt install -y curl jq


On Windows, you can refer to the installation guide for jq, and if curl is not already installed, you can download it from the curl website

GitHub

export RESP="$(

curl \
-H "Authorization: token $GITHUB_TOKEN" \
-fSsL https://$GITHUB_API_DOMAIN/repos/$REPO_OWNER/$REPO_NAME/commits/$(git rev-parse HEAD)/status || exit 1 )" if [ $(jq -r '.state' <<< "$RESP") != "success" ]; then
echo "Build status is not success" >&2
exit 1 fi


Note that $GITHUB_API_DOMAIN is typically api.github.com unless you are using GitHub Enterprise with a custom domain name.

Gitea

export RESP="$(

curl \
-H "Authorization: token $GITEA_TOKEN" \
-fSsL https://$GITEA_DOMAIN/repos/$REPO_OWNER/$REPO_NAME/statuses/$(git rev-parse HEAD) || exit 1 )" if [ $(jq -r '.state' <<< "$RESP") != "success" ]; then
echo "Build status is not success" >&2
exit 1 fi


Gitlab


export RESP="$(
curl \
-H "Authorization: token $GITLAB_TOKEN" \
-fSsL https://$GITLAB_DOMAIN/api/v4/projects/$PROJECT_ID/repository/commits/$(git rev-parse HEAD)/statuses
)"
for line in $(jq -r '.[] | [.name, .status, .allow_failure] | join("|")' <<<"$RESP"); do
IFS="|" read -r job_name job_status allow_failure <<<"$line"
if [ "$job_status" == "pending" ]; then
echo "job $job_name is pending" >&2
exit 1
elif [ "$job_status" == "failed" ] && [ ! "$allow_failure" == "true" ]; then
echo "job $job_name failed" >&2
exit 1
fi done


Multibranch releases

Prior to v8, Python Semantic Release would perform git checkout to switch to your configured release branch and determine if a release would need to be made. In v8 this has been changed - you must manually check out the branch which you would like to release against, and if you would like to create releases against this branch you must also ensure that it belongs to a release group.

changelog command

A new option, --post-to-release-tag [TAG] has been added. If you omit this argument on the command line then the changelog rendering process, which is described in more detail at Custom Changelogs, will be triggered, but the new changelog will not be posted to any release. If you use this new command-line option, it should be set to a tag within the remote which has a corresponding release. For example, to update the changelog and post it to the release corresponding to the tag v1.1.4, you should run:

semantic-release changelog --post-to-release-tag v1.1.4


Changelog customisation

A number of options relevant to customising the changelog have been removed. This is because Python Semantic Release now supports authoring a completely custom Jinja template with the contents of your changelog. Historically, the number of options added to Python Semantic Release in order to allow this customisation has grown significantly; it now uses templates in order to fully open up customising the changelog's appearance.

Configuration

The configuration structure has been completely reworked, so you should read Configuration carefully during the process of upgrading to v8+. However, some common pitfalls and potential sources of confusion are summarised here.

setup.cfg is no longer supported

Python Semantic Release no longer supports configuration via setup.cfg. This is because the Python ecosystem is centering around pyproject.toml as universal tool and project configuration file, and TOML allows expressions via configuration, such as the mechanism for declaring configuration via environment variables, which introduce much greater complexity to support in the otherwise equivalent ini-format configuration.

You can use semantic-release generate-config to generate new-format configuration that can be added to pyproject.toml, and adjust the default settings according to your needs.

WARNING:

If you don't already have a pyproject.toml configuration file, pip can change its behaviour once you add one, as a result of PEP-517. If you find that this breaks your packaging, you can add your Python Semantic Release configuration to a separate file such as semantic-release.toml, and use the --config option to reference this alternative configuration file.

More detail about this issue can be found in this pip issue.



Commit parser options

Options such as major_emoji, parser_angular_patch_types or parser_angular_default_level_bump have been removed. Instead, these have been replaced with a single set of recognised commit parser options, allowed_tags, major_tags, minor_tags, and patch_tags, though the interpretation of these is up to the specific parsers in use. You can read more detail about using commit parser options in commit_parser_options, and if you need to parse multiple commit styles for a single project it's recommended that you create a parser following Custom Parsers that is tailored to the specific needs of your project.

version_variable

This option has been renamed to version_variables as it refers to a list of variables which can be updated.

version_pattern

This option has been removed. It's recommended to use an alternative tool to perform substitution using arbitrary regular expressions, such as sed. You can always use Python Semantic Release to identify the next version to be created for a project and store this in an environment variable like so:

export VERSION=$(semantic-release version --print)


version_toml

This option will no longer accept a string or comma-separated string of version locations to be updated in TOML files. Instead, you must supply a List[str]. For existing configurations using a single location in this option, you can simply wrap the value in []:

# Python Semantic Release v7 configuration
[tool.semantic_release]
version_toml = "pyproject.toml:tool.poetry.version"
# Python Semantic Release v8 configuration
[tool.semantic_release]
version_toml = ["pyproject.toml:tool.poetry.version"]


tag_format

This option has the same effect as it did in Python Semantic Release prior to v8, but Python Semantic Release will now verify that it has a {version} format key and raise an error if this is not the case.

upload_to_release

This option has been renamed to upload_to_vcs_release.

Custom Commit Parsers

Previously, a custom commit parser had to satisfy the following criteria:

  • It should be import-able from the virtual environment where the semantic-release is run
  • It should be a function which accepts the commit message as its only argument and returns a semantic_release.history.parser_helpers.ParsedCommit if the commit is parsed successfully, or raise a semantic_release.UnknownCommitMessageStyleError if parsing is unsuccessful.



It is still possible to implement custom commit parsers, but the interface for doing so has been modified with stronger support for Python type annotations and broader input provided to the parser to enable capturing more information from each commit, such as the commit's date and author, if desired. A full guide to implementing a custom commit parser can be found at Custom Parsers.

src

semantic_release package

Python Semantic Release

A hook to be used in setup.py to enable python setup.py publish.
argv -- sys.argv


Subpackages

semantic_release.changelog package

Submodules

semantic_release.changelog.context module








semantic_release.changelog.release_history module



semantic_release.changelog.template module

Bases: SandboxedEnvironment
Add support for complex directory structures in the template directory.

This method overrides the default functionality of the SandboxedEnvironment where all 'include' keywords expect to be in the same directory as the calling template, however this is unintuitive when using a complex directory structure.

This override simulates the changing of directories when you include the template from a child directory. When the child then includes a template, it will make the path relative to the child directory rather than the top level template directory.





semantic_release.cli package

Subpackages

semantic_release.cli.commands package

Submodules

semantic_release.cli.commands.changelog module


semantic_release.cli.commands.generate_config module

semantic_release.cli.commands.main module


semantic_release.cli.commands.publish module


semantic_release.cli.commands.version module


Run the build command to build the distributions.
  • build_command -- The build command to run.
  • build_command_env -- The environment variables to use when running the build command.
  • noop -- Whether or not to run the build command.

BuildDistributionsError: if the build command fails



Determine if this release is forced to have prerelease on/off. If force_prerelease is set then yes. Otherwise if we are forcing a specific level bump without force_prerelease, it's False. Otherwise (force_level is None) use the value of prerelease





Submodules

semantic_release.cli.changelog_writer module








semantic_release.cli.cli_context module

Bases: object

Lazy load the runtime context. This is done to avoid configuration loading when the command is not run. This is useful for commands like --help and --version


semantic_release.cli.config module


Bases: BaseModel
Deprecated! Moved to 'default_templates.changelog_file'








Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].











Bases: BaseModel













Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].














Bases: object

































semantic_release.cli.const module

semantic_release.cli.github_actions_output module


semantic_release.cli.masking_filter module

Bases: Filter


Determine if the specified record is to be logged.

Returns True if the record should be logged, or False otherwise. If deemed appropriate, the record may be modified in-place.




semantic_release.cli.util module

Utilities for command-line functionality

Convenience function for text-formatting for the console.

Ensures the least indented line of the msg string is indented by prefix with consistent alignment of the remainder of msg irrespective of the level of indentation in the Python source code


Load raw configuration as a dict from the filename specified by config_filename, trying the following parsing methods:
1.
try to parse with tomli.load (guessing it's a TOML file)
2.
try to parse with json.load (guessing it's a JSON file)
3.
raise InvalidConfiguration if none of the above parsing methods work

This function will also raise FileNotFoundError if it is raised while trying to read the specified configuration file


Rich-prints a msg with a standard prefix to report when an action is not being taken due to a "noop" flag

Attempts to parse raw configuration for semantic_release using tomlkit.loads, raising InvalidConfiguration if the TOML is invalid or there's no top level "semantic_release" or "tool.semantic_release" keys

Rich-prints to stderr so that redirection of command output isn't cluttered

semantic_release.commit_parser package

Submodules

semantic_release.commit_parser.angular module

Angular commit style parser https://github.com/angular/angular/blob/master/CONTRIBUTING.md#-commit-message-guidelines


Bases: ParserOptions

Options dataclass for AngularCommitParser

All commit-type prefixes that are allowed.

These are used to identify a valid commit message. If a commit message does not start with one of these prefixes, it will not be considered a valid commit message.


The minimum bump level to apply to valid commit message.

Commit-type prefixes that should result in a minor release bump.

Commit-type prefixes that are allowed but do not result in a version bump.

Commit-type prefixes that should result in a patch release bump.

A mapping of commit tags to the level bump they should result in.


semantic_release.commit_parser.emoji module

Commit parser which looks for emojis to determine the type of commit

Bases: CommitParser[ParsedCommit | ParseError, EmojiParserOptions]

Parse a commit using an emoji in the subject line. When multiple emojis are encountered, the one with the highest bump level is used. If there are multiple emojis on the same level, the we use the one listed earliest in the configuration. If the message does not contain any known emojis, then the level to bump will be 0 and the type of change "Other". This parser never raises UnknownCommitMessageStyleError. Emojis are not removed from the description, and will appear alongside the commit subject in the changelog.



Attempt to parse the commit message with a regular expression into a ParseResult


alias of EmojiParserOptions


Bases: ParserOptions

Options dataclass for EmojiCommitParser


The minimum bump level to apply to valid commit message.

Commit-type prefixes that should result in a major release bump.


Commit-type prefixes that are allowed but do not result in a version bump.

Whether to parse linked issues from the commit message.

Issue identification is not defined in the Gitmoji specification, so this parser will not attempt to parse issues by default. If enabled, the parser will use the same identification as GitHub, GitLab, and BitBucket use for linking issues, which is to look for a git commit message footer starting with "Closes:", "Fixes:", or "Resolves:" then a space, and then the issue identifier. The line prefix can be singular or plural and it is not case-sensitive but must have a colon and a whitespace separator.



A mapping of commit tags to the level bump they should result in.


semantic_release.commit_parser.scipy module

Parses commit messages using scipy tags of the form:

<tag>(<scope>): <subject>
<body>


The elements <tag>, <scope> and <body> are optional. If no tag is present, the commit will be added to the changelog section "None" and no version increment will be performed.

While <scope> is supported here it isn't actually part of the scipy style. If it is missing, parentheses around it are too. The commit should then be of the form:

<tag>: <subject>
<body>


To communicate a breaking change add "BREAKING CHANGE" into the body at the beginning of a paragraph. Fill this paragraph with information how to migrate from the broken behavior to the new behavior. It will be added to the "Breaking" section of the changelog.

Supported Tags:

(

API,
DEP,
ENH,
REV,
BUG,
MAINT,
BENCH,
BLD, ) DEV, DOC, STY, TST, REL, FEAT, TEST


Supported Changelog Sections:

breaking, feature, fix, Other, None



Bases: AngularParserOptions

Options dataclass for ScipyCommitParser

Scipy-style commit messages follow the same format as Angular-style commit just with different tag names.

All commit-type prefixes that are allowed.

These are used to identify a valid commit message. If a commit message does not start with one of these prefixes, it will not be considered a valid commit message.


The minimum bump level to apply to valid commit message.

Commit-type prefixes that should result in a major release bump.

Commit-type prefixes that should result in a minor release bump.

Commit-type prefixes that should result in a patch release bump.


semantic_release.commit_parser.tag module

Legacy commit parser from Python Semantic Release 1.0

Bases: CommitParser[ParsedCommit | ParseError, TagParserOptions]

Parse a commit message according to the 1.0 version of python-semantic-release. It expects a tag of some sort in the commit message and will use the rest of the first line as changelog content.



alias of TagParserOptions



semantic_release.commit_parser.token module

Bases: NamedTuple

A read-only named tuple object representing an error that occurred while parsing a commit message.

The original commit object (a class defined by GitPython) that was parsed

A string with a description for why the commit parsing failed.

A hex representation of the hash value of the commit.

This is a pass through property for convience to access the hexsha attribute of the commit.


A string representation of the commit message.

This is a pass through property for convience to access the message attribute of the commit object.

If the message is of type bytes then it will be decoded to a UTF-8 string.


A convience method to raise a CommitParseError with the error message.

A short representation of the hash value (in hex) of the commit.


Bases: NamedTuple

A read-only named tuple object representing the result of parsing a commit message.

A list of paragraphs which are deemed to identify and describe breaking changes by the parser.

An example would be a paragraph which begins with the text BREAKING CHANGE: in the commit message but the parser gennerally strips the prefix and includes the rest of the paragraph in this list.


A LevelBump enum value indicating what type of change this commit introduces.

The original commit object (a class defined by GitPython) that was parsed

A list of paragraphs from the commit message.

Paragraphs are generally delimited by a double-newline since git commit messages are sometimes manually wordwrapped with a single newline, but this is up to the parser to implement.


A convience method to create a ParsedCommit object from a ParsedMessageResult object and a Commit object.

A hex representation of the hash value of the commit.

This is a pass through property for convience to access the hexsha attribute of the commit.


A boolean value indicating whether this commit should be included in the changelog.

This enables parsers to flag commits which are not user-facing or are otherwise not relevant to the changelog to be filtered out by PSR's internal algorithms.


A tuple of issue numbers as strings, if the commit is contains issue references.

If there are no issue references, this should be an empty tuple. Although, we generally refer to them as "issue numbers", it generally should be a string to adhere to the prefixes used by the VCS (ex. # for GitHub, GitLab, etc.) or issue tracker (ex. JIRA uses AAA-###).


A pull request or merge request definition, if the commit is labeled with a pull/merge request number.

This is a string value which includes any special character prefix used by the VCS (e.g. # for GitHub, ! for GitLab).


An alias to the linked_merge_request attribute.

A string representation of the commit message.

This is a pass through property for convience to access the message attribute of the commit object.

If the message is of type bytes then it will be decoded to a UTF-8 string.


The scope, as a string, parsed from the commit.

Generally an optional field based on the commit message style which means it very likely can be an empty string. Commit styles which do not have a meaningful concept of "scope" usually fill this field with an empty string.


A short representation of the hash value (in hex) of the commit.

The type of the commit as a string, per the commit message style.

This is up to the parser to implement; for example, the EmojiCommitParser parser fills this field with the emoji representing the most significant change for the commit.



Bases: NamedTuple

A read-only named tuple object representing the result from parsing a commit message.

Essentially this is a data structure which holds the parsed information from a commit message without the actual commit object itself. Very helpful for unit testing.

Most of the fields will replicate the fields of a ParsedCommit

Alias for field number 5

Alias for field number 0

Alias for field number 2

Alias for field number 4

Alias for field number 8

Alias for field number 6

Alias for field number 7

Alias for field number 3

Alias for field number 1


semantic_release.commit_parser.util module

This will take a text block and return a list containing each paragraph with single line breaks collapsed into spaces.

To handle Windows line endings, carriage returns 'r' are removed before separating into paragraphs.

It will attempt to detect Git footers and they will not be condensed.

text -- The text string to be divided.
A list of condensed paragraphs, as strings.



semantic_release.hvcs package

Submodules

semantic_release.hvcs.bitbucket module

Helper code for interacting with a Bitbucket remote VCS

Bases: RemoteHvcsBase

Bitbucket HVCS interface for interacting with BitBucket repositories

This class supports the following products:

  • BitBucket Cloud
  • BitBucket Data Center Server (on-premises installations)



This interface does its best to detect which product is configured based on the provided domain. If it is the official bitbucket.org, the default domain, then it is considered as BitBucket Cloud which uses the subdomain api.bitbucket.org/2.0 for api communication.

If the provided domain is anything else, than it is assumed to be communicating with an on-premise or 3rd-party maintained BitBucket instance which matches with the BitBucket Data Center Server product. The on-prem server product uses a path prefix for handling api requests which is configured to be server.domain/rest/api/1.0 based on the documentation in April 2024.








Get the Bitbucket comparison link between two version tags. :param from_rev: The older version to compare. :param to_rev: The newer version to compare. :return: Link to view a comparison between the two versions.

Create or update a release for the given tag in a remote VCS, attaching the given changelog, if supported

Create a release in a remote VCS, if supported

Which includes uploading any assets as part of the release


Return a list of functions that can be used as filters in a Jinja2 template

ex. filters to convert text to URLs for issues and commits



Get the remote url including the token for authentication if requested

Upload built distributions to a release on a remote VCS that supports such uploads


semantic_release.hvcs.gitea module

Helper code for interacting with a Gitea remote VCS

Bases: RemoteHvcsBase

Gitea helper class




Get the correct upload url for a release https://gitea.com/api/swagger#/repository/repoCreateReleaseAttachment :param release_id: ID of the release to upload to


Post release changelog :param version: The version number :param changelog: The release notes for this version
The status of the request


Create a new release

Ref: https://gitea.com/api/swagger#/repository/repoCreateRelease

  • tag -- Tag to create release for
  • release_notes -- The release notes for this version
  • prerelease -- Whether or not this release should be specified as a prerelease

Whether the request succeeded


Edit a release with updated change notes https://gitea.com/api/swagger#/repository/repoEditRelease :param id: ID of release to update :param release_notes: The release notes for this version
The ID of the release that was edited


Return a list of functions that can be used as filters in a Jinja2 template

ex. filters to convert text to URLs for issues and commits


Get a release by its tag name https://gitea.com/api/swagger#/repository/repoGetReleaseByTag :param tag: Tag to get release for
ID of found release




Get the remote url including the token for authentication if requested

Upload distributions to a release :param tag: Tag to upload for :param path: Path to the dist directory
The number of distributions successfully uploaded


Upload an asset to an existing release https://gitea.com/api/swagger#/repository/repoCreateReleaseAttachment :param release_id: ID of the release to upload to :param file: Path of the file to upload :param label: this parameter has no effect
The status of the request



semantic_release.hvcs.github module

Helper code for interacting with a GitHub remote VCS

Bases: RemoteHvcsBase

GitHub HVCS interface for interacting with GitHub repositories

This class supports the following products:

  • GitHub Free, Pro, & Team
  • GitHub Enterprise Cloud
  • GitHub Enterprise Server (on-premises installations)



This interface does its best to detect which product is configured based on the provided domain. If it is the official github.com, the default domain, then it is considered as GitHub Enterprise Cloud which uses the subdomain api.github.com for api communication.

If the provided domain is anything else, than it is assumed to be communicating with an on-premise or 3rd-party maintained GitHub instance which matches with the GitHub Enterprise Server product. The on-prem server product uses a path prefix for handling api requests which is configured to be server.domain/api/v3 based on the documentation in April 2024.








Get the correct upload url for a release https://docs.github.com/en/enterprise-server@3.5/rest/releases/releases#get-a-release :param release_id: ID of the release to upload to :return: URL to upload for a release if found, else None


Get the GitHub comparison link between two version tags. :param from_rev: The older version to compare. :param to_rev: The newer version to compare. :return: Link to view a comparison between the two versions.

Post release changelog :param tag: The version number :param release_notes: The release notes for this version :param prerelease: Whether or not this release should be created as a prerelease :return: The status of the request

Create a new release

REF: https://docs.github.com/rest/reference/repos#create-a-release

  • tag -- Tag to create release for
  • release_notes -- The release notes for this version
  • prerelease -- Whether or not this release should be created as a prerelease
  • assets -- a list of artifacts to upload to the release

the ID of the release


Edit a release with updated change notes https://docs.github.com/rest/reference/repos#update-a-release :param release_id: ID of release to update :param release_notes: The release notes for this version :return: The ID of the release that was edited

Return a list of functions that can be used as filters in a Jinja2 template

ex. filters to convert text to URLs for issues and commits


Get a release by its tag name https://docs.github.com/rest/reference/repos#get-a-release-by-tag-name :param tag: Tag to get release for :return: ID of release, if found, else None



Get the remote url including the token for authentication if requested

Upload distributions to a release :param tag: Version to upload for :param dist_glob: Path to the dist directory :return: The number of distributions successfully uploaded

Upload an asset to an existing release https://docs.github.com/rest/reference/repos#upload-a-release-asset :param release_id: ID of the release to upload to :param file: Path of the file to upload :param label: Optional custom label for this file :return: The status of the request


semantic_release.hvcs.gitlab module

Helper code for interacting with a Gitlab remote VCS

Bases: RemoteHvcsBase

Gitlab HVCS interface for interacting with Gitlab repositories





Create or update a release for the given tag in a remote VCS.
  • tag -- The tag to create or update the release for
  • release_notes -- The changelog description for this version only
  • prerelease -- This parameter has no effect in GitLab

The release id
  • ValueError -- If the release could not be created or updated
  • gitlab.exceptions.GitlabAuthenticationError -- If the user is not authenticated
  • GitlabUpdateError -- If the server cannot perform the request



Create a release in a remote VCS, adding any release notes and assets to it
  • tag -- The tag to create the release for
  • release_notes -- The changelog description for this version only
  • prerelease -- This parameter has no effect in GitLab
  • assets -- A list of paths to files to upload as assets (TODO: not implemented)
  • noop -- If True, do not perform any actions, only log intents

The tag of the release
GitlabAuthenticationError: If authentication is not correct
GitlabCreateError: If the server cannot perform the request


Update the release notes for a given release.
  • release -- The release object to update
  • release_notes -- The new release notes

The release id
GitlabAuthenticationError: If authentication is not correct
GitlabUpdateError: If the server cannot perform the request


Return a list of functions that can be used as filters in a Jinja2 template

ex. filters to convert text to URLs for issues and commits


Get a release by its tag name.
tag -- The tag name to get the release for
gitlab.v4.objects.ProjectRelease or None if not found
gitlab.exceptions.GitlabAuthenticationError: If the user is not authenticated






Get the remote url including the token for authentication if requested

Upload built distributions to a release on a remote VCS that supports such uploads


semantic_release.hvcs.remote_hvcs_base module

Common functionality and interface for interacting with Git remote VCS

Bases: HvcsBase

Interface for subclasses interacting with a remote VCS

This abstract class is defined to provide common helper functions and a set of basic methods that all remote VCS environments usually support.

If the remote vcs implementation (via subclass) does not support a functionality then it can just call super()'s method which defaults as a non-supported log message and empty results. This is more straightforward than checking for NotImplemented around every function call in the core library code.




Create or update a release for the given tag in a remote VCS, attaching the given changelog, if supported

Create a release in a remote VCS, if supported

Which includes uploading any assets as part of the release





Upload built distributions to a release on a remote VCS that supports such uploads


semantic_release.hvcs.token_auth module

Bases: AuthBase

requests Authentication for token based authorization. This allows us to attach the Authorization header with a token to a session.


semantic_release.hvcs.util module

Create a requests session.
  • raise_for_status -- If True, a hook to invoke raise_for_status be installed
  • retry -- If true, it will use default Retry configuration. if an integer, it will use default Retry configuration with given integer as total retry count. if Retry instance, it will use this instance.
  • auth -- Optional TokenAuth instance to be used to provide the Authorization header to the session

configured requests Session


For the codes given, return a decorator that will suppress HTTPErrors that are raised from responses that came with one of those status codes. The function will return False instead of raising the HTTPError


semantic_release.version package

Submodules

semantic_release.version.algorithm module


Return a list of 2-tuples, where each element is a tuple (tag, version) from the tags in the Git repo and their corresponding Version according to Version.from_tag. The returned list is sorted according to semver ordering rules.

Tags which are not matched by translator are ignored.


semantic_release.version.declaration module

Bases: VersionDeclarationABC

VersionDeclarationABC implementation representing a version number in a particular file. The version number is identified by a regular expression, which should be provided in search_text.

Return the versions matching this pattern. Because a pattern can match in multiple places, this method returns a set of matches. Generally, there should only be one element in this set (i.e. even if the version is specified in multiple places, it should be the same version in each place), but it falls on the caller to check for this condition.

Update the versions. This method reads the underlying file, replaces each occurrence of the matched pattern, then writes the updated file. :param new_version: The new version number as a Version instance


Bases: VersionDeclarationABC

VersionDeclarationABC implementation which manages toml-format source files.

Look for the version in the source content

Replace the version in the source content with new_version, and return the updated content.


Bases: ABC

ABC for classes representing a location in which a version is declared somewhere within the source tree of the repository

The content of the source file in which the version is stored. This property is cached in the instance variable _content

Return a set of the versions which can be parsed from the file. Because a source can match in multiple places, this method returns a set of matches. Generally, there should only be one element in this set (i.e. even if the version is specified in multiple places, it should be the same version in each place), but enforcing that condition is not mandatory or expected.

Update the versions. This method reads the underlying file, replaces each occurrence of the matched pattern, then writes the updated file. :param new_version: The new version number as a Version instance

Write new content back to the source path. Use alongside .replace(): >>> class MyVD(VersionDeclarationABC): ... def parse(self): ... ... def replace(self, new_version: Version): ... ... def write(self, content: str): ...

>>> new_version = Version.parse("1.2.3")
>>> vd = MyVD("path", r"__version__ = (?P<version>\d+\d+\d+)")
>>> vd.write(vd.replace(new_version))
    


semantic_release.version.translator module

Bases: object

Class to handle translation from Git tags into their corresponding Version instances.

Return a Version instance from a string. Delegates directly to Version.parse, using the translator's own stored values for tag_format and prerelease

Return a Version instance from a Git tag, if tag_format matches the format which would have generated the tag from a version. Otherwise return None. For example, a tag of 'v1.2.3' should be matched if tag_format = 'v{version}, but not if tag_format = staging--v{version}.

Formats a version string into a tag name


semantic_release.version.version module

Bases: object


Return a new Version instance according to the level specified to bump. Note this will intentionally drop the build metadata - that should be added elsewhere for the specific build producing this version.



Parse version string to a Version instance. Inspired by semver.version:VersionInfo.parse, this implementation doesn't allow optional minor and patch versions.
prerelease_token -- will be ignored if the version string is a prerelease, the parsed token from version_str will be used instead.





Submodules

semantic_release.const module

semantic_release.enums module

Bases: IntEnum

IntEnum representing valid types of bumps for a version. We use an IntEnum to enable ordering of levels.






Get the level from string representation. For backwards-compatibility, dashes are replaced with underscores so that: >>> LevelBump.from_string("no-release") == LevelBump.NO_RELEASE Equally, >>> LevelBump.from_string("minor") == LevelBump.MINOR



semantic_release.errors module

Custom Errors

Bases: SemanticReleaseBaseError

Raised when there is a failure uploading an asset to a remote hvcs's release artifact storage.


Bases: SemanticReleaseBaseError

Raised when there is a failure to build the distribution files.


Bases: SemanticReleaseBaseError

Raised when a commit cannot be parsed by a commit parser. Custom commit parsers should also raise this Exception


Bases: SemanticReleaseBaseError

Raised when the git repository is in a detached HEAD state


Bases: SemanticReleaseBaseError

Raised when there is a failure to add files to the git index.


Bases: SemanticReleaseBaseError

Raised when there is an attempt to commit an empty index.


Bases: SemanticReleaseBaseError

Raised when there is a failure to commit the changes.


Bases: SemanticReleaseBaseError

Raised when there is a failure to push to the git remote.


Bases: SemanticReleaseBaseError

Raised when there is a failure to tag the release.


Bases: SemanticReleaseBaseError

Raised when there is a failure amongst one of the api requests when creating a release on a remote hvcs.


Bases: SemanticReleaseBaseError

Raised when an internal error occurs, which should never happen


Bases: SemanticReleaseBaseError

Raised when configuration is deemed invalid


Bases: InvalidConfiguration

Raised when the parser options are invalid


Bases: ValueError, SemanticReleaseBaseError

Raised when Version.parse attempts to parse a string containing an invalid version.


Bases: SemanticReleaseBaseError

Raised when repository is missing the configured remote origin or upstream


Bases: SemanticReleaseBaseError

Raised when the merge base cannot be found with the current history. Generally because of a shallow git clone.


Bases: InvalidConfiguration

Raised when semantic_release is invoked on a branch which isn't configured for releases


Bases: SemanticReleaseBaseError

Raised when there is a failure to find, load, or instantiate a custom parser definition.


Bases: Exception

Base Exception from which all other custom Exceptions defined in semantic_release inherit


Bases: SemanticReleaseBaseError

Raised when an HTTP response cannot be parsed properly or the expected structure is not found.


semantic_release.gitproject module

Module for git related operations.


semantic_release.globals module

Semantic Release Global Variables.

bool: Enable debug level logging and runtime actions.

semantic_release.helpers module

Bases: NamedTuple

Container for the elements parsed from a git URL

Alias for field number 2

Alias for field number 1

Alias for field number 3

Alias for field number 0



Dynamically import an object from a conventionally formatted "module:attribute" string

Helper to format an argument an argument for logging

Decorator which adds debug logging of a function's input arguments and return value.

The input arguments are logged before the function is called, and the return value is logged once it has completed.

logger -- Logger to send output to.


Attempt to parse a string as a git url http[s]://, git://, file://, or ssh format, into a ParsedGitUrl.
http://git.mycompany.com/username/myproject.git https://github.com/username/myproject.git https://gitlab.com/group/subgroup/myproject.git https://git.mycompany.com:4443/username/myproject.git git://host.xz/path/to/repo.git/ git://host.xz:9418/path/to/repo.git/ git@github.com:username/myproject.git <-- assumes ssh:// ssh://git@github.com:3759/myproject.git <-- non-standard, but assume user 3759 ssh://git@github.com:username/myproject.git ssh://git@bitbucket.org:7999/username/myproject.git git+ssh://git@github.com:username/myproject.git /Users/username/dev/remote/myproject.git <-- Posix File paths file:///Users/username/dev/remote/myproject.git C:/Users/username/dev/remote/myproject.git <-- Windows File paths file:///C:/Users/username/dev/remote/myproject.git

REFERENCE: https://stackoverflow.com/questions/31801271/what-are-the-supported-git-url-formats

Raises ValueError if the url can't be parsed.


Python Semantic Release's Version Bumping Algorithm

Below is a technical description of the algorithm which Python Semantic Release uses to calculate a new version for a project.

Assumptions

  • At runtime, we are in a Git repository with HEAD referring to a commit on some branch of the repository (i.e. not in detached HEAD state).
  • We know in advance whether we want to produce a prerelease or not (based on the configuration and command-line flags).
  • We can parse the tags of the repository into semantic versions, as we are given the format that those Git tags should follow via configuration, but cannot cherry-pick only tags that apply to commits on specific branches. We must parse all tags in order to ensure we have parsed any that might apply to commits in this branch's history.
  • If we can identify a commit as a merge-base between our HEAD commit and one or more tags, then that merge-base should be unique.
  • We know ahead of time what prerelease_token to use for prereleases - e.g. rc.
  • We know ahead of time whether major changes introduced by commits should cause the new version to remain on 0.y.z if the project is already on a 0. version - see major_on_zero.

Implementation

1.
Parse all the Git tags of the repository into semantic versions, and sort in descending (most recent first) order according to semver precedence. Ignore any tags which do not correspond to valid semantic vesrions according to tag_format.
2.
Find the merge-base of HEAD and the latest tag according to the sort above. Call this commit M. If there are no tags in the repo's history, we set M=HEAD.
3.
Find the latest non-prerelease version whose tag references a commit that is an ancestor of M. We do this via a breadth-first search through the commit lineage, starting against M, and for each tag checking if the tag corresponds to that commit. We break from the search when we find such a tag. If no such tag is found, see 4a). Else, suppose that tag corresponds to a commit L - goto 4b).
4.
If no commit corresponding to the last non-prerelease version is found, the entire history of the repository is considered. We parse every commit that is an ancestor of HEAD to determine the type of change introduced - either major, minor, patch, prerelease_revision or no_release. We store this levels in a set as we only require the distinct types of change that were introduced.
However, if we found a commit L which is the commit against which the last non-prerelease was tagged, then we parse only the commits from HEAD as far back as L, to understand what changes have been introduced since the previous non-prerelease. We store these levels - either major, minor, patch, prerelease_revision, or no_release, in a set, as we only require the distinct types of change that were introduced.
We look for tags that correspond to each commit during this process, to identify the latest pre-release that was made within HEAD's ancestry.

5.
If there have been no changes since the last non-prerelease, or all commits since that release result in a no_release type according to the commit parser, then we terminate the algorithm.
6.
If we have not exited by this point, we know the following information:

  • The latest version, by semver precedence, within the whole repository. Call this LV. This might not be within the ancestry of HEAD.
  • The latest version, prerelease or non-prerelease, within the whole repository. Call this LVH. This might not be within the ancestry of HEAD. This may be the same as LV.
  • The latest non-prerelease version within the ancestry of HEAD. Call this LVHF. This may be the same as LVH.
  • The most significant type of change introduced by the commits since the previous full release. Call this level
  • Whether or not we wish to produce a prerelease from this version increment. Call this a boolean flag, prerelease. (Assumption)
  • Whether or not to increment the major digit if a major change is introduced against an existing 0. version. Call this major_on_zero, a boolean flag. (Assumption)

Using this information, the new version is decided according to the following criteria:

If LV has a major digit of 0, major_on_zero is False and level is major, reduce level to minor.
If prerelease=True, then
Diff LV with LVHF, to understand if the major, minor or patch digits have changed. For example, diffing 1.2.1 and 1.2.0 is a patch diff, while diffing 2.1.1 and 1.17.2 is a major diff. Call this DIFF
If DIFF is less semantically significant than level, for example if DIFF=patch and level=minor, then
1.
Increment the digit of LVF corresponding to level, for example the minor digit if level=minor, setting all less significant digits to zero.
2.
Add prerelease_token as a suffix result of 1., together with a prerelease revision number of 1. Return this new version and terminate the algorithm.

Thus if DIFF=patch, level=minor, prerelease=True, prerelease_token="rc", and LVF=1.1.1, then the version returned by the algorithm is 1.2.0-rc.1.

If DIFF is semantically less significant than or equally significant to level, then this means that the significance of change introduced by level is already reflected in a prerelease version that has been created since the last full release. For example, if LVHF=1.1.1, LV=1.2.0-rc.1 and level=minor.

In this case we:

1.
If the prerelease token of LV is different from prerelease_token, take the major, minor and patch digits of LV and construct a prerelease version using our given prerelease_token and a prerelease revision of 1. We then return this version and terminate the algorithm.

For example, if LV=1.2.0-rc.1 and prerelease_token=alpha, we return 1.2.0-alpha.1.

2.
If the prerelease token of LV is the same as prerelease_token, we increment the revision number of LV, return this version, and

terminate the algorithm. For example, if LV=1.2.0-rc.1 and prerelease_token=rc, we return 1.2.0-rc.2.



If prerelease=False, then

If LV is not a prerelease, then we increment the digit of LV corresponding to level, for example the minor digit if level=minor, setting all less significant digits to zero. We return the result of this and terminate the algorithm.
If LV is a prerelease, then:

1.
Diff LV with LVHF, to understand if the major, minor or patch digits have changed. Call this DIFF
2.
If DIFF is less semantically significant than level, then

Increment the digit of LV corresponding to level, for example the minor digit if level=minor, setting all less significant digits to zero.
Remove the prerelease token and revision number from the result of i., ("Finalize" the result of i.) return the result and terminate the algorithm.

For example, if LV=1.2.2-alpha.1 and level=minor, we return 1.3.0.




3.
If DIFF is semantically less significant than or equally significant to level, then we finalize LV, return the result and terminate the algorithm.







Complexity

Space:

A list of parsed tags takes O(number of tags) in space. Parsing each commit during the breadth-first search between merge-base and the latest tag in the ancestry of HEAD takes at worst O(number of commits) in space to track visited commits. Therefore worst-case space complexity will be linear in the number of commits in the repo, unless the number of tags significantly exceeds the number of commits (in which case it will be linear in the number of tags).

Time:

Assuming using regular expression parsing of each tag is a constant-time operation, then the following steps contribute to the time complexity of the algorithm:

  • Parsing each tag - O(number of tags)
  • Sorting tags by semver precedence - O(number of tags * log(number of tags))
  • Finding the merge-base of HEAD and the latest release tag - O(number of commits) (worst case)
  • Parsing each commit and checking each tag against each commit - O(number of commits) + O(number of tags * number of commits) (worst case)

Overall, assuming that the number of tags is less than or equal to the number of commits in the repository, this would lead to a worst-case time complexity that's quadratic in the number of commits in the repo.

GETTING STARTED

If you haven't done so already, install Python Semantic Release following the instructions above.

There is no strict requirement to have it installed locally if you intend on using a CI service, however running with --noop can be useful to test your configuration.

Generating your configuration

Python Semantic Release ships with a command-line interface, semantic-release. You can inspect the default configuration in your terminal by running

semantic-release generate-config

You can also use the -f/--format option to specify what format you would like this configuration to be. The default is TOML, but JSON can also be used.

You can append the configuration to your existing pyproject.toml file using a standard redirect, for example:

semantic-release generate-config --pyproject >> pyproject.toml

and then editing to your project's requirements.

SEE ALSO:

  • semantic-release generate-config
  • Configuration



Setting up version numbering

Create a variable set to the current version number. This could be anywhere in your project, for example setup.py:

from setuptools import setup
__version__ = "0.0.0"
setup(

name="my-package",
version=__version__,
# And so on... )


Python Semantic Release can be configured using a TOML or JSON file; the default configuration file is pyproject.toml, if you wish to use another file you will need to use the -c/--config option to specify the file.

Set version_variables to a list, the only element of which should be the location of your version variable inside any Python file, specified in standard module:attribute syntax:

pyproject.toml:

[tool.semantic_release]
version_variables = ["setup.py:__version__"]


SEE ALSO:

Configuration - tailor Python Semantic Release to your project



Setting up commit parsing

We rely on commit messages to detect when a version bump is needed. By default, Python Semantic Release uses the Angular style. You can find out more about this in Commit Parsing.

SEE ALSO:

  • branches - Adding configuration for releases from multiple branches.
  • commit_parser - use a different parser for commit messages. For example, Python Semantic Release also ships with emoji and scipy-style parsers.
  • remote.type - specify the type of your remote VCS.



Setting up the changelog

SEE ALSO:

  • Changelog - Customize the changelog generated by Python Semantic Release.
  • Migrating an Existing Changelog



Creating VCS Releases

You can set up Python Semantic Release to create Releases in your remote version control system, so you can publish assets and release notes for your project.

In order to do so, you will need to place an authentication token in the appropriate environment variable so that Python Semantic Release can authenticate with the remote VCS to push tags, create releases, or upload files.

GitHub (GH_TOKEN)

For local publishing to GitHub, you should use a personal access token and store it in your environment variables. Specify the name of the environment variable in your configuration setting remote.token. The default is GH_TOKEN.

To generate a token go to https://github.com/settings/tokens and click on "Generate new token".

For Personal Access Token (classic), you will need the repo scope to write (ie. push) to the repository.

For fine-grained Personal Access Tokens, you will need the contents permission.

GitLab (GITLAB_TOKEN)

A personal access token from GitLab. This is used for authenticating when pushing tags, publishing releases etc. This token should be stored in the GITLAB_TOKEN environment variable.

Gitea (GITEA_TOKEN)

A personal access token from Gitea. This token should be stored in the GITEA_TOKEN environment variable.

Bitbucket (BITBUCKET_TOKEN)

Bitbucket does not support uploading releases but can still benefit from automated tags and changelogs. The user has three options to push changes to the repository:

1.
Use SSH keys.
2.
Use an App Secret, store the secret in the BITBUCKET_TOKEN environment variable and the username in BITBUCKET_USER.
3.
Use an Access Token for the repository and store it in the BITBUCKET_TOKEN environment variable.

SEE ALSO:

  • Changelog - customize your project's changelog.
  • Custom Release Notes - customize the published release notes
  • upload_to_vcs_release - enable/disable uploading artefacts to VCS releases
  • version --vcs-release/--no-vcs-release - enable/disable VCS release creation.
  • upload-to-gh-release, a GitHub Action for running semantic-release publish



Running from setup.py

Add the following hook to your setup.py and you will be able to run python setup.py <command> as you would semantic-release <command>:

try:

from semantic_release import setup_hook
setup_hook(sys.argv) except ImportError:
pass


NOTE:

Only the version, publish, and changelog commands may be invoked from setup.py in this way.


Running on CI

Getting a fully automated setup with releases from CI can be helpful for some projects. See Automatic Releases.

AUTHOR

Python Semantic Release Team

COPYRIGHT

2024, Python Semantic Release Team

December 19, 2024 9.15.2