Latest commit

History

History
433 lines (340 loc) · 20.5 KB

File metadata and controls

433 lines (340 loc) · 20.5 KB

Customizing commitizen is not hard at all. We have two different ways to do so.

1. Customize in configuration file

The basic steps are:

  1. Define your custom committing or bumping rules in the configuration file.
  2. Declare name = "cz_customize" in your configuration file, or add -n cz_customize when running commitizen.

Example:

[tool.commitizen]
name = "cz_customize"
[tool.commitizen.customize]
message_template = "{{change_type}}:{% if show_message %} {{message}}{% endif %}"example = "feature: this feature enable customize through config file"schema = "<type>: <body>"schema_pattern = "(feature|bug fix):(\\s.*)"bump_pattern = "^(break|new|fix|hotfix)"bump_map = {"break" = "MAJOR", "new" = "MINOR", "fix" = "PATCH", "hotfix" = "PATCH"}
change_type_order = ["BREAKING CHANGE", "feat", "fix", "refactor", "perf"]
info_path = "cz_customize_info.txt"info = """This is customized info"""commit_parser = "^(?P<change_type>feature|bug fix):\\s(?P<message>.*)?"changelog_pattern = "^(feature|bug fix)?(!)?"change_type_map = {"feature" = "Feat", "bug fix" = "Fix"}
[[tool.commitizen.customize.questions]]
type = "list"name = "change_type"choices = [{value = "feature", name = "feature: A new feature."}, {value = "bug fix", name = "bug fix: A bug fix."}]
# choices = ["feature", "fix"] # short versionmessage = "Select the type of change you are committing"
[[tool.commitizen.customize.questions]]
type = "input"name = "message"message = "Body."
[[tool.commitizen.customize.questions]]
type = "confirm"name = "show_message"message = "Do you want to add body message in commit?"

The equivalent example for a json config file:

{
"commitizen": {
"name": "cz_customize",
"customize": {
"message_template": "{{change_type}}:{% if show_message %} {{message}}{% endif %}",
"example": "feature: this feature enable customize through config file",
"schema": "<type>: <body>",
"schema_pattern": "(feature|bug fix):(\\s.*)",
"bump_pattern": "^(break|new|fix|hotfix)",
"bump_map": {
"break": "MAJOR",
"new": "MINOR",
"fix": "PATCH",
"hotfix": "PATCH"
},
"change_type_order": ["BREAKING CHANGE", "feat", "fix", "refactor", "perf"],
"info_path": "cz_customize_info.txt",
"info": "This is customized info",
"commit_parser": "^(?P<change_type>feature|bug fix):\\s(?P<message>.*)?",
"changelog_pattern": "^(feature|bug fix)?(!)?",
"change_type_map": {"feature": "Feat", "bug fix": "Fix"},
"questions": [
{
"type": "list",
"name": "change_type",
"choices": [
{
"value": "feature",
"name": "feature: A new feature."
},
{
"value": "bug fix",
"name": "bug fix: A bug fix."
}
],
"message": "Select the type of change you are committing"
},
{
"type": "input",
"name": "message",
"message": "Body."
},
{
"type": "confirm",
"name": "show_message",
"message": "Do you want to add body message in commit?"
}
]
}
}
}

And the correspondent example for a yaml json file:

commitizen:
name: cz_customizecustomize:
message_template: "{{change_type}}:{% if show_message %} {{message}}{% endif %}"example: 'feature: this feature enable customize through config file'schema: "<type>: <body>"schema_pattern: "(feature|bug fix):(\\s.*)"bump_pattern: "^(break|new|fix|hotfix)"commit_parser: "^(?P<change_type>feature|bug fix):\\s(?P<message>.*)?",changelog_pattern: "^(feature|bug fix)?(!)?",change_type_map:
feature: Featbug fix: Fixbump_map:
break: MAJORnew: MINORfix: PATCHhotfix: PATCHchange_type_order: ["BREAKING CHANGE", "feat", "fix", "refactor", "perf"]info_path: cz_customize_info.txtinfo: This is customized infoquestions:
- type: listname: change_typechoices:
- value: featurename: 'feature: A new feature.'
- value: bug fixname: 'bug fix: A bug fix.'message: Select the type of change you are committing
- type: inputname: messagemessage: Body.
- type: confirmname: show_messagemessage: Do you want to add body message in commit?

Customize configuration

ParameterTypeDefaultDescription
questionsQuestionsNoneQuestions regarding the commit message. Detailed below. The type Questions is an alias to Iterable[MutableMapping[str, Any]] which is defined in commitizen.defaults. It expects a list of dictionaries.
message_templatestrNoneThe template for generating message from the given answers. message_template should either follow Jinja2 formatting specification, and all the variables in this template should be defined in name in questions
examplestrNone(OPTIONAL) Provide an example to help understand the style. Used by cz example.
schemastrNone(OPTIONAL) Show the schema used. Used by cz schema.
schema_patternstrNone(OPTIONAL) The regular expression used to do commit message validation. Used by cz check.
info_pathstrNone(OPTIONAL) The path to the file that contains explanation of the commit rules. Used by cz info. If not provided cz info, will load info instead.
infostrNone(OPTIONAL) Explanation of the commit rules. Used by cz info.
bump_mapdictNone(OPTIONAL) Dictionary mapping the extracted information to a SemVer increment type (MAJOR, MINOR, PATCH)
bump_patternstrNone(OPTIONAL) Regex to extract information from commit (subject and body)
change_type_orderstrNone(OPTIONAL) List of strings used to order the Changelog. All other types will be sorted alphabetically. Default is ["BREAKING CHANGE", "Feat", "Fix", "Refactor", "Perf"]
commit_parserstrNone(OPTIONAL) Regex to extract information used in creating changelog. See more
changelog_patternstrNone(OPTIONAL) Regex to understand which commits to include in the changelog
change_type_mapdictNone(OPTIONAL) Dictionary mapping the type of the commit to a changelog entry

Detailed questions content

ParameterTypeDefaultDescription
typestrNoneThe type of questions. Valid type: list, input and etc. [See More][different-question-types]
namestrNoneThe key for the value answered by user. It's used in message_template
messagestrNoneDetail description for the question.
choiceslistNone(OPTIONAL) The choices when type = list. Either use a list of values or a list of dictionaries with name and value keys. Keyboard shortcuts can be defined via key. See examples above.
defaultAnyNone(OPTIONAL) The default value for this question.
filterstrNone(Optional) Validator for user's answer. (Work in Progress)
[different-question-types]: https://github.com/tmbo/questionary#different-question-types

Shortcut keys

When the use_shortcuts config option is enabled, commitizen can show and use keyboard shortcuts to select items from lists directly. For example, when using the cz_conventional_commits commitizen template, shortcut keys are shown when selecting the commit type. Unless otherwise defined, keyboard shortcuts will be numbered automatically. To specify keyboard shortcuts for your custom choices, provide the shortcut using the key parameter in dictionary form for each choice you would like to customize.

2. Customize through customizing a class

The basic steps are:

  1. Inheriting from BaseCommitizen
  2. Give a name to your rules.
  3. Create a python package using setup.py, poetry, etc
  4. Expose the class as a commitizen.plugin entrypoint

Check an example on how to configure BaseCommitizen.

You can also automate the steps above through cookiecutter.

cookiecutter gh:commitizen-tools/commitizen_cz_template

See commitizen_cz_template for details.

Once you publish your rules, you can send us a PR to the Third-party section.

Custom commit rules

Create a Python module, for example cz_jira.py.

Inherit from BaseCommitizen, and you must define questions and message. The others are optional.

fromcommitizen.cz.baseimportBaseCommitizenfromcommitizen.defaultsimportQuestionsclassJiraCz(BaseCommitizen):
# Questions = Iterable[MutableMapping[str, Any]]# It expects a list with dictionaries.defquestions(self) ->Questions:
"""Questions regarding the commit message."""questions= [
{"type": "input", "name": "title", "message": "Commit title"},
{"type": "input", "name": "issue", "message": "Jira Issue number:"},
]
returnquestionsdefmessage(self, answers: dict) ->str:
"""Generate the message with the given answers."""return"{0} (#{1})".format(answers["title"], answers["issue"])
defexample(self) ->str:
"""Provide an example to help understand the style (OPTIONAL) Used by `cz example`. """return"Problem with user (#321)"defschema(self) ->str:
"""Show the schema used (OPTIONAL) Used by `cz schema`. """return"<title> (<issue>)"definfo(self) ->str:
"""Explanation of the commit rules. (OPTIONAL) Used by `cz info`. """return"We use this because is useful"

The next file required is setup.py modified from flask version.

fromsetuptoolsimportsetupsetup(
name="JiraCommitizen",
version="0.1.0",
py_modules=["cz_jira"],
license="MIT",
long_description="this is a long description",
install_requires=["commitizen"],
entry_points={"commitizen.plugin": ["cz_jira = cz_jira:JiraCz"]},
)

So in the end, we would have

.
├── cz_jira.py
└── setup.py

And that's it. You can install it without uploading to pypi by simply doing pip install .

If you feel like it should be part of this repo, create a PR.

Custom bump rules

You need to define 2 parameters inside your custom BaseCommitizen.

ParameterTypeDefaultDescription
bump_patternstrNoneRegex to extract information from commit (subject and body)
bump_mapdictNoneDictionary mapping the extracted information to a SemVer increment type (MAJOR, MINOR, PATCH)

Let's see an example.

fromcommitizen.cz.baseimportBaseCommitizenclassStrangeCommitizen(BaseCommitizen):
bump_pattern=r"^(break|new|fix|hotfix)"bump_map= {"break": "MAJOR", "new": "MINOR", "fix": "PATCH", "hotfix": "PATCH"}

That's it, your commitizen now supports custom rules, and you can run.

cz -n cz_strange bump

Custom changelog generator

The changelog generator should just work in a very basic manner without touching anything. You can customize it of course, and this are the variables you need to add to your custom BaseCommitizen.

ParameterTypeRequiredDescription
commit_parserstrNORegex which should provide the variables explained in the changelog description
changelog_patternstrNORegex to validate the commits, this is useful to skip commits that don't meet your ruling standards like a Merge. Usually the same as bump_pattern
change_type_mapdictNOConvert the title of the change type that will appear in the changelog, if a value is not found, the original will be provided
changelog_message_builder_hookmethod: (dict, git.GitCommit) -> dictNOCustomize with extra information your message output, like adding links, this function is executed per parsed commit. Each GitCommit contains the following attrs: rev, title, body, author, author_email
changelog_hookmethod: (full_changelog: str, partial_changelog: Optional[str]) -> strNOReceives the whole and partial (if used incremental) changelog. Useful to send slack messages or notify a compliance department. Must return the full_changelog
fromcommitizen.cz.baseimportBaseCommitizenimportchatimportcomplianceclassStrangeCommitizen(BaseCommitizen):
changelog_pattern=r"^(break|new|fix|hotfix)"commit_parser=r"^(?P<change_type>feat|fix|refactor|perf|BREAKING CHANGE)(?:\((?P<scope>[^()\r\n]*)\)|\()?(?P<breaking>!)?:\s(?P<message>.*)?"change_type_map= {
"feat": "Features",
"fix": "Bug Fixes",
"refactor": "Code Refactor",
"perf": "Performance improvements",
}
defchangelog_message_builder_hook(
self, parsed_message: dict, commit: git.GitCommit
) ->dict:
rev=commit.revm=parsed_message["message"]
parsed_message[
"message"
] =f"{m}{rev} [{commit.author}]({commit.author_email})"returnparsed_messagedefchangelog_hook(
self, full_changelog: str, partial_changelog: Optional[str]
) ->str:
"""Executed at the end of the changelog generation full_changelog: it's the output about to being written into the file partial_changelog: it's the new stuff, this is useful to send slack messages or similar Return: the new updated full_changelog """ifpartial_changelog:
chat.room("#committers").notify(partial_changelog)
iffull_changelog:
compliance.send(full_changelog)
full_changelog.replace(" fix ", " **fix** ")
returnfull_changelog

Raise Customize Exception

If you want commitizen to catch your exception and print the message, you'll have to inherit CzException.

fromcommitizen.cz.exceptionimportCzExceptionclassNoSubjectProvidedException(CzException):
...

Migrating from legacy plugin format

Commitizen migrated to a new plugin format relying on importlib.metadata.EntryPoint. Migration should be straight-forward for legacy plugins:

  • Remove the discover_this line from you plugin module
  • Expose the plugin class under as a commitizen.plugin entrypoint.

The name of the plugin is now determined by the name of the entrypoint.

Example

If you were having a CzPlugin class in a cz_plugin.py module like this:

fromcommitizen.cz.baseimportBaseCommitizenclassPluginCz(BaseCommitizen):
...
discover_this=PluginCz

Then remove the discover_this line:

fromcommitizen.cz.baseimportBaseCommitizenclassPluginCz(BaseCommitizen):
...

and expose the class as entrypoint in you setuptools:

fromsetuptoolsimportsetupsetup(
name="MyPlugin",
version="0.1.0",
py_modules=["cz_plugin"],
entry_points={"commitizen.plugin": ["plugin = cz_plugin:PluginCz"]},
...,
)

Then your plugin will be available under the name plugin.

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Latest commit

History

History
433 lines (340 loc) · 20.5 KB

File metadata and controls

433 lines (340 loc) · 20.5 KB

Customizing commitizen is not hard at all. We have two different ways to do so.

1. Customize in configuration file

The basic steps are:

  1. Define your custom committing or bumping rules in the configuration file.
  2. Declare name = "cz_customize" in your configuration file, or add -n cz_customize when running commitizen.

Example:

[tool.commitizen]
name = "cz_customize"
[tool.commitizen.customize]
message_template = "{{change_type}}:{% if show_message %} {{message}}{% endif %}"example = "feature: this feature enable customize through config file"schema = "<type>: <body>"schema_pattern = "(feature|bug fix):(\\s.*)"bump_pattern = "^(break|new|fix|hotfix)"bump_map = {"break" = "MAJOR", "new" = "MINOR", "fix" = "PATCH", "hotfix" = "PATCH"}
change_type_order = ["BREAKING CHANGE", "feat", "fix", "refactor", "perf"]
info_path = "cz_customize_info.txt"info = """This is customized info"""commit_parser = "^(?P<change_type>feature|bug fix):\\s(?P<message>.*)?"changelog_pattern = "^(feature|bug fix)?(!)?"change_type_map = {"feature" = "Feat", "bug fix" = "Fix"}
[[tool.commitizen.customize.questions]]
type = "list"name = "change_type"choices = [{value = "feature", name = "feature: A new feature."}, {value = "bug fix", name = "bug fix: A bug fix."}]
# choices = ["feature", "fix"] # short versionmessage = "Select the type of change you are committing"
[[tool.commitizen.customize.questions]]
type = "input"name = "message"message = "Body."
[[tool.commitizen.customize.questions]]
type = "confirm"name = "show_message"message = "Do you want to add body message in commit?"

The equivalent example for a json config file:

{
"commitizen": {
"name": "cz_customize",
"customize": {
"message_template": "{{change_type}}:{% if show_message %} {{message}}{% endif %}",
"example": "feature: this feature enable customize through config file",
"schema": "<type>: <body>",
"schema_pattern": "(feature|bug fix):(\\s.*)",
"bump_pattern": "^(break|new|fix|hotfix)",
"bump_map": {
"break": "MAJOR",
"new": "MINOR",
"fix": "PATCH",
"hotfix": "PATCH"
},
"change_type_order": ["BREAKING CHANGE", "feat", "fix", "refactor", "perf"],
"info_path": "cz_customize_info.txt",
"info": "This is customized info",
"commit_parser": "^(?P<change_type>feature|bug fix):\\s(?P<message>.*)?",
"changelog_pattern": "^(feature|bug fix)?(!)?",
"change_type_map": {"feature": "Feat", "bug fix": "Fix"},
"questions": [
{
"type": "list",
"name": "change_type",
"choices": [
{
"value": "feature",
"name": "feature: A new feature."
},
{
"value": "bug fix",
"name": "bug fix: A bug fix."
}
],
"message": "Select the type of change you are committing"
},
{
"type": "input",
"name": "message",
"message": "Body."
},
{
"type": "confirm",
"name": "show_message",
"message": "Do you want to add body message in commit?"
}
]
}
}
}

And the correspondent example for a yaml json file:

commitizen:
name: cz_customizecustomize:
message_template: "{{change_type}}:{% if show_message %} {{message}}{% endif %}"example: 'feature: this feature enable customize through config file'schema: "<type>: <body>"schema_pattern: "(feature|bug fix):(\\s.*)"bump_pattern: "^(break|new|fix|hotfix)"commit_parser: "^(?P<change_type>feature|bug fix):\\s(?P<message>.*)?",changelog_pattern: "^(feature|bug fix)?(!)?",change_type_map:
feature: Featbug fix: Fixbump_map:
break: MAJORnew: MINORfix: PATCHhotfix: PATCHchange_type_order: ["BREAKING CHANGE", "feat", "fix", "refactor", "perf"]info_path: cz_customize_info.txtinfo: This is customized infoquestions:
- type: listname: change_typechoices:
- value: featurename: 'feature: A new feature.'
- value: bug fixname: 'bug fix: A bug fix.'message: Select the type of change you are committing
- type: inputname: messagemessage: Body.
- type: confirmname: show_messagemessage: Do you want to add body message in commit?

Customize configuration

ParameterTypeDefaultDescription
questionsQuestionsNoneQuestions regarding the commit message. Detailed below. The type Questions is an alias to Iterable[MutableMapping[str, Any]] which is defined in commitizen.defaults. It expects a list of dictionaries.
message_templatestrNoneThe template for generating message from the given answers. message_template should either follow Jinja2 formatting specification, and all the variables in this template should be defined in name in questions
examplestrNone(OPTIONAL) Provide an example to help understand the style. Used by cz example.
schemastrNone(OPTIONAL) Show the schema used. Used by cz schema.
schema_patternstrNone(OPTIONAL) The regular expression used to do commit message validation. Used by cz check.
info_pathstrNone(OPTIONAL) The path to the file that contains explanation of the commit rules. Used by cz info. If not provided cz info, will load info instead.
infostrNone(OPTIONAL) Explanation of the commit rules. Used by cz info.
bump_mapdictNone(OPTIONAL) Dictionary mapping the extracted information to a SemVer increment type (MAJOR, MINOR, PATCH)
bump_patternstrNone(OPTIONAL) Regex to extract information from commit (subject and body)
change_type_orderstrNone(OPTIONAL) List of strings used to order the Changelog. All other types will be sorted alphabetically. Default is ["BREAKING CHANGE", "Feat", "Fix", "Refactor", "Perf"]
commit_parserstrNone(OPTIONAL) Regex to extract information used in creating changelog. See more
changelog_patternstrNone(OPTIONAL) Regex to understand which commits to include in the changelog
change_type_mapdictNone(OPTIONAL) Dictionary mapping the type of the commit to a changelog entry

Detailed questions content

ParameterTypeDefaultDescription
typestrNoneThe type of questions. Valid type: list, input and etc. [See More][different-question-types]
namestrNoneThe key for the value answered by user. It's used in message_template
messagestrNoneDetail description for the question.
choiceslistNone(OPTIONAL) The choices when type = list. Either use a list of values or a list of dictionaries with name and value keys. Keyboard shortcuts can be defined via key. See examples above.
defaultAnyNone(OPTIONAL) The default value for this question.
filterstrNone(Optional) Validator for user's answer. (Work in Progress)
[different-question-types]: https://github.com/tmbo/questionary#different-question-types

Shortcut keys

When the use_shortcuts config option is enabled, commitizen can show and use keyboard shortcuts to select items from lists directly. For example, when using the cz_conventional_commits commitizen template, shortcut keys are shown when selecting the commit type. Unless otherwise defined, keyboard shortcuts will be numbered automatically. To specify keyboard shortcuts for your custom choices, provide the shortcut using the key parameter in dictionary form for each choice you would like to customize.

2. Customize through customizing a class

The basic steps are:

  1. Inheriting from BaseCommitizen
  2. Give a name to your rules.
  3. Create a python package using setup.py, poetry, etc
  4. Expose the class as a commitizen.plugin entrypoint

Check an example on how to configure BaseCommitizen.

You can also automate the steps above through cookiecutter.

cookiecutter gh:commitizen-tools/commitizen_cz_template

See commitizen_cz_template for details.

Once you publish your rules, you can send us a PR to the Third-party section.

Custom commit rules

Create a Python module, for example cz_jira.py.

Inherit from BaseCommitizen, and you must define questions and message. The others are optional.

fromcommitizen.cz.baseimportBaseCommitizenfromcommitizen.defaultsimportQuestionsclassJiraCz(BaseCommitizen):
# Questions = Iterable[MutableMapping[str, Any]]# It expects a list with dictionaries.defquestions(self) ->Questions:
"""Questions regarding the commit message."""questions= [
{"type": "input", "name": "title", "message": "Commit title"},
{"type": "input", "name": "issue", "message": "Jira Issue number:"},
]
returnquestionsdefmessage(self, answers: dict) ->str:
"""Generate the message with the given answers."""return"{0} (#{1})".format(answers["title"], answers["issue"])
defexample(self) ->str:
"""Provide an example to help understand the style (OPTIONAL) Used by `cz example`. """return"Problem with user (#321)"defschema(self) ->str:
"""Show the schema used (OPTIONAL) Used by `cz schema`. """return"<title> (<issue>)"definfo(self) ->str:
"""Explanation of the commit rules. (OPTIONAL) Used by `cz info`. """return"We use this because is useful"

The next file required is setup.py modified from flask version.

fromsetuptoolsimportsetupsetup(
name="JiraCommitizen",
version="0.1.0",
py_modules=["cz_jira"],
license="MIT",
long_description="this is a long description",
install_requires=["commitizen"],
entry_points={"commitizen.plugin": ["cz_jira = cz_jira:JiraCz"]},
)

So in the end, we would have

.
├── cz_jira.py
└── setup.py

And that's it. You can install it without uploading to pypi by simply doing pip install .

If you feel like it should be part of this repo, create a PR.

Custom bump rules

You need to define 2 parameters inside your custom BaseCommitizen.

ParameterTypeDefaultDescription
bump_patternstrNoneRegex to extract information from commit (subject and body)
bump_mapdictNoneDictionary mapping the extracted information to a SemVer increment type (MAJOR, MINOR, PATCH)

Let's see an example.

fromcommitizen.cz.baseimportBaseCommitizenclassStrangeCommitizen(BaseCommitizen):
bump_pattern=r"^(break|new|fix|hotfix)"bump_map= {"break": "MAJOR", "new": "MINOR", "fix": "PATCH", "hotfix": "PATCH"}

That's it, your commitizen now supports custom rules, and you can run.

cz -n cz_strange bump

Custom changelog generator

The changelog generator should just work in a very basic manner without touching anything. You can customize it of course, and this are the variables you need to add to your custom BaseCommitizen.

ParameterTypeRequiredDescription
commit_parserstrNORegex which should provide the variables explained in the changelog description
changelog_patternstrNORegex to validate the commits, this is useful to skip commits that don't meet your ruling standards like a Merge. Usually the same as bump_pattern
change_type_mapdictNOConvert the title of the change type that will appear in the changelog, if a value is not found, the original will be provided
changelog_message_builder_hookmethod: (dict, git.GitCommit) -> dictNOCustomize with extra information your message output, like adding links, this function is executed per parsed commit. Each GitCommit contains the following attrs: rev, title, body, author, author_email
changelog_hookmethod: (full_changelog: str, partial_changelog: Optional[str]) -> strNOReceives the whole and partial (if used incremental) changelog. Useful to send slack messages or notify a compliance department. Must return the full_changelog
fromcommitizen.cz.baseimportBaseCommitizenimportchatimportcomplianceclassStrangeCommitizen(BaseCommitizen):
changelog_pattern=r"^(break|new|fix|hotfix)"commit_parser=r"^(?P<change_type>feat|fix|refactor|perf|BREAKING CHANGE)(?:\((?P<scope>[^()\r\n]*)\)|\()?(?P<breaking>!)?:\s(?P<message>.*)?"change_type_map= {
"feat": "Features",
"fix": "Bug Fixes",
"refactor": "Code Refactor",
"perf": "Performance improvements",
}
defchangelog_message_builder_hook(
self, parsed_message: dict, commit: git.GitCommit
) ->dict:
rev=commit.revm=parsed_message["message"]
parsed_message[
"message"
] =f"{m}{rev} [{commit.author}]({commit.author_email})"returnparsed_messagedefchangelog_hook(
self, full_changelog: str, partial_changelog: Optional[str]
) ->str:
"""Executed at the end of the changelog generation full_changelog: it's the output about to being written into the file partial_changelog: it's the new stuff, this is useful to send slack messages or similar Return: the new updated full_changelog """ifpartial_changelog:
chat.room("#committers").notify(partial_changelog)
iffull_changelog:
compliance.send(full_changelog)
full_changelog.replace(" fix ", " **fix** ")
returnfull_changelog

Raise Customize Exception

If you want commitizen to catch your exception and print the message, you'll have to inherit CzException.

fromcommitizen.cz.exceptionimportCzExceptionclassNoSubjectProvidedException(CzException):
...

Migrating from legacy plugin format

Commitizen migrated to a new plugin format relying on importlib.metadata.EntryPoint. Migration should be straight-forward for legacy plugins:

  • Remove the discover_this line from you plugin module
  • Expose the plugin class under as a commitizen.plugin entrypoint.

The name of the plugin is now determined by the name of the entrypoint.

Example

If you were having a CzPlugin class in a cz_plugin.py module like this:

fromcommitizen.cz.baseimportBaseCommitizenclassPluginCz(BaseCommitizen):
...
discover_this=PluginCz

Then remove the discover_this line:

fromcommitizen.cz.baseimportBaseCommitizenclassPluginCz(BaseCommitizen):
...

and expose the class as entrypoint in you setuptools:

fromsetuptoolsimportsetupsetup(
name="MyPlugin",
version="0.1.0",
py_modules=["cz_plugin"],
entry_points={"commitizen.plugin": ["plugin = cz_plugin:PluginCz"]},
...,
)

Then your plugin will be available under the name plugin.

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

History
433 lines (340 loc) · 20.5 KB

File metadata and controls

433 lines (340 loc) · 20.5 KB

Customizing commitizen is not hard at all. We have two different ways to do so.

1. Customize in configuration file

The basic steps are:

  1. Define your custom committing or bumping rules in the configuration file.
  2. Declare name = "cz_customize" in your configuration file, or add -n cz_customize when running commitizen.

Example:

[tool.commitizen]
name = "cz_customize"
[tool.commitizen.customize]
message_template = "{{change_type}}:{% if show_message %} {{message}}{% endif %}"example = "feature: this feature enable customize through config file"schema = "<type>: <body>"schema_pattern = "(feature|bug fix):(\\s.*)"bump_pattern = "^(break|new|fix|hotfix)"bump_map = {"break" = "MAJOR", "new" = "MINOR", "fix" = "PATCH", "hotfix" = "PATCH"}
change_type_order = ["BREAKING CHANGE", "feat", "fix", "refactor", "perf"]
info_path = "cz_customize_info.txt"info = """This is customized info"""commit_parser = "^(?P<change_type>feature|bug fix):\\s(?P<message>.*)?"changelog_pattern = "^(feature|bug fix)?(!)?"change_type_map = {"feature" = "Feat", "bug fix" = "Fix"}
[[tool.commitizen.customize.questions]]
type = "list"name = "change_type"choices = [{value = "feature", name = "feature: A new feature."}, {value = "bug fix", name = "bug fix: A bug fix."}]
# choices = ["feature", "fix"] # short versionmessage = "Select the type of change you are committing"
[[tool.commitizen.customize.questions]]
type = "input"name = "message"message = "Body."
[[tool.commitizen.customize.questions]]
type = "confirm"name = "show_message"message = "Do you want to add body message in commit?"

The equivalent example for a json config file:

{
"commitizen": {
"name": "cz_customize",
"customize": {
"message_template": "{{change_type}}:{% if show_message %} {{message}}{% endif %}",
"example": "feature: this feature enable customize through config file",
"schema": "<type>: <body>",
"schema_pattern": "(feature|bug fix):(\\s.*)",
"bump_pattern": "^(break|new|fix|hotfix)",
"bump_map": {
"break": "MAJOR",
"new": "MINOR",
"fix": "PATCH",
"hotfix": "PATCH"
},
"change_type_order": ["BREAKING CHANGE", "feat", "fix", "refactor", "perf"],
"info_path": "cz_customize_info.txt",
"info": "This is customized info",
"commit_parser": "^(?P<change_type>feature|bug fix):\\s(?P<message>.*)?",
"changelog_pattern": "^(feature|bug fix)?(!)?",
"change_type_map": {"feature": "Feat", "bug fix": "Fix"},
"questions": [
{
"type": "list",
"name": "change_type",
"choices": [
{
"value": "feature",
"name": "feature: A new feature."
},
{
"value": "bug fix",
"name": "bug fix: A bug fix."
}
],
"message": "Select the type of change you are committing"
},
{
"type": "input",
"name": "message",
"message": "Body."
},
{
"type": "confirm",
"name": "show_message",
"message": "Do you want to add body message in commit?"
}
]
}
}
}

And the correspondent example for a yaml json file:

commitizen:
name: cz_customizecustomize:
message_template: "{{change_type}}:{% if show_message %} {{message}}{% endif %}"example: 'feature: this feature enable customize through config file'schema: "<type>: <body>"schema_pattern: "(feature|bug fix):(\\s.*)"bump_pattern: "^(break|new|fix|hotfix)"commit_parser: "^(?P<change_type>feature|bug fix):\\s(?P<message>.*)?",changelog_pattern: "^(feature|bug fix)?(!)?",change_type_map:
feature: Featbug fix: Fixbump_map:
break: MAJORnew: MINORfix: PATCHhotfix: PATCHchange_type_order: ["BREAKING CHANGE", "feat", "fix", "refactor", "perf"]info_path: cz_customize_info.txtinfo: This is customized infoquestions:
- type: listname: change_typechoices:
- value: featurename: 'feature: A new feature.'
- value: bug fixname: 'bug fix: A bug fix.'message: Select the type of change you are committing
- type: inputname: messagemessage: Body.
- type: confirmname: show_messagemessage: Do you want to add body message in commit?

Customize configuration

ParameterTypeDefaultDescription
questionsQuestionsNoneQuestions regarding the commit message. Detailed below. The type Questions is an alias to Iterable[MutableMapping[str, Any]] which is defined in commitizen.defaults. It expects a list of dictionaries.
message_templatestrNoneThe template for generating message from the given answers. message_template should either follow Jinja2 formatting specification, and all the variables in this template should be defined in name in questions
examplestrNone(OPTIONAL) Provide an example to help understand the style. Used by cz example.
schemastrNone(OPTIONAL) Show the schema used. Used by cz schema.
schema_patternstrNone(OPTIONAL) The regular expression used to do commit message validation. Used by cz check.
info_pathstrNone(OPTIONAL) The path to the file that contains explanation of the commit rules. Used by cz info. If not provided cz info, will load info instead.
infostrNone(OPTIONAL) Explanation of the commit rules. Used by cz info.
bump_mapdictNone(OPTIONAL) Dictionary mapping the extracted information to a SemVer increment type (MAJOR, MINOR, PATCH)
bump_patternstrNone(OPTIONAL) Regex to extract information from commit (subject and body)
change_type_orderstrNone(OPTIONAL) List of strings used to order the Changelog. All other types will be sorted alphabetically. Default is ["BREAKING CHANGE", "Feat", "Fix", "Refactor", "Perf"]
commit_parserstrNone(OPTIONAL) Regex to extract information used in creating changelog. See more
changelog_patternstrNone(OPTIONAL) Regex to understand which commits to include in the changelog
change_type_mapdictNone(OPTIONAL) Dictionary mapping the type of the commit to a changelog entry

Detailed questions content

ParameterTypeDefaultDescription
typestrNoneThe type of questions. Valid type: list, input and etc. [See More][different-question-types]
namestrNoneThe key for the value answered by user. It's used in message_template
messagestrNoneDetail description for the question.
choiceslistNone(OPTIONAL) The choices when type = list. Either use a list of values or a list of dictionaries with name and value keys. Keyboard shortcuts can be defined via key. See examples above.
defaultAnyNone(OPTIONAL) The default value for this question.
filterstrNone(Optional) Validator for user's answer. (Work in Progress)
[different-question-types]: https://github.com/tmbo/questionary#different-question-types

Shortcut keys

When the use_shortcuts config option is enabled, commitizen can show and use keyboard shortcuts to select items from lists directly. For example, when using the cz_conventional_commits commitizen template, shortcut keys are shown when selecting the commit type. Unless otherwise defined, keyboard shortcuts will be numbered automatically. To specify keyboard shortcuts for your custom choices, provide the shortcut using the key parameter in dictionary form for each choice you would like to customize.

2. Customize through customizing a class

The basic steps are:

  1. Inheriting from BaseCommitizen
  2. Give a name to your rules.
  3. Create a python package using setup.py, poetry, etc
  4. Expose the class as a commitizen.plugin entrypoint

Check an example on how to configure BaseCommitizen.

You can also automate the steps above through cookiecutter.

cookiecutter gh:commitizen-tools/commitizen_cz_template

See commitizen_cz_template for details.

Once you publish your rules, you can send us a PR to the Third-party section.

Custom commit rules

Create a Python module, for example cz_jira.py.

Inherit from BaseCommitizen, and you must define questions and message. The others are optional.

fromcommitizen.cz.baseimportBaseCommitizenfromcommitizen.defaultsimportQuestionsclassJiraCz(BaseCommitizen):
# Questions = Iterable[MutableMapping[str, Any]]# It expects a list with dictionaries.defquestions(self) ->Questions:
"""Questions regarding the commit message."""questions= [
{"type": "input", "name": "title", "message": "Commit title"},
{"type": "input", "name": "issue", "message": "Jira Issue number:"},
]
returnquestionsdefmessage(self, answers: dict) ->str:
"""Generate the message with the given answers."""return"{0} (#{1})".format(answers["title"], answers["issue"])
defexample(self) ->str:
"""Provide an example to help understand the style (OPTIONAL) Used by `cz example`. """return"Problem with user (#321)"defschema(self) ->str:
"""Show the schema used (OPTIONAL) Used by `cz schema`. """return"<title> (<issue>)"definfo(self) ->str:
"""Explanation of the commit rules. (OPTIONAL) Used by `cz info`. """return"We use this because is useful"

The next file required is setup.py modified from flask version.

fromsetuptoolsimportsetupsetup(
name="JiraCommitizen",
version="0.1.0",
py_modules=["cz_jira"],
license="MIT",
long_description="this is a long description",
install_requires=["commitizen"],
entry_points={"commitizen.plugin": ["cz_jira = cz_jira:JiraCz"]},
)

So in the end, we would have

.
├── cz_jira.py
└── setup.py

And that's it. You can install it without uploading to pypi by simply doing pip install .

If you feel like it should be part of this repo, create a PR.

Custom bump rules

You need to define 2 parameters inside your custom BaseCommitizen.

ParameterTypeDefaultDescription
bump_patternstrNoneRegex to extract information from commit (subject and body)
bump_mapdictNoneDictionary mapping the extracted information to a SemVer increment type (MAJOR, MINOR, PATCH)

Let's see an example.

fromcommitizen.cz.baseimportBaseCommitizenclassStrangeCommitizen(BaseCommitizen):
bump_pattern=r"^(break|new|fix|hotfix)"bump_map= {"break": "MAJOR", "new": "MINOR", "fix": "PATCH", "hotfix": "PATCH"}

That's it, your commitizen now supports custom rules, and you can run.

cz -n cz_strange bump

Custom changelog generator

The changelog generator should just work in a very basic manner without touching anything. You can customize it of course, and this are the variables you need to add to your custom BaseCommitizen.

ParameterTypeRequiredDescription
commit_parserstrNORegex which should provide the variables explained in the changelog description
changelog_patternstrNORegex to validate the commits, this is useful to skip commits that don't meet your ruling standards like a Merge. Usually the same as bump_pattern
change_type_mapdictNOConvert the title of the change type that will appear in the changelog, if a value is not found, the original will be provided
changelog_message_builder_hookmethod: (dict, git.GitCommit) -> dictNOCustomize with extra information your message output, like adding links, this function is executed per parsed commit. Each GitCommit contains the following attrs: rev, title, body, author, author_email
changelog_hookmethod: (full_changelog: str, partial_changelog: Optional[str]) -> strNOReceives the whole and partial (if used incremental) changelog. Useful to send slack messages or notify a compliance department. Must return the full_changelog
fromcommitizen.cz.baseimportBaseCommitizenimportchatimportcomplianceclassStrangeCommitizen(BaseCommitizen):
changelog_pattern=r"^(break|new|fix|hotfix)"commit_parser=r"^(?P<change_type>feat|fix|refactor|perf|BREAKING CHANGE)(?:\((?P<scope>[^()\r\n]*)\)|\()?(?P<breaking>!)?:\s(?P<message>.*)?"change_type_map= {
"feat": "Features",
"fix": "Bug Fixes",
"refactor": "Code Refactor",
"perf": "Performance improvements",
}
defchangelog_message_builder_hook(
self, parsed_message: dict, commit: git.GitCommit
) ->dict:
rev=commit.revm=parsed_message["message"]
parsed_message[
"message"
] =f"{m}{rev} [{commit.author}]({commit.author_email})"returnparsed_messagedefchangelog_hook(
self, full_changelog: str, partial_changelog: Optional[str]
) ->str:
"""Executed at the end of the changelog generation full_changelog: it's the output about to being written into the file partial_changelog: it's the new stuff, this is useful to send slack messages or similar Return: the new updated full_changelog """ifpartial_changelog:
chat.room("#committers").notify(partial_changelog)
iffull_changelog:
compliance.send(full_changelog)
full_changelog.replace(" fix ", " **fix** ")
returnfull_changelog

Raise Customize Exception

If you want commitizen to catch your exception and print the message, you'll have to inherit CzException.

fromcommitizen.cz.exceptionimportCzExceptionclassNoSubjectProvidedException(CzException):
...

Migrating from legacy plugin format

Commitizen migrated to a new plugin format relying on importlib.metadata.EntryPoint. Migration should be straight-forward for legacy plugins:

  • Remove the discover_this line from you plugin module
  • Expose the plugin class under as a commitizen.plugin entrypoint.

The name of the plugin is now determined by the name of the entrypoint.

Example

If you were having a CzPlugin class in a cz_plugin.py module like this:

fromcommitizen.cz.baseimportBaseCommitizenclassPluginCz(BaseCommitizen):
...
discover_this=PluginCz

Then remove the discover_this line:

fromcommitizen.cz.baseimportBaseCommitizenclassPluginCz(BaseCommitizen):
...

and expose the class as entrypoint in you setuptools:

fromsetuptoolsimportsetupsetup(
name="MyPlugin",
version="0.1.0",
py_modules=["cz_plugin"],
entry_points={"commitizen.plugin": ["plugin = cz_plugin:PluginCz"]},
...,
)

Then your plugin will be available under the name plugin.

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

History
433 lines (340 loc) · 20.5 KB

File metadata and controls

433 lines (340 loc) · 20.5 KB

Customizing commitizen is not hard at all. We have two different ways to do so.

1. Customize in configuration file

The basic steps are:

  1. Define your custom committing or bumping rules in the configuration file.
  2. Declare name = "cz_customize" in your configuration file, or add -n cz_customize when running commitizen.

Example:

[tool.commitizen]
name = "cz_customize"
[tool.commitizen.customize]
message_template = "{{change_type}}:{% if show_message %} {{message}}{% endif %}"example = "feature: this feature enable customize through config file"schema = "<type>: <body>"schema_pattern = "(feature|bug fix):(\\s.*)"bump_pattern = "^(break|new|fix|hotfix)"bump_map = {"break" = "MAJOR", "new" = "MINOR", "fix" = "PATCH", "hotfix" = "PATCH"}
change_type_order = ["BREAKING CHANGE", "feat", "fix", "refactor", "perf"]
info_path = "cz_customize_info.txt"info = """This is customized info"""commit_parser = "^(?P<change_type>feature|bug fix):\\s(?P<message>.*)?"changelog_pattern = "^(feature|bug fix)?(!)?"change_type_map = {"feature" = "Feat", "bug fix" = "Fix"}
[[tool.commitizen.customize.questions]]
type = "list"name = "change_type"choices = [{value = "feature", name = "feature: A new feature."}, {value = "bug fix", name = "bug fix: A bug fix."}]
# choices = ["feature", "fix"] # short versionmessage = "Select the type of change you are committing"
[[tool.commitizen.customize.questions]]
type = "input"name = "message"message = "Body."
[[tool.commitizen.customize.questions]]
type = "confirm"name = "show_message"message = "Do you want to add body message in commit?"

The equivalent example for a json config file:

{
"commitizen": {
"name": "cz_customize",
"customize": {
"message_template": "{{change_type}}:{% if show_message %} {{message}}{% endif %}",
"example": "feature: this feature enable customize through config file",
"schema": "<type>: <body>",
"schema_pattern": "(feature|bug fix):(\\s.*)",
"bump_pattern": "^(break|new|fix|hotfix)",
"bump_map": {
"break": "MAJOR",
"new": "MINOR",
"fix": "PATCH",
"hotfix": "PATCH"
},
"change_type_order": ["BREAKING CHANGE", "feat", "fix", "refactor", "perf"],
"info_path": "cz_customize_info.txt",
"info": "This is customized info",
"commit_parser": "^(?P<change_type>feature|bug fix):\\s(?P<message>.*)?",
"changelog_pattern": "^(feature|bug fix)?(!)?",
"change_type_map": {"feature": "Feat", "bug fix": "Fix"},
"questions": [
{
"type": "list",
"name": "change_type",
"choices": [
{
"value": "feature",
"name": "feature: A new feature."
},
{
"value": "bug fix",
"name": "bug fix: A bug fix."
}
],
"message": "Select the type of change you are committing"
},
{
"type": "input",
"name": "message",
"message": "Body."
},
{
"type": "confirm",
"name": "show_message",
"message": "Do you want to add body message in commit?"
}
]
}
}
}

And the correspondent example for a yaml json file:

commitizen:
name: cz_customizecustomize:
message_template: "{{change_type}}:{% if show_message %} {{message}}{% endif %}"example: 'feature: this feature enable customize through config file'schema: "<type>: <body>"schema_pattern: "(feature|bug fix):(\\s.*)"bump_pattern: "^(break|new|fix|hotfix)"commit_parser: "^(?P<change_type>feature|bug fix):\\s(?P<message>.*)?",changelog_pattern: "^(feature|bug fix)?(!)?",change_type_map:
feature: Featbug fix: Fixbump_map:
break: MAJORnew: MINORfix: PATCHhotfix: PATCHchange_type_order: ["BREAKING CHANGE", "feat", "fix", "refactor", "perf"]info_path: cz_customize_info.txtinfo: This is customized infoquestions:
- type: listname: change_typechoices:
- value: featurename: 'feature: A new feature.'
- value: bug fixname: 'bug fix: A bug fix.'message: Select the type of change you are committing
- type: inputname: messagemessage: Body.
- type: confirmname: show_messagemessage: Do you want to add body message in commit?

Customize configuration

ParameterTypeDefaultDescription
questionsQuestionsNoneQuestions regarding the commit message. Detailed below. The type Questions is an alias to Iterable[MutableMapping[str, Any]] which is defined in commitizen.defaults. It expects a list of dictionaries.
message_templatestrNoneThe template for generating message from the given answers. message_template should either follow Jinja2 formatting specification, and all the variables in this template should be defined in name in questions
examplestrNone(OPTIONAL) Provide an example to help understand the style. Used by cz example.
schemastrNone(OPTIONAL) Show the schema used. Used by cz schema.
schema_patternstrNone(OPTIONAL) The regular expression used to do commit message validation. Used by cz check.
info_pathstrNone(OPTIONAL) The path to the file that contains explanation of the commit rules. Used by cz info. If not provided cz info, will load info instead.
infostrNone(OPTIONAL) Explanation of the commit rules. Used by cz info.
bump_mapdictNone(OPTIONAL) Dictionary mapping the extracted information to a SemVer increment type (MAJOR, MINOR, PATCH)
bump_patternstrNone(OPTIONAL) Regex to extract information from commit (subject and body)
change_type_orderstrNone(OPTIONAL) List of strings used to order the Changelog. All other types will be sorted alphabetically. Default is ["BREAKING CHANGE", "Feat", "Fix", "Refactor", "Perf"]
commit_parserstrNone(OPTIONAL) Regex to extract information used in creating changelog. See more
changelog_patternstrNone(OPTIONAL) Regex to understand which commits to include in the changelog
change_type_mapdictNone(OPTIONAL) Dictionary mapping the type of the commit to a changelog entry

Detailed questions content

ParameterTypeDefaultDescription
typestrNoneThe type of questions. Valid type: list, input and etc. [See More][different-question-types]
namestrNoneThe key for the value answered by user. It's used in message_template
messagestrNoneDetail description for the question.
choiceslistNone(OPTIONAL) The choices when type = list. Either use a list of values or a list of dictionaries with name and value keys. Keyboard shortcuts can be defined via key. See examples above.
defaultAnyNone(OPTIONAL) The default value for this question.
filterstrNone(Optional) Validator for user's answer. (Work in Progress)
[different-question-types]: https://github.com/tmbo/questionary#different-question-types

Shortcut keys

When the use_shortcuts config option is enabled, commitizen can show and use keyboard shortcuts to select items from lists directly. For example, when using the cz_conventional_commits commitizen template, shortcut keys are shown when selecting the commit type. Unless otherwise defined, keyboard shortcuts will be numbered automatically. To specify keyboard shortcuts for your custom choices, provide the shortcut using the key parameter in dictionary form for each choice you would like to customize.

2. Customize through customizing a class

The basic steps are:

  1. Inheriting from BaseCommitizen
  2. Give a name to your rules.
  3. Create a python package using setup.py, poetry, etc
  4. Expose the class as a commitizen.plugin entrypoint

Check an example on how to configure BaseCommitizen.

You can also automate the steps above through cookiecutter.

cookiecutter gh:commitizen-tools/commitizen_cz_template

See commitizen_cz_template for details.

Once you publish your rules, you can send us a PR to the Third-party section.

Custom commit rules

Create a Python module, for example cz_jira.py.

Inherit from BaseCommitizen, and you must define questions and message. The others are optional.

fromcommitizen.cz.baseimportBaseCommitizenfromcommitizen.defaultsimportQuestionsclassJiraCz(BaseCommitizen):
# Questions = Iterable[MutableMapping[str, Any]]# It expects a list with dictionaries.defquestions(self) ->Questions:
"""Questions regarding the commit message."""questions= [
{"type": "input", "name": "title", "message": "Commit title"},
{"type": "input", "name": "issue", "message": "Jira Issue number:"},
]
returnquestionsdefmessage(self, answers: dict) ->str:
"""Generate the message with the given answers."""return"{0} (#{1})".format(answers["title"], answers["issue"])
defexample(self) ->str:
"""Provide an example to help understand the style (OPTIONAL) Used by `cz example`. """return"Problem with user (#321)"defschema(self) ->str:
"""Show the schema used (OPTIONAL) Used by `cz schema`. """return"<title> (<issue>)"definfo(self) ->str:
"""Explanation of the commit rules. (OPTIONAL) Used by `cz info`. """return"We use this because is useful"

The next file required is setup.py modified from flask version.

fromsetuptoolsimportsetupsetup(
name="JiraCommitizen",
version="0.1.0",
py_modules=["cz_jira"],
license="MIT",
long_description="this is a long description",
install_requires=["commitizen"],
entry_points={"commitizen.plugin": ["cz_jira = cz_jira:JiraCz"]},
)

So in the end, we would have

.
├── cz_jira.py
└── setup.py

And that's it. You can install it without uploading to pypi by simply doing pip install .

If you feel like it should be part of this repo, create a PR.

Custom bump rules

You need to define 2 parameters inside your custom BaseCommitizen.

ParameterTypeDefaultDescription
bump_patternstrNoneRegex to extract information from commit (subject and body)
bump_mapdictNoneDictionary mapping the extracted information to a SemVer increment type (MAJOR, MINOR, PATCH)

Let's see an example.

fromcommitizen.cz.baseimportBaseCommitizenclassStrangeCommitizen(BaseCommitizen):
bump_pattern=r"^(break|new|fix|hotfix)"bump_map= {"break": "MAJOR", "new": "MINOR", "fix": "PATCH", "hotfix": "PATCH"}

That's it, your commitizen now supports custom rules, and you can run.

cz -n cz_strange bump

Custom changelog generator

The changelog generator should just work in a very basic manner without touching anything. You can customize it of course, and this are the variables you need to add to your custom BaseCommitizen.

ParameterTypeRequiredDescription
commit_parserstrNORegex which should provide the variables explained in the changelog description
changelog_patternstrNORegex to validate the commits, this is useful to skip commits that don't meet your ruling standards like a Merge. Usually the same as bump_pattern
change_type_mapdictNOConvert the title of the change type that will appear in the changelog, if a value is not found, the original will be provided
changelog_message_builder_hookmethod: (dict, git.GitCommit) -> dictNOCustomize with extra information your message output, like adding links, this function is executed per parsed commit. Each GitCommit contains the following attrs: rev, title, body, author, author_email
changelog_hookmethod: (full_changelog: str, partial_changelog: Optional[str]) -> strNOReceives the whole and partial (if used incremental) changelog. Useful to send slack messages or notify a compliance department. Must return the full_changelog
fromcommitizen.cz.baseimportBaseCommitizenimportchatimportcomplianceclassStrangeCommitizen(BaseCommitizen):
changelog_pattern=r"^(break|new|fix|hotfix)"commit_parser=r"^(?P<change_type>feat|fix|refactor|perf|BREAKING CHANGE)(?:\((?P<scope>[^()\r\n]*)\)|\()?(?P<breaking>!)?:\s(?P<message>.*)?"change_type_map= {
"feat": "Features",
"fix": "Bug Fixes",
"refactor": "Code Refactor",
"perf": "Performance improvements",
}
defchangelog_message_builder_hook(
self, parsed_message: dict, commit: git.GitCommit
) ->dict:
rev=commit.revm=parsed_message["message"]
parsed_message[
"message"
] =f"{m}{rev} [{commit.author}]({commit.author_email})"returnparsed_messagedefchangelog_hook(
self, full_changelog: str, partial_changelog: Optional[str]
) ->str:
"""Executed at the end of the changelog generation full_changelog: it's the output about to being written into the file partial_changelog: it's the new stuff, this is useful to send slack messages or similar Return: the new updated full_changelog """ifpartial_changelog:
chat.room("#committers").notify(partial_changelog)
iffull_changelog:
compliance.send(full_changelog)
full_changelog.replace(" fix ", " **fix** ")
returnfull_changelog

Raise Customize Exception

If you want commitizen to catch your exception and print the message, you'll have to inherit CzException.

fromcommitizen.cz.exceptionimportCzExceptionclassNoSubjectProvidedException(CzException):
...

Migrating from legacy plugin format

Commitizen migrated to a new plugin format relying on importlib.metadata.EntryPoint. Migration should be straight-forward for legacy plugins:

  • Remove the discover_this line from you plugin module
  • Expose the plugin class under as a commitizen.plugin entrypoint.

The name of the plugin is now determined by the name of the entrypoint.

Example

If you were having a CzPlugin class in a cz_plugin.py module like this:

fromcommitizen.cz.baseimportBaseCommitizenclassPluginCz(BaseCommitizen):
...
discover_this=PluginCz

Then remove the discover_this line:

fromcommitizen.cz.baseimportBaseCommitizenclassPluginCz(BaseCommitizen):
...

and expose the class as entrypoint in you setuptools:

fromsetuptoolsimportsetupsetup(
name="MyPlugin",
version="0.1.0",
py_modules=["cz_plugin"],
entry_points={"commitizen.plugin": ["plugin = cz_plugin:PluginCz"]},
...,
)

Then your plugin will be available under the name plugin.

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Latest commit

History

History
433 lines (340 loc) · 20.5 KB

File metadata and controls

433 lines (340 loc) · 20.5 KB

Customizing commitizen is not hard at all. We have two different ways to do so.

1. Customize in configuration file

The basic steps are:

  1. Define your custom committing or bumping rules in the configuration file.
  2. Declare name = "cz_customize" in your configuration file, or add -n cz_customize when running commitizen.

Example:

[tool.commitizen]
name = "cz_customize"
[tool.commitizen.customize]
message_template = "{{change_type}}:{% if show_message %} {{message}}{% endif %}"example = "feature: this feature enable customize through config file"schema = "<type>: <body>"schema_pattern = "(feature|bug fix):(\\s.*)"bump_pattern = "^(break|new|fix|hotfix)"bump_map = {"break" = "MAJOR", "new" = "MINOR", "fix" = "PATCH", "hotfix" = "PATCH"}
change_type_order = ["BREAKING CHANGE", "feat", "fix", "refactor", "perf"]
info_path = "cz_customize_info.txt"info = """This is customized info"""commit_parser = "^(?P<change_type>feature|bug fix):\\s(?P<message>.*)?"changelog_pattern = "^(feature|bug fix)?(!)?"change_type_map = {"feature" = "Feat", "bug fix" = "Fix"}
[[tool.commitizen.customize.questions]]
type = "list"name = "change_type"choices = [{value = "feature", name = "feature: A new feature."}, {value = "bug fix", name = "bug fix: A bug fix."}]
# choices = ["feature", "fix"] # short versionmessage = "Select the type of change you are committing"
[[tool.commitizen.customize.questions]]
type = "input"name = "message"message = "Body."
[[tool.commitizen.customize.questions]]
type = "confirm"name = "show_message"message = "Do you want to add body message in commit?"

The equivalent example for a json config file:

{
"commitizen": {
"name": "cz_customize",
"customize": {
"message_template": "{{change_type}}:{% if show_message %} {{message}}{% endif %}",
"example": "feature: this feature enable customize through config file",
"schema": "<type>: <body>",
"schema_pattern": "(feature|bug fix):(\\s.*)",
"bump_pattern": "^(break|new|fix|hotfix)",
"bump_map": {
"break": "MAJOR",
"new": "MINOR",
"fix": "PATCH",
"hotfix": "PATCH"
},
"change_type_order": ["BREAKING CHANGE", "feat", "fix", "refactor", "perf"],
"info_path": "cz_customize_info.txt",
"info": "This is customized info",
"commit_parser": "^(?P<change_type>feature|bug fix):\\s(?P<message>.*)?",
"changelog_pattern": "^(feature|bug fix)?(!)?",
"change_type_map": {"feature": "Feat", "bug fix": "Fix"},
"questions": [
{
"type": "list",
"name": "change_type",
"choices": [
{
"value": "feature",
"name": "feature: A new feature."
},
{
"value": "bug fix",
"name": "bug fix: A bug fix."
}
],
"message": "Select the type of change you are committing"
},
{
"type": "input",
"name": "message",
"message": "Body."
},
{
"type": "confirm",
"name": "show_message",
"message": "Do you want to add body message in commit?"
}
]
}
}
}

And the correspondent example for a yaml json file:

commitizen:
name: cz_customizecustomize:
message_template: "{{change_type}}:{% if show_message %} {{message}}{% endif %}"example: 'feature: this feature enable customize through config file'schema: "<type>: <body>"schema_pattern: "(feature|bug fix):(\\s.*)"bump_pattern: "^(break|new|fix|hotfix)"commit_parser: "^(?P<change_type>feature|bug fix):\\s(?P<message>.*)?",changelog_pattern: "^(feature|bug fix)?(!)?",change_type_map:
feature: Featbug fix: Fixbump_map:
break: MAJORnew: MINORfix: PATCHhotfix: PATCHchange_type_order: ["BREAKING CHANGE", "feat", "fix", "refactor", "perf"]info_path: cz_customize_info.txtinfo: This is customized infoquestions:
- type: listname: change_typechoices:
- value: featurename: 'feature: A new feature.'
- value: bug fixname: 'bug fix: A bug fix.'message: Select the type of change you are committing
- type: inputname: messagemessage: Body.
- type: confirmname: show_messagemessage: Do you want to add body message in commit?

Customize configuration

ParameterTypeDefaultDescription
questionsQuestionsNoneQuestions regarding the commit message. Detailed below. The type Questions is an alias to Iterable[MutableMapping[str, Any]] which is defined in commitizen.defaults. It expects a list of dictionaries.
message_templatestrNoneThe template for generating message from the given answers. message_template should either follow Jinja2 formatting specification, and all the variables in this template should be defined in name in questions
examplestrNone(OPTIONAL) Provide an example to help understand the style. Used by cz example.
schemastrNone(OPTIONAL) Show the schema used. Used by cz schema.
schema_patternstrNone(OPTIONAL) The regular expression used to do commit message validation. Used by cz check.
info_pathstrNone(OPTIONAL) The path to the file that contains explanation of the commit rules. Used by cz info. If not provided cz info, will load info instead.
infostrNone(OPTIONAL) Explanation of the commit rules. Used by cz info.
bump_mapdictNone(OPTIONAL) Dictionary mapping the extracted information to a SemVer increment type (MAJOR, MINOR, PATCH)
bump_patternstrNone(OPTIONAL) Regex to extract information from commit (subject and body)
change_type_orderstrNone(OPTIONAL) List of strings used to order the Changelog. All other types will be sorted alphabetically. Default is ["BREAKING CHANGE", "Feat", "Fix", "Refactor", "Perf"]
commit_parserstrNone(OPTIONAL) Regex to extract information used in creating changelog. See more
changelog_patternstrNone(OPTIONAL) Regex to understand which commits to include in the changelog
change_type_mapdictNone(OPTIONAL) Dictionary mapping the type of the commit to a changelog entry

Detailed questions content

ParameterTypeDefaultDescription
typestrNoneThe type of questions. Valid type: list, input and etc. [See More][different-question-types]
namestrNoneThe key for the value answered by user. It's used in message_template
messagestrNoneDetail description for the question.
choiceslistNone(OPTIONAL) The choices when type = list. Either use a list of values or a list of dictionaries with name and value keys. Keyboard shortcuts can be defined via key. See examples above.
defaultAnyNone(OPTIONAL) The default value for this question.
filterstrNone(Optional) Validator for user's answer. (Work in Progress)
[different-question-types]: https://github.com/tmbo/questionary#different-question-types

Shortcut keys

When the use_shortcuts config option is enabled, commitizen can show and use keyboard shortcuts to select items from lists directly. For example, when using the cz_conventional_commits commitizen template, shortcut keys are shown when selecting the commit type. Unless otherwise defined, keyboard shortcuts will be numbered automatically. To specify keyboard shortcuts for your custom choices, provide the shortcut using the key parameter in dictionary form for each choice you would like to customize.

2. Customize through customizing a class

The basic steps are:

  1. Inheriting from BaseCommitizen
  2. Give a name to your rules.
  3. Create a python package using setup.py, poetry, etc
  4. Expose the class as a commitizen.plugin entrypoint

Check an example on how to configure BaseCommitizen.

You can also automate the steps above through cookiecutter.

cookiecutter gh:commitizen-tools/commitizen_cz_template

See commitizen_cz_template for details.

Once you publish your rules, you can send us a PR to the Third-party section.

Custom commit rules

Create a Python module, for example cz_jira.py.

Inherit from BaseCommitizen, and you must define questions and message. The others are optional.

fromcommitizen.cz.baseimportBaseCommitizenfromcommitizen.defaultsimportQuestionsclassJiraCz(BaseCommitizen):
# Questions = Iterable[MutableMapping[str, Any]]# It expects a list with dictionaries.defquestions(self) ->Questions:
"""Questions regarding the commit message."""questions= [
{"type": "input", "name": "title", "message": "Commit title"},
{"type": "input", "name": "issue", "message": "Jira Issue number:"},
]
returnquestionsdefmessage(self, answers: dict) ->str:
"""Generate the message with the given answers."""return"{0} (#{1})".format(answers["title"], answers["issue"])
defexample(self) ->str:
"""Provide an example to help understand the style (OPTIONAL) Used by `cz example`. """return"Problem with user (#321)"defschema(self) ->str:
"""Show the schema used (OPTIONAL) Used by `cz schema`. """return"<title> (<issue>)"definfo(self) ->str:
"""Explanation of the commit rules. (OPTIONAL) Used by `cz info`. """return"We use this because is useful"

The next file required is setup.py modified from flask version.

fromsetuptoolsimportsetupsetup(
name="JiraCommitizen",
version="0.1.0",
py_modules=["cz_jira"],
license="MIT",
long_description="this is a long description",
install_requires=["commitizen"],
entry_points={"commitizen.plugin": ["cz_jira = cz_jira:JiraCz"]},
)

So in the end, we would have

.
├── cz_jira.py
└── setup.py

And that's it. You can install it without uploading to pypi by simply doing pip install .

If you feel like it should be part of this repo, create a PR.

Custom bump rules

You need to define 2 parameters inside your custom BaseCommitizen.

ParameterTypeDefaultDescription
bump_patternstrNoneRegex to extract information from commit (subject and body)
bump_mapdictNoneDictionary mapping the extracted information to a SemVer increment type (MAJOR, MINOR, PATCH)

Let's see an example.

fromcommitizen.cz.baseimportBaseCommitizenclassStrangeCommitizen(BaseCommitizen):
bump_pattern=r"^(break|new|fix|hotfix)"bump_map= {"break": "MAJOR", "new": "MINOR", "fix": "PATCH", "hotfix": "PATCH"}

That's it, your commitizen now supports custom rules, and you can run.

cz -n cz_strange bump

Custom changelog generator

The changelog generator should just work in a very basic manner without touching anything. You can customize it of course, and this are the variables you need to add to your custom BaseCommitizen.

ParameterTypeRequiredDescription
commit_parserstrNORegex which should provide the variables explained in the changelog description
changelog_patternstrNORegex to validate the commits, this is useful to skip commits that don't meet your ruling standards like a Merge. Usually the same as bump_pattern
change_type_mapdictNOConvert the title of the change type that will appear in the changelog, if a value is not found, the original will be provided
changelog_message_builder_hookmethod: (dict, git.GitCommit) -> dictNOCustomize with extra information your message output, like adding links, this function is executed per parsed commit. Each GitCommit contains the following attrs: rev, title, body, author, author_email
changelog_hookmethod: (full_changelog: str, partial_changelog: Optional[str]) -> strNOReceives the whole and partial (if used incremental) changelog. Useful to send slack messages or notify a compliance department. Must return the full_changelog
fromcommitizen.cz.baseimportBaseCommitizenimportchatimportcomplianceclassStrangeCommitizen(BaseCommitizen):
changelog_pattern=r"^(break|new|fix|hotfix)"commit_parser=r"^(?P<change_type>feat|fix|refactor|perf|BREAKING CHANGE)(?:\((?P<scope>[^()\r\n]*)\)|\()?(?P<breaking>!)?:\s(?P<message>.*)?"change_type_map= {
"feat": "Features",
"fix": "Bug Fixes",
"refactor": "Code Refactor",
"perf": "Performance improvements",
}
defchangelog_message_builder_hook(
self, parsed_message: dict, commit: git.GitCommit
) ->dict:
rev=commit.revm=parsed_message["message"]
parsed_message[
"message"
] =f"{m}{rev} [{commit.author}]({commit.author_email})"returnparsed_messagedefchangelog_hook(
self, full_changelog: str, partial_changelog: Optional[str]
) ->str:
"""Executed at the end of the changelog generation full_changelog: it's the output about to being written into the file partial_changelog: it's the new stuff, this is useful to send slack messages or similar Return: the new updated full_changelog """ifpartial_changelog:
chat.room("#committers").notify(partial_changelog)
iffull_changelog:
compliance.send(full_changelog)
full_changelog.replace(" fix ", " **fix** ")
returnfull_changelog

Raise Customize Exception

If you want commitizen to catch your exception and print the message, you'll have to inherit CzException.

fromcommitizen.cz.exceptionimportCzExceptionclassNoSubjectProvidedException(CzException):
...

Migrating from legacy plugin format

Commitizen migrated to a new plugin format relying on importlib.metadata.EntryPoint. Migration should be straight-forward for legacy plugins:

  • Remove the discover_this line from you plugin module
  • Expose the plugin class under as a commitizen.plugin entrypoint.

The name of the plugin is now determined by the name of the entrypoint.

Example

If you were having a CzPlugin class in a cz_plugin.py module like this:

fromcommitizen.cz.baseimportBaseCommitizenclassPluginCz(BaseCommitizen):
...
discover_this=PluginCz

Then remove the discover_this line:

fromcommitizen.cz.baseimportBaseCommitizenclassPluginCz(BaseCommitizen):
...

and expose the class as entrypoint in you setuptools:

fromsetuptoolsimportsetupsetup(
name="MyPlugin",
version="0.1.0",
py_modules=["cz_plugin"],
entry_points={"commitizen.plugin": ["plugin = cz_plugin:PluginCz"]},
...,
)

Then your plugin will be available under the name plugin.

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

History
433 lines (340 loc) · 20.5 KB

File metadata and controls

433 lines (340 loc) · 20.5 KB

Customizing commitizen is not hard at all. We have two different ways to do so.

1. Customize in configuration file

The basic steps are:

  1. Define your custom committing or bumping rules in the configuration file.
  2. Declare name = "cz_customize" in your configuration file, or add -n cz_customize when running commitizen.

Example:

[tool.commitizen]
name = "cz_customize"
[tool.commitizen.customize]
message_template = "{{change_type}}:{% if show_message %} {{message}}{% endif %}"example = "feature: this feature enable customize through config file"schema = "<type>: <body>"schema_pattern = "(feature|bug fix):(\\s.*)"bump_pattern = "^(break|new|fix|hotfix)"bump_map = {"break" = "MAJOR", "new" = "MINOR", "fix" = "PATCH", "hotfix" = "PATCH"}
change_type_order = ["BREAKING CHANGE", "feat", "fix", "refactor", "perf"]
info_path = "cz_customize_info.txt"info = """This is customized info"""commit_parser = "^(?P<change_type>feature|bug fix):\\s(?P<message>.*)?"changelog_pattern = "^(feature|bug fix)?(!)?"change_type_map = {"feature" = "Feat", "bug fix" = "Fix"}
[[tool.commitizen.customize.questions]]
type = "list"name = "change_type"choices = [{value = "feature", name = "feature: A new feature."}, {value = "bug fix", name = "bug fix: A bug fix."}]
# choices = ["feature", "fix"] # short versionmessage = "Select the type of change you are committing"
[[tool.commitizen.customize.questions]]
type = "input"name = "message"message = "Body."
[[tool.commitizen.customize.questions]]
type = "confirm"name = "show_message"message = "Do you want to add body message in commit?"

The equivalent example for a json config file:

{
"commitizen": {
"name": "cz_customize",
"customize": {
"message_template": "{{change_type}}:{% if show_message %} {{message}}{% endif %}",
"example": "feature: this feature enable customize through config file",
"schema": "<type>: <body>",
"schema_pattern": "(feature|bug fix):(\\s.*)",
"bump_pattern": "^(break|new|fix|hotfix)",
"bump_map": {
"break": "MAJOR",
"new": "MINOR",
"fix": "PATCH",
"hotfix": "PATCH"
},
"change_type_order": ["BREAKING CHANGE", "feat", "fix", "refactor", "perf"],
"info_path": "cz_customize_info.txt",
"info": "This is customized info",
"commit_parser": "^(?P<change_type>feature|bug fix):\\s(?P<message>.*)?",
"changelog_pattern": "^(feature|bug fix)?(!)?",
"change_type_map": {"feature": "Feat", "bug fix": "Fix"},
"questions": [
{
"type": "list",
"name": "change_type",
"choices": [
{
"value": "feature",
"name": "feature: A new feature."
},
{
"value": "bug fix",
"name": "bug fix: A bug fix."
}
],
"message": "Select the type of change you are committing"
},
{
"type": "input",
"name": "message",
"message": "Body."
},
{
"type": "confirm",
"name": "show_message",
"message": "Do you want to add body message in commit?"
}
]
}
}
}

And the correspondent example for a yaml json file:

commitizen:
name: cz_customizecustomize:
message_template: "{{change_type}}:{% if show_message %} {{message}}{% endif %}"example: 'feature: this feature enable customize through config file'schema: "<type>: <body>"schema_pattern: "(feature|bug fix):(\\s.*)"bump_pattern: "^(break|new|fix|hotfix)"commit_parser: "^(?P<change_type>feature|bug fix):\\s(?P<message>.*)?",changelog_pattern: "^(feature|bug fix)?(!)?",change_type_map:
feature: Featbug fix: Fixbump_map:
break: MAJORnew: MINORfix: PATCHhotfix: PATCHchange_type_order: ["BREAKING CHANGE", "feat", "fix", "refactor", "perf"]info_path: cz_customize_info.txtinfo: This is customized infoquestions:
- type: listname: change_typechoices:
- value: featurename: 'feature: A new feature.'
- value: bug fixname: 'bug fix: A bug fix.'message: Select the type of change you are committing
- type: inputname: messagemessage: Body.
- type: confirmname: show_messagemessage: Do you want to add body message in commit?

Customize configuration

ParameterTypeDefaultDescription
questionsQuestionsNoneQuestions regarding the commit message. Detailed below. The type Questions is an alias to Iterable[MutableMapping[str, Any]] which is defined in commitizen.defaults. It expects a list of dictionaries.
message_templatestrNoneThe template for generating message from the given answers. message_template should either follow Jinja2 formatting specification, and all the variables in this template should be defined in name in questions
examplestrNone(OPTIONAL) Provide an example to help understand the style. Used by cz example.
schemastrNone(OPTIONAL) Show the schema used. Used by cz schema.
schema_patternstrNone(OPTIONAL) The regular expression used to do commit message validation. Used by cz check.
info_pathstrNone(OPTIONAL) The path to the file that contains explanation of the commit rules. Used by cz info. If not provided cz info, will load info instead.
infostrNone(OPTIONAL) Explanation of the commit rules. Used by cz info.
bump_mapdictNone(OPTIONAL) Dictionary mapping the extracted information to a SemVer increment type (MAJOR, MINOR, PATCH)
bump_patternstrNone(OPTIONAL) Regex to extract information from commit (subject and body)
change_type_orderstrNone(OPTIONAL) List of strings used to order the Changelog. All other types will be sorted alphabetically. Default is ["BREAKING CHANGE", "Feat", "Fix", "Refactor", "Perf"]
commit_parserstrNone(OPTIONAL) Regex to extract information used in creating changelog. See more
changelog_patternstrNone(OPTIONAL) Regex to understand which commits to include in the changelog
change_type_mapdictNone(OPTIONAL) Dictionary mapping the type of the commit to a changelog entry

Detailed questions content

ParameterTypeDefaultDescription
typestrNoneThe type of questions. Valid type: list, input and etc. [See More][different-question-types]
namestrNoneThe key for the value answered by user. It's used in message_template
messagestrNoneDetail description for the question.
choiceslistNone(OPTIONAL) The choices when type = list. Either use a list of values or a list of dictionaries with name and value keys. Keyboard shortcuts can be defined via key. See examples above.
defaultAnyNone(OPTIONAL) The default value for this question.
filterstrNone(Optional) Validator for user's answer. (Work in Progress)
[different-question-types]: https://github.com/tmbo/questionary#different-question-types

Shortcut keys

When the use_shortcuts config option is enabled, commitizen can show and use keyboard shortcuts to select items from lists directly. For example, when using the cz_conventional_commits commitizen template, shortcut keys are shown when selecting the commit type. Unless otherwise defined, keyboard shortcuts will be numbered automatically. To specify keyboard shortcuts for your custom choices, provide the shortcut using the key parameter in dictionary form for each choice you would like to customize.

2. Customize through customizing a class

The basic steps are:

  1. Inheriting from BaseCommitizen
  2. Give a name to your rules.
  3. Create a python package using setup.py, poetry, etc
  4. Expose the class as a commitizen.plugin entrypoint

Check an example on how to configure BaseCommitizen.

You can also automate the steps above through cookiecutter.

cookiecutter gh:commitizen-tools/commitizen_cz_template

See commitizen_cz_template for details.

Once you publish your rules, you can send us a PR to the Third-party section.

Custom commit rules

Create a Python module, for example cz_jira.py.

Inherit from BaseCommitizen, and you must define questions and message. The others are optional.

fromcommitizen.cz.baseimportBaseCommitizenfromcommitizen.defaultsimportQuestionsclassJiraCz(BaseCommitizen):
# Questions = Iterable[MutableMapping[str, Any]]# It expects a list with dictionaries.defquestions(self) ->Questions:
"""Questions regarding the commit message."""questions= [
{"type": "input", "name": "title", "message": "Commit title"},
{"type": "input", "name": "issue", "message": "Jira Issue number:"},
]
returnquestionsdefmessage(self, answers: dict) ->str:
"""Generate the message with the given answers."""return"{0} (#{1})".format(answers["title"], answers["issue"])
defexample(self) ->str:
"""Provide an example to help understand the style (OPTIONAL) Used by `cz example`. """return"Problem with user (#321)"defschema(self) ->str:
"""Show the schema used (OPTIONAL) Used by `cz schema`. """return"<title> (<issue>)"definfo(self) ->str:
"""Explanation of the commit rules. (OPTIONAL) Used by `cz info`. """return"We use this because is useful"

The next file required is setup.py modified from flask version.

fromsetuptoolsimportsetupsetup(
name="JiraCommitizen",
version="0.1.0",
py_modules=["cz_jira"],
license="MIT",
long_description="this is a long description",
install_requires=["commitizen"],
entry_points={"commitizen.plugin": ["cz_jira = cz_jira:JiraCz"]},
)

So in the end, we would have

.
├── cz_jira.py
└── setup.py

And that's it. You can install it without uploading to pypi by simply doing pip install .

If you feel like it should be part of this repo, create a PR.

Custom bump rules

You need to define 2 parameters inside your custom BaseCommitizen.

ParameterTypeDefaultDescription
bump_patternstrNoneRegex to extract information from commit (subject and body)
bump_mapdictNoneDictionary mapping the extracted information to a SemVer increment type (MAJOR, MINOR, PATCH)

Let's see an example.

fromcommitizen.cz.baseimportBaseCommitizenclassStrangeCommitizen(BaseCommitizen):
bump_pattern=r"^(break|new|fix|hotfix)"bump_map= {"break": "MAJOR", "new": "MINOR", "fix": "PATCH", "hotfix": "PATCH"}

That's it, your commitizen now supports custom rules, and you can run.

cz -n cz_strange bump

Custom changelog generator

The changelog generator should just work in a very basic manner without touching anything. You can customize it of course, and this are the variables you need to add to your custom BaseCommitizen.

ParameterTypeRequiredDescription
commit_parserstrNORegex which should provide the variables explained in the changelog description
changelog_patternstrNORegex to validate the commits, this is useful to skip commits that don't meet your ruling standards like a Merge. Usually the same as bump_pattern
change_type_mapdictNOConvert the title of the change type that will appear in the changelog, if a value is not found, the original will be provided
changelog_message_builder_hookmethod: (dict, git.GitCommit) -> dictNOCustomize with extra information your message output, like adding links, this function is executed per parsed commit. Each GitCommit contains the following attrs: rev, title, body, author, author_email
changelog_hookmethod: (full_changelog: str, partial_changelog: Optional[str]) -> strNOReceives the whole and partial (if used incremental) changelog. Useful to send slack messages or notify a compliance department. Must return the full_changelog
fromcommitizen.cz.baseimportBaseCommitizenimportchatimportcomplianceclassStrangeCommitizen(BaseCommitizen):
changelog_pattern=r"^(break|new|fix|hotfix)"commit_parser=r"^(?P<change_type>feat|fix|refactor|perf|BREAKING CHANGE)(?:\((?P<scope>[^()\r\n]*)\)|\()?(?P<breaking>!)?:\s(?P<message>.*)?"change_type_map= {
"feat": "Features",
"fix": "Bug Fixes",
"refactor": "Code Refactor",
"perf": "Performance improvements",
}
defchangelog_message_builder_hook(
self, parsed_message: dict, commit: git.GitCommit
) ->dict:
rev=commit.revm=parsed_message["message"]
parsed_message[
"message"
] =f"{m}{rev} [{commit.author}]({commit.author_email})"returnparsed_messagedefchangelog_hook(
self, full_changelog: str, partial_changelog: Optional[str]
) ->str:
"""Executed at the end of the changelog generation full_changelog: it's the output about to being written into the file partial_changelog: it's the new stuff, this is useful to send slack messages or similar Return: the new updated full_changelog """ifpartial_changelog:
chat.room("#committers").notify(partial_changelog)
iffull_changelog:
compliance.send(full_changelog)
full_changelog.replace(" fix ", " **fix** ")
returnfull_changelog

Raise Customize Exception

If you want commitizen to catch your exception and print the message, you'll have to inherit CzException.

fromcommitizen.cz.exceptionimportCzExceptionclassNoSubjectProvidedException(CzException):
...

Migrating from legacy plugin format

Commitizen migrated to a new plugin format relying on importlib.metadata.EntryPoint. Migration should be straight-forward for legacy plugins:

  • Remove the discover_this line from you plugin module
  • Expose the plugin class under as a commitizen.plugin entrypoint.

The name of the plugin is now determined by the name of the entrypoint.

Example

If you were having a CzPlugin class in a cz_plugin.py module like this:

fromcommitizen.cz.baseimportBaseCommitizenclassPluginCz(BaseCommitizen):
...
discover_this=PluginCz

Then remove the discover_this line:

fromcommitizen.cz.baseimportBaseCommitizenclassPluginCz(BaseCommitizen):
...

and expose the class as entrypoint in you setuptools:

fromsetuptoolsimportsetupsetup(
name="MyPlugin",
version="0.1.0",
py_modules=["cz_plugin"],
entry_points={"commitizen.plugin": ["plugin = cz_plugin:PluginCz"]},
...,
)

Then your plugin will be available under the name plugin.

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

History
433 lines (340 loc) · 20.5 KB

File metadata and controls

433 lines (340 loc) · 20.5 KB

Customizing commitizen is not hard at all. We have two different ways to do so.

1. Customize in configuration file

The basic steps are:

  1. Define your custom committing or bumping rules in the configuration file.
  2. Declare name = "cz_customize" in your configuration file, or add -n cz_customize when running commitizen.

Example:

[tool.commitizen]
name = "cz_customize"
[tool.commitizen.customize]
message_template = "{{change_type}}:{% if show_message %} {{message}}{% endif %}"example = "feature: this feature enable customize through config file"schema = "<type>: <body>"schema_pattern = "(feature|bug fix):(\\s.*)"bump_pattern = "^(break|new|fix|hotfix)"bump_map = {"break" = "MAJOR", "new" = "MINOR", "fix" = "PATCH", "hotfix" = "PATCH"}
change_type_order = ["BREAKING CHANGE", "feat", "fix", "refactor", "perf"]
info_path = "cz_customize_info.txt"info = """This is customized info"""commit_parser = "^(?P<change_type>feature|bug fix):\\s(?P<message>.*)?"changelog_pattern = "^(feature|bug fix)?(!)?"change_type_map = {"feature" = "Feat", "bug fix" = "Fix"}
[[tool.commitizen.customize.questions]]
type = "list"name = "change_type"choices = [{value = "feature", name = "feature: A new feature."}, {value = "bug fix", name = "bug fix: A bug fix."}]
# choices = ["feature", "fix"] # short versionmessage = "Select the type of change you are committing"
[[tool.commitizen.customize.questions]]
type = "input"name = "message"message = "Body."
[[tool.commitizen.customize.questions]]
type = "confirm"name = "show_message"message = "Do you want to add body message in commit?"

The equivalent example for a json config file:

{
"commitizen": {
"name": "cz_customize",
"customize": {
"message_template": "{{change_type}}:{% if show_message %} {{message}}{% endif %}",
"example": "feature: this feature enable customize through config file",
"schema": "<type>: <body>",
"schema_pattern": "(feature|bug fix):(\\s.*)",
"bump_pattern": "^(break|new|fix|hotfix)",
"bump_map": {
"break": "MAJOR",
"new": "MINOR",
"fix": "PATCH",
"hotfix": "PATCH"
},
"change_type_order": ["BREAKING CHANGE", "feat", "fix", "refactor", "perf"],
"info_path": "cz_customize_info.txt",
"info": "This is customized info",
"commit_parser": "^(?P<change_type>feature|bug fix):\\s(?P<message>.*)?",
"changelog_pattern": "^(feature|bug fix)?(!)?",
"change_type_map": {"feature": "Feat", "bug fix": "Fix"},
"questions": [
{
"type": "list",
"name": "change_type",
"choices": [
{
"value": "feature",
"name": "feature: A new feature."
},
{
"value": "bug fix",
"name": "bug fix: A bug fix."
}
],
"message": "Select the type of change you are committing"
},
{
"type": "input",
"name": "message",
"message": "Body."
},
{
"type": "confirm",
"name": "show_message",
"message": "Do you want to add body message in commit?"
}
]
}
}
}

And the correspondent example for a yaml json file:

commitizen:
name: cz_customizecustomize:
message_template: "{{change_type}}:{% if show_message %} {{message}}{% endif %}"example: 'feature: this feature enable customize through config file'schema: "<type>: <body>"schema_pattern: "(feature|bug fix):(\\s.*)"bump_pattern: "^(break|new|fix|hotfix)"commit_parser: "^(?P<change_type>feature|bug fix):\\s(?P<message>.*)?",changelog_pattern: "^(feature|bug fix)?(!)?",change_type_map:
feature: Featbug fix: Fixbump_map:
break: MAJORnew: MINORfix: PATCHhotfix: PATCHchange_type_order: ["BREAKING CHANGE", "feat", "fix", "refactor", "perf"]info_path: cz_customize_info.txtinfo: This is customized infoquestions:
- type: listname: change_typechoices:
- value: featurename: 'feature: A new feature.'
- value: bug fixname: 'bug fix: A bug fix.'message: Select the type of change you are committing
- type: inputname: messagemessage: Body.
- type: confirmname: show_messagemessage: Do you want to add body message in commit?

Customize configuration

ParameterTypeDefaultDescription
questionsQuestionsNoneQuestions regarding the commit message. Detailed below. The type Questions is an alias to Iterable[MutableMapping[str, Any]] which is defined in commitizen.defaults. It expects a list of dictionaries.
message_templatestrNoneThe template for generating message from the given answers. message_template should either follow Jinja2 formatting specification, and all the variables in this template should be defined in name in questions
examplestrNone(OPTIONAL) Provide an example to help understand the style. Used by cz example.
schemastrNone(OPTIONAL) Show the schema used. Used by cz schema.
schema_patternstrNone(OPTIONAL) The regular expression used to do commit message validation. Used by cz check.
info_pathstrNone(OPTIONAL) The path to the file that contains explanation of the commit rules. Used by cz info. If not provided cz info, will load info instead.
infostrNone(OPTIONAL) Explanation of the commit rules. Used by cz info.
bump_mapdictNone(OPTIONAL) Dictionary mapping the extracted information to a SemVer increment type (MAJOR, MINOR, PATCH)
bump_patternstrNone(OPTIONAL) Regex to extract information from commit (subject and body)
change_type_orderstrNone(OPTIONAL) List of strings used to order the Changelog. All other types will be sorted alphabetically. Default is ["BREAKING CHANGE", "Feat", "Fix", "Refactor", "Perf"]
commit_parserstrNone(OPTIONAL) Regex to extract information used in creating changelog. See more
changelog_patternstrNone(OPTIONAL) Regex to understand which commits to include in the changelog
change_type_mapdictNone(OPTIONAL) Dictionary mapping the type of the commit to a changelog entry

Detailed questions content

ParameterTypeDefaultDescription
typestrNoneThe type of questions. Valid type: list, input and etc. [See More][different-question-types]
namestrNoneThe key for the value answered by user. It's used in message_template
messagestrNoneDetail description for the question.
choiceslistNone(OPTIONAL) The choices when type = list. Either use a list of values or a list of dictionaries with name and value keys. Keyboard shortcuts can be defined via key. See examples above.
defaultAnyNone(OPTIONAL) The default value for this question.
filterstrNone(Optional) Validator for user's answer. (Work in Progress)
[different-question-types]: https://github.com/tmbo/questionary#different-question-types

Shortcut keys

When the use_shortcuts config option is enabled, commitizen can show and use keyboard shortcuts to select items from lists directly. For example, when using the cz_conventional_commits commitizen template, shortcut keys are shown when selecting the commit type. Unless otherwise defined, keyboard shortcuts will be numbered automatically. To specify keyboard shortcuts for your custom choices, provide the shortcut using the key parameter in dictionary form for each choice you would like to customize.

2. Customize through customizing a class

The basic steps are:

  1. Inheriting from BaseCommitizen
  2. Give a name to your rules.
  3. Create a python package using setup.py, poetry, etc
  4. Expose the class as a commitizen.plugin entrypoint

Check an example on how to configure BaseCommitizen.

You can also automate the steps above through cookiecutter.

cookiecutter gh:commitizen-tools/commitizen_cz_template

See commitizen_cz_template for details.

Once you publish your rules, you can send us a PR to the Third-party section.

Custom commit rules

Create a Python module, for example cz_jira.py.

Inherit from BaseCommitizen, and you must define questions and message. The others are optional.

fromcommitizen.cz.baseimportBaseCommitizenfromcommitizen.defaultsimportQuestionsclassJiraCz(BaseCommitizen):
# Questions = Iterable[MutableMapping[str, Any]]# It expects a list with dictionaries.defquestions(self) ->Questions:
"""Questions regarding the commit message."""questions= [
{"type": "input", "name": "title", "message": "Commit title"},
{"type": "input", "name": "issue", "message": "Jira Issue number:"},
]
returnquestionsdefmessage(self, answers: dict) ->str:
"""Generate the message with the given answers."""return"{0} (#{1})".format(answers["title"], answers["issue"])
defexample(self) ->str:
"""Provide an example to help understand the style (OPTIONAL) Used by `cz example`. """return"Problem with user (#321)"defschema(self) ->str:
"""Show the schema used (OPTIONAL) Used by `cz schema`. """return"<title> (<issue>)"definfo(self) ->str:
"""Explanation of the commit rules. (OPTIONAL) Used by `cz info`. """return"We use this because is useful"

The next file required is setup.py modified from flask version.

fromsetuptoolsimportsetupsetup(
name="JiraCommitizen",
version="0.1.0",
py_modules=["cz_jira"],
license="MIT",
long_description="this is a long description",
install_requires=["commitizen"],
entry_points={"commitizen.plugin": ["cz_jira = cz_jira:JiraCz"]},
)

So in the end, we would have

.
├── cz_jira.py
└── setup.py

And that's it. You can install it without uploading to pypi by simply doing pip install .

If you feel like it should be part of this repo, create a PR.

Custom bump rules

You need to define 2 parameters inside your custom BaseCommitizen.

ParameterTypeDefaultDescription
bump_patternstrNoneRegex to extract information from commit (subject and body)
bump_mapdictNoneDictionary mapping the extracted information to a SemVer increment type (MAJOR, MINOR, PATCH)

Let's see an example.

fromcommitizen.cz.baseimportBaseCommitizenclassStrangeCommitizen(BaseCommitizen):
bump_pattern=r"^(break|new|fix|hotfix)"bump_map= {"break": "MAJOR", "new": "MINOR", "fix": "PATCH", "hotfix": "PATCH"}

That's it, your commitizen now supports custom rules, and you can run.

cz -n cz_strange bump

Custom changelog generator

The changelog generator should just work in a very basic manner without touching anything. You can customize it of course, and this are the variables you need to add to your custom BaseCommitizen.

ParameterTypeRequiredDescription
commit_parserstrNORegex which should provide the variables explained in the changelog description
changelog_patternstrNORegex to validate the commits, this is useful to skip commits that don't meet your ruling standards like a Merge. Usually the same as bump_pattern
change_type_mapdictNOConvert the title of the change type that will appear in the changelog, if a value is not found, the original will be provided
changelog_message_builder_hookmethod: (dict, git.GitCommit) -> dictNOCustomize with extra information your message output, like adding links, this function is executed per parsed commit. Each GitCommit contains the following attrs: rev, title, body, author, author_email
changelog_hookmethod: (full_changelog: str, partial_changelog: Optional[str]) -> strNOReceives the whole and partial (if used incremental) changelog. Useful to send slack messages or notify a compliance department. Must return the full_changelog
fromcommitizen.cz.baseimportBaseCommitizenimportchatimportcomplianceclassStrangeCommitizen(BaseCommitizen):
changelog_pattern=r"^(break|new|fix|hotfix)"commit_parser=r"^(?P<change_type>feat|fix|refactor|perf|BREAKING CHANGE)(?:\((?P<scope>[^()\r\n]*)\)|\()?(?P<breaking>!)?:\s(?P<message>.*)?"change_type_map= {
"feat": "Features",
"fix": "Bug Fixes",
"refactor": "Code Refactor",
"perf": "Performance improvements",
}
defchangelog_message_builder_hook(
self, parsed_message: dict, commit: git.GitCommit
) ->dict:
rev=commit.revm=parsed_message["message"]
parsed_message[
"message"
] =f"{m}{rev} [{commit.author}]({commit.author_email})"returnparsed_messagedefchangelog_hook(
self, full_changelog: str, partial_changelog: Optional[str]
) ->str:
"""Executed at the end of the changelog generation full_changelog: it's the output about to being written into the file partial_changelog: it's the new stuff, this is useful to send slack messages or similar Return: the new updated full_changelog """ifpartial_changelog:
chat.room("#committers").notify(partial_changelog)
iffull_changelog:
compliance.send(full_changelog)
full_changelog.replace(" fix ", " **fix** ")
returnfull_changelog

Raise Customize Exception

If you want commitizen to catch your exception and print the message, you'll have to inherit CzException.

fromcommitizen.cz.exceptionimportCzExceptionclassNoSubjectProvidedException(CzException):
...

Migrating from legacy plugin format

Commitizen migrated to a new plugin format relying on importlib.metadata.EntryPoint. Migration should be straight-forward for legacy plugins:

  • Remove the discover_this line from you plugin module
  • Expose the plugin class under as a commitizen.plugin entrypoint.

The name of the plugin is now determined by the name of the entrypoint.

Example

If you were having a CzPlugin class in a cz_plugin.py module like this:

fromcommitizen.cz.baseimportBaseCommitizenclassPluginCz(BaseCommitizen):
...
discover_this=PluginCz

Then remove the discover_this line:

fromcommitizen.cz.baseimportBaseCommitizenclassPluginCz(BaseCommitizen):
...

and expose the class as entrypoint in you setuptools:

fromsetuptoolsimportsetupsetup(
name="MyPlugin",
version="0.1.0",
py_modules=["cz_plugin"],
entry_points={"commitizen.plugin": ["plugin = cz_plugin:PluginCz"]},
...,
)

Then your plugin will be available under the name plugin.

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Latest commit

History

History
433 lines (340 loc) · 20.5 KB

File metadata and controls

433 lines (340 loc) · 20.5 KB

Customizing commitizen is not hard at all. We have two different ways to do so.

1. Customize in configuration file

The basic steps are:

  1. Define your custom committing or bumping rules in the configuration file.
  2. Declare name = "cz_customize" in your configuration file, or add -n cz_customize when running commitizen.

Example:

[tool.commitizen]
name = "cz_customize"
[tool.commitizen.customize]
message_template = "{{change_type}}:{% if show_message %} {{message}}{% endif %}"example = "feature: this feature enable customize through config file"schema = "<type>: <body>"schema_pattern = "(feature|bug fix):(\\s.*)"bump_pattern = "^(break|new|fix|hotfix)"bump_map = {"break" = "MAJOR", "new" = "MINOR", "fix" = "PATCH", "hotfix" = "PATCH"}
change_type_order = ["BREAKING CHANGE", "feat", "fix", "refactor", "perf"]
info_path = "cz_customize_info.txt"info = """This is customized info"""commit_parser = "^(?P<change_type>feature|bug fix):\\s(?P<message>.*)?"changelog_pattern = "^(feature|bug fix)?(!)?"change_type_map = {"feature" = "Feat", "bug fix" = "Fix"}
[[tool.commitizen.customize.questions]]
type = "list"name = "change_type"choices = [{value = "feature", name = "feature: A new feature."}, {value = "bug fix", name = "bug fix: A bug fix."}]
# choices = ["feature", "fix"] # short versionmessage = "Select the type of change you are committing"
[[tool.commitizen.customize.questions]]
type = "input"name = "message"message = "Body."
[[tool.commitizen.customize.questions]]
type = "confirm"name = "show_message"message = "Do you want to add body message in commit?"

The equivalent example for a json config file:

{
"commitizen": {
"name": "cz_customize",
"customize": {
"message_template": "{{change_type}}:{% if show_message %} {{message}}{% endif %}",
"example": "feature: this feature enable customize through config file",
"schema": "<type>: <body>",
"schema_pattern": "(feature|bug fix):(\\s.*)",
"bump_pattern": "^(break|new|fix|hotfix)",
"bump_map": {
"break": "MAJOR",
"new": "MINOR",
"fix": "PATCH",
"hotfix": "PATCH"
},
"change_type_order": ["BREAKING CHANGE", "feat", "fix", "refactor", "perf"],
"info_path": "cz_customize_info.txt",
"info": "This is customized info",
"commit_parser": "^(?P<change_type>feature|bug fix):\\s(?P<message>.*)?",
"changelog_pattern": "^(feature|bug fix)?(!)?",
"change_type_map": {"feature": "Feat", "bug fix": "Fix"},
"questions": [
{
"type": "list",
"name": "change_type",
"choices": [
{
"value": "feature",
"name": "feature: A new feature."
},
{
"value": "bug fix",
"name": "bug fix: A bug fix."
}
],
"message": "Select the type of change you are committing"
},
{
"type": "input",
"name": "message",
"message": "Body."
},
{
"type": "confirm",
"name": "show_message",
"message": "Do you want to add body message in commit?"
}
]
}
}
}

And the correspondent example for a yaml json file:

commitizen:
name: cz_customizecustomize:
message_template: "{{change_type}}:{% if show_message %} {{message}}{% endif %}"example: 'feature: this feature enable customize through config file'schema: "<type>: <body>"schema_pattern: "(feature|bug fix):(\\s.*)"bump_pattern: "^(break|new|fix|hotfix)"commit_parser: "^(?P<change_type>feature|bug fix):\\s(?P<message>.*)?",changelog_pattern: "^(feature|bug fix)?(!)?",change_type_map:
feature: Featbug fix: Fixbump_map:
break: MAJORnew: MINORfix: PATCHhotfix: PATCHchange_type_order: ["BREAKING CHANGE", "feat", "fix", "refactor", "perf"]info_path: cz_customize_info.txtinfo: This is customized infoquestions:
- type: listname: change_typechoices:
- value: featurename: 'feature: A new feature.'
- value: bug fixname: 'bug fix: A bug fix.'message: Select the type of change you are committing
- type: inputname: messagemessage: Body.
- type: confirmname: show_messagemessage: Do you want to add body message in commit?

Customize configuration

ParameterTypeDefaultDescription
questionsQuestionsNoneQuestions regarding the commit message. Detailed below. The type Questions is an alias to Iterable[MutableMapping[str, Any]] which is defined in commitizen.defaults. It expects a list of dictionaries.
message_templatestrNoneThe template for generating message from the given answers. message_template should either follow Jinja2 formatting specification, and all the variables in this template should be defined in name in questions
examplestrNone(OPTIONAL) Provide an example to help understand the style. Used by cz example.
schemastrNone(OPTIONAL) Show the schema used. Used by cz schema.
schema_patternstrNone(OPTIONAL) The regular expression used to do commit message validation. Used by cz check.
info_pathstrNone(OPTIONAL) The path to the file that contains explanation of the commit rules. Used by cz info. If not provided cz info, will load info instead.
infostrNone(OPTIONAL) Explanation of the commit rules. Used by cz info.
bump_mapdictNone(OPTIONAL) Dictionary mapping the extracted information to a SemVer increment type (MAJOR, MINOR, PATCH)
bump_patternstrNone(OPTIONAL) Regex to extract information from commit (subject and body)
change_type_orderstrNone(OPTIONAL) List of strings used to order the Changelog. All other types will be sorted alphabetically. Default is ["BREAKING CHANGE", "Feat", "Fix", "Refactor", "Perf"]
commit_parserstrNone(OPTIONAL) Regex to extract information used in creating changelog. See more
changelog_patternstrNone(OPTIONAL) Regex to understand which commits to include in the changelog
change_type_mapdictNone(OPTIONAL) Dictionary mapping the type of the commit to a changelog entry

Detailed questions content

ParameterTypeDefaultDescription
typestrNoneThe type of questions. Valid type: list, input and etc. [See More][different-question-types]
namestrNoneThe key for the value answered by user. It's used in message_template
messagestrNoneDetail description for the question.
choiceslistNone(OPTIONAL) The choices when type = list. Either use a list of values or a list of dictionaries with name and value keys. Keyboard shortcuts can be defined via key. See examples above.
defaultAnyNone(OPTIONAL) The default value for this question.
filterstrNone(Optional) Validator for user's answer. (Work in Progress)
[different-question-types]: https://github.com/tmbo/questionary#different-question-types

Shortcut keys

When the use_shortcuts config option is enabled, commitizen can show and use keyboard shortcuts to select items from lists directly. For example, when using the cz_conventional_commits commitizen template, shortcut keys are shown when selecting the commit type. Unless otherwise defined, keyboard shortcuts will be numbered automatically. To specify keyboard shortcuts for your custom choices, provide the shortcut using the key parameter in dictionary form for each choice you would like to customize.

2. Customize through customizing a class

The basic steps are:

  1. Inheriting from BaseCommitizen
  2. Give a name to your rules.
  3. Create a python package using setup.py, poetry, etc
  4. Expose the class as a commitizen.plugin entrypoint

Check an example on how to configure BaseCommitizen.

You can also automate the steps above through cookiecutter.

cookiecutter gh:commitizen-tools/commitizen_cz_template

See commitizen_cz_template for details.

Once you publish your rules, you can send us a PR to the Third-party section.

Custom commit rules

Create a Python module, for example cz_jira.py.

Inherit from BaseCommitizen, and you must define questions and message. The others are optional.

fromcommitizen.cz.baseimportBaseCommitizenfromcommitizen.defaultsimportQuestionsclassJiraCz(BaseCommitizen):
# Questions = Iterable[MutableMapping[str, Any]]# It expects a list with dictionaries.defquestions(self) ->Questions:
"""Questions regarding the commit message."""questions= [
{"type": "input", "name": "title", "message": "Commit title"},
{"type": "input", "name": "issue", "message": "Jira Issue number:"},
]
returnquestionsdefmessage(self, answers: dict) ->str:
"""Generate the message with the given answers."""return"{0} (#{1})".format(answers["title"], answers["issue"])
defexample(self) ->str:
"""Provide an example to help understand the style (OPTIONAL) Used by `cz example`. """return"Problem with user (#321)"defschema(self) ->str:
"""Show the schema used (OPTIONAL) Used by `cz schema`. """return"<title> (<issue>)"definfo(self) ->str:
"""Explanation of the commit rules. (OPTIONAL) Used by `cz info`. """return"We use this because is useful"

The next file required is setup.py modified from flask version.

fromsetuptoolsimportsetupsetup(
name="JiraCommitizen",
version="0.1.0",
py_modules=["cz_jira"],
license="MIT",
long_description="this is a long description",
install_requires=["commitizen"],
entry_points={"commitizen.plugin": ["cz_jira = cz_jira:JiraCz"]},
)

So in the end, we would have

.
├── cz_jira.py
└── setup.py

And that's it. You can install it without uploading to pypi by simply doing pip install .

If you feel like it should be part of this repo, create a PR.

Custom bump rules

You need to define 2 parameters inside your custom BaseCommitizen.

ParameterTypeDefaultDescription
bump_patternstrNoneRegex to extract information from commit (subject and body)
bump_mapdictNoneDictionary mapping the extracted information to a SemVer increment type (MAJOR, MINOR, PATCH)

Let's see an example.

fromcommitizen.cz.baseimportBaseCommitizenclassStrangeCommitizen(BaseCommitizen):
bump_pattern=r"^(break|new|fix|hotfix)"bump_map= {"break": "MAJOR", "new": "MINOR", "fix": "PATCH", "hotfix": "PATCH"}

That's it, your commitizen now supports custom rules, and you can run.

cz -n cz_strange bump

Custom changelog generator

The changelog generator should just work in a very basic manner without touching anything. You can customize it of course, and this are the variables you need to add to your custom BaseCommitizen.

ParameterTypeRequiredDescription
commit_parserstrNORegex which should provide the variables explained in the changelog description
changelog_patternstrNORegex to validate the commits, this is useful to skip commits that don't meet your ruling standards like a Merge. Usually the same as bump_pattern
change_type_mapdictNOConvert the title of the change type that will appear in the changelog, if a value is not found, the original will be provided
changelog_message_builder_hookmethod: (dict, git.GitCommit) -> dictNOCustomize with extra information your message output, like adding links, this function is executed per parsed commit. Each GitCommit contains the following attrs: rev, title, body, author, author_email
changelog_hookmethod: (full_changelog: str, partial_changelog: Optional[str]) -> strNOReceives the whole and partial (if used incremental) changelog. Useful to send slack messages or notify a compliance department. Must return the full_changelog
fromcommitizen.cz.baseimportBaseCommitizenimportchatimportcomplianceclassStrangeCommitizen(BaseCommitizen):
changelog_pattern=r"^(break|new|fix|hotfix)"commit_parser=r"^(?P<change_type>feat|fix|refactor|perf|BREAKING CHANGE)(?:\((?P<scope>[^()\r\n]*)\)|\()?(?P<breaking>!)?:\s(?P<message>.*)?"change_type_map= {
"feat": "Features",
"fix": "Bug Fixes",
"refactor": "Code Refactor",
"perf": "Performance improvements",
}
defchangelog_message_builder_hook(
self, parsed_message: dict, commit: git.GitCommit
) ->dict:
rev=commit.revm=parsed_message["message"]
parsed_message[
"message"
] =f"{m}{rev} [{commit.author}]({commit.author_email})"returnparsed_messagedefchangelog_hook(
self, full_changelog: str, partial_changelog: Optional[str]
) ->str:
"""Executed at the end of the changelog generation full_changelog: it's the output about to being written into the file partial_changelog: it's the new stuff, this is useful to send slack messages or similar Return: the new updated full_changelog """ifpartial_changelog:
chat.room("#committers").notify(partial_changelog)
iffull_changelog:
compliance.send(full_changelog)
full_changelog.replace(" fix ", " **fix** ")
returnfull_changelog

Raise Customize Exception

If you want commitizen to catch your exception and print the message, you'll have to inherit CzException.

fromcommitizen.cz.exceptionimportCzExceptionclassNoSubjectProvidedException(CzException):
...

Migrating from legacy plugin format

Commitizen migrated to a new plugin format relying on importlib.metadata.EntryPoint. Migration should be straight-forward for legacy plugins:

  • Remove the discover_this line from you plugin module
  • Expose the plugin class under as a commitizen.plugin entrypoint.

The name of the plugin is now determined by the name of the entrypoint.

Example

If you were having a CzPlugin class in a cz_plugin.py module like this:

fromcommitizen.cz.baseimportBaseCommitizenclassPluginCz(BaseCommitizen):
...
discover_this=PluginCz

Then remove the discover_this line:

fromcommitizen.cz.baseimportBaseCommitizenclassPluginCz(BaseCommitizen):
...

and expose the class as entrypoint in you setuptools:

fromsetuptoolsimportsetupsetup(
name="MyPlugin",
version="0.1.0",
py_modules=["cz_plugin"],
entry_points={"commitizen.plugin": ["plugin = cz_plugin:PluginCz"]},
...,
)

Then your plugin will be available under the name plugin.