Debian Codegraph @

docs/user_defined_rules.md

raw symbols SCIP
1 # User Defined Rules
2 _Introduced in gitlint v0.8.0_
3
4 Gitlint supports the concept of **user-defined** rules: the ability for users to write their own custom rules in python.
5
6 In a nutshell, use `--extra-path /home/joe/myextensions` to point gitlint to a `myextensions` directory where it will search
7 for python files containing gitlint rule classes. You can also specify a single python module, ie
8 `--extra-path /home/joe/my_rules.py`.
9
10 ```sh
11 cat examples/commit-message-1 | gitlint --extra-path examples/
12 # Example output of a user-defined Signed-off-by rule
13 1: UC2 Body does not contain a 'Signed-off-by Line'
14 # other violations were removed for brevity
15 ```
16
17 The `SignedOffBy` user-defined `CommitRule` was discovered by gitlint when it scanned
18 [examples/gitlint/my_commit_rules.py](https://github.com/jorisroovers/gitlint/blob/main/examples/my_commit_rules.py),
19 which is part of the examples directory that was passed via `--extra-path`:
20
21 ```python
22 # -*- coding: utf-8 -*-
23 from gitlint.rules import CommitRule, RuleViolation
24
25 class SignedOffBy(CommitRule):
26 """ This rule will enforce that each commit contains a "Signed-off-by" line.
27 We keep things simple here and just check whether the commit body contains a
28 line that starts with "Signed-off-by".
29 """
30
31 # A rule MUST have a human friendly name
32 name = "body-requires-signed-off-by"
33
34 # A rule MUST have a *unique* id, we recommend starting with UC
35 # (for User-defined Commit-rule).
36 id = "UC2"
37
38 def validate(self, commit):
39 self.log.debug("SignedOffBy: This will be visible when running `gitlint --debug`")
40
41 for line in commit.message.body:
42 if line.startswith("Signed-off-by"):
43 return
44
45 msg = "Body does not contain a 'Signed-off-by' line"
46 return [RuleViolation(self.id, msg, line_nr=1)]
47 ```
48
49 As always, `--extra-path` can also be set by adding it under the `[general]` section in your `.gitlint` file or using
50 [one of the other ways to configure gitlint](configuration.md).
51
52 If you want to check whether your rules are properly discovered by gitlint, you can use the `--debug` flag:
53
54 ```sh
55 $ gitlint --debug --extra-path examples/
56 # [output cut for brevity]
57 UC1: body-max-line-count
58 body-max-line-count=3
59 UC2: body-requires-signed-off-by
60 UL1: title-no-special-chars
61 special-chars=['$', '^', '%', '@', '!', '*', '(', ')']
62 ```
63
64 !!! Note
65 In most cases it's really the easiest to just copy an example from the
66 [examples](https://github.com/jorisroovers/gitlint/tree/main/examples) directory and modify it to your needs.
67 The remainder of this page contains the technical details, mostly for reference.
68
69 ## Line and Commit Rules
70 The `SignedOffBy` class above was an example of a user-defined `CommitRule`. Commit rules are gitlint rules that
71 act on the entire commit at once. Once the rules are discovered, gitlint will automatically take care of applying them
72 to the entire commit. This happens exactly once per commit.
73
74 A `CommitRule` contrasts with a `LineRule`
75 (see e.g.: [examples/my_line_rules.py](https://github.com/jorisroovers/gitlint/blob/main/examples/my_line_rules.py))
76 in that a `CommitRule` is only applied once on an entire commit while a `LineRule` is applied for every line in the commit
77 (you can also apply it once to the title using a `target` - see the examples section below).
78
79 The benefit of a commit rule is that it allows commit rules to implement more complex checks that span multiple lines and/or checks
80 that should only be done once per commit.
81
82 While every `LineRule` can be implemented as a `CommitRule`, it's usually easier and more concise to go with a `LineRule` if
83 that fits your needs.
84
85 ### Examples
86
87 In terms of code, writing your own `CommitRule` or `LineRule` is very similar.
88 The only 2 differences between a `CommitRule` and a `LineRule` are the parameters of the `validate(...)` method and the extra
89 `target` attribute that `LineRule` requires.
90
91 Consider the following `CommitRule` that can be found in [examples/my_commit_rules.py](https://github.com/jorisroovers/gitlint/blob/main/examples/my_commit_rules.py):
92
93 ```python
94 # -*- coding: utf-8 -*-
95 from gitlint.rules import CommitRule, RuleViolation
96
97 class SignedOffBy(CommitRule):
98 """ This rule will enforce that each commit contains a "Signed-off-by" line.
99 We keep things simple here and just check whether the commit body contains a
100 line that starts with "Signed-off-by".
101 """
102
103 # A rule MUST have a human friendly name
104 name = "body-requires-signed-off-by"
105
106 # A rule MUST have a *unique* id, we recommend starting with UC
107 # (for User-defined Commit-rule).
108 id = "UC2"
109
110 def validate(self, commit):
111 self.log.debug("SignedOffBy: This will be visible when running `gitlint --debug`")
112
113 for line in commit.message.body:
114 if line.startswith("Signed-off-by"):
115 return
116
117 msg = "Body does not contain a 'Signed-off-by' line"
118 return [RuleViolation(self.id, msg, line_nr=1)]
119 ```
120 Note the use of the `name` and `id` class attributes and the `validate(...)` method taking a single `commit` parameter.
121
122 Contrast this with the following `LineRule` that can be found in [examples/my_line_rules.py](https://github.com/jorisroovers/gitlint/blob/main/examples/my_line_rules.py):
123
124 ```python
125 # -*- coding: utf-8 -*-
126 from gitlint.rules import LineRule, RuleViolation, CommitMessageTitle
127 from gitlint.options import ListOption
128
129 class SpecialChars(LineRule):
130 """ This rule will enforce that the commit message title does not contai
131 any of the following characters:
132 $^%@!*() """
133
134 # A rule MUST have a human friendly name
135 name = "title-no-special-chars"
136
137 # A rule MUST have a *unique* id, we recommend starting with UL
138 # for User-defined Line-rule), but this can really be anything.
139 id = "UL1"
140
141 # A line-rule MUST have a target (not required for CommitRules).
142 target = CommitMessageTitle
143
144 # A rule MAY have an option_spec if its behavior should be configurable.
145 options_spec = [ListOption('special-chars', ['$', '^', '%', '@', '!', '*', '(', ')'],
146 "Comma separated list of characters that should not occur in the title")]
147
148 def validate(self, line, _commit):
149 self.log.debug("SpecialChars: This will be visible when running `gitlint --debug`")
150
151 violations = []
152 # options can be accessed by looking them up by their name in self.options
153 for char in self.options['special-chars'].value:
154 if char in line:
155 msg = f"Title contains the special character '{char}'"
156 violation = RuleViolation(self.id, msg, line)
157 violations.append(violation)
158
159 return violations
160
161 ```
162
163 Note the following 2 differences:
164
165 - **extra `target` class attribute**: in this example set to `CommitMessageTitle` indicating that this `LineRule`
166 should only be applied once to the commit message title. The alternative value for `target` is `CommitMessageBody`,
167 in which case gitlint will apply
168 your rule to **every** line in the commit message body.
169 - **`validate(...)` takes 2 parameters**: Line rules get the `line` against which they are applied as the first parameter and
170 the `commit` object of which the line is part of as second.
171
172 In addition, you probably also noticed the extra `options_spec` class attribute which allows you to make your rules configurable.
173 Options are not unique to `LineRule`s, they can also be used by `CommitRule`s and are further explained in the
174 [Options](user_defined_rules.md#options) section below.
175
176
177 ## The commit object
178 Both `CommitRule`s and `LineRule`s take a `commit` object in their `validate(...)` methods.
179 The table below outlines the various attributes of that commit object that can be used during validation.
180
181
182 | Property | Type | Description |
183 | -------------------------------------------- | --------------------------------- | ------------------------------------------------------------------------------------ |
184 | commit | `GitCommit` | Python object representing the commit |
185 | commit.message | `GitCommitMessage` | Python object representing the commit message |
186 | commit.message.original | `str` | Original commit message as returned by git |
187 | commit.message.full | `str` | Full commit message, with comments (lines starting with #) removed. |
188 | commit.message.title | `str` | Title/subject of the commit message: the first line |
189 | commit.message.body | `str[]` | List of lines in the body of the commit message (i.e. starting from the second line) |
190 | commit.author_name | `str` | Name of the author, result of `git log --pretty=%aN` |
191 | commit.author_email | `str` | Email of the author, result of `git log --pretty=%aE` |
192 | commit.date | `datetime.datetime` | Python `datetime` object representing the time of commit |
193 | commit.is_merge_commit | `bool` | Boolean indicating whether the commit is a merge commit or not. |
194 | commit.is_revert_commit | `bool` | Boolean indicating whether the commit is a revert commit or not. |
195 | commit.is_fixup_commit | `bool` | Boolean indicating whether the commit is a fixup commit or not. |
196 | commit.is_fixup_amend_commit | `bool` | Boolean indicating whether the commit is a (fixup) amend commit or not. |
197 | commit.is_squash_commit | `bool` | Boolean indicating whether the commit is a squash commit or not. |
198 | commit.parents | `str[]` | List of parent commit `sha`s (only for merge commits). |
199 | commit.changed_files | `str[]` | List of files changed in the commit (relative paths). |
200 | commit.changed_files_stats | `dict[str, GitChangedFilesStats]` | Dictionary mapping the changed files to a `GitChangedFilesStats` objects |
201 | commit.changed_files_stats["path"].filepath | `pathlib.Path` | Relative path (compared to repo root) of the file that was changed. |
202 | commit.changed_files_stats["path"].additions | `int` | Number of additions in the file. |
203 | commit.changed_files_stats["path"].deletions | `int` | Number of deletions in the file. |
204 | commit.branches | `str[]` | List of branch names the commit is part of |
205 | commit.context | `GitContext` | Object pointing to the bigger git context that the commit is part of |
206 | commit.context.current_branch | `str` | Name of the currently active branch (of local repo) |
207 | commit.context.repository_path | `str` | Absolute path pointing to the git repository being linted |
208 | commit.context.commits | `GitCommit[]` | List of commits gitlint is acting on, NOT all commits in the repo. |
209
210 ## Violations
211 In order to let gitlint know that there is a violation in the commit being linted, users should have the `validate(...)`
212 method in their rules return a list of `RuleViolation`s.
213
214 !!! important
215 The `validate(...)` method doesn't always need to return a list, you can just skip the return statement in case there are no violations.
216 However, in case of a single violation, validate should return a **list** with a single item.
217
218 The `RuleViolation` class has the following generic signature:
219
220 ```python
221 RuleViolation(rule_id, message, content=None, line_nr=None):
222 ```
223 With the parameters meaning the following:
224
225 | Parameter | Type | Description |
226 | --------- | ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
227 | rule_id | `str` | Rule's unique string id |
228 | message | `str` | Short description of the violation |
229 | content | `str` | (optional) the violating part of commit or line |
230 | line_nr | `int` | (optional) line number in the commit message where the violation occurs. **Automatically set to the correct line number for `LineRule`s if not set explicitly.** |
231
232 A typical `validate(...)` implementation for a `CommitRule` would then be as follows:
233 ```python
234 def validate(self, commit)
235 for line_nr, line in commit.message.body:
236 if "Jon Snow" in line:
237 # we add 1 to the line_nr because we offset the title which is on the first line
238 return [RuleViolation(self.id, "Commit message has the words 'Jon Snow' in it", line, line_nr + 1)]
239 return []
240 ```
241
242 The parameters of this `RuleViolation` can be directly mapped onto gitlint's output as follows:
243
244 ![How Rule violations map to gitlint output](images/RuleViolation.png)
245
246 ## Options
247
248 In order to make your own rules configurable, you can add an optional `options_spec` attribute to your rule class
249 (supported for both `LineRule` and `CommitRule`).
250
251 ```python
252 # -*- coding: utf-8 -*-
253 from gitlint.rules import CommitRule, RuleViolation
254 from gitlint.options import IntOption
255
256 class BodyMaxLineCount(CommitRule):
257 # A rule MUST have a human friendly name
258 name = "body-max-line-count"
259
260 # A rule MUST have a *unique* id, we recommend starting with UC (for
261 # User-defined Commit-rule).
262 id = "UC1"
263
264 # A rule MAY have an option_spec if its behavior should be configurable.
265 options_spec = [IntOption('max-line-count', 3, "Maximum body line count")]
266
267 def validate(self, commit):
268 line_count = len(commit.message.body)
269 max_line_count = self.options['max-line-count'].value
270 if line_count > max_line_count:
271 message = f"Body contains too many lines ({line_count} > {max_line_count})"
272 return [RuleViolation(self.id, message, line_nr=1)]
273 ```
274
275
276 By using `options_spec`, you make your option available to be configured through a `.gitlint` file
277 or one of the [other ways to configure gitlint](configuration.md). Gitlint automatically takes care of the parsing and input validation.
278
279 For example, to change the value of the `max-line-count` option, add the following to your `.gitlint` file:
280 ```ini
281 [body-max-line-count]
282 body-max-line-count=1
283 ```
284
285 As `options_spec` is a list, you can obviously have multiple options per rule. The general signature of an option is:
286 `Option(name, default_value, description)`.
287
288 Gitlint supports a variety of different option types, all can be imported from `gitlint.options`:
289
290 | Option Class | Use for |
291 | ------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
292 | `StrOption ` | Strings |
293 | `IntOption` | Integers. `IntOption` takes an optional `allow_negative` parameter if you want to allow negative integers. |
294 | `BoolOption` | Booleans. Valid values: `true`, `false`. Case-insensitive. |
295 | `ListOption` | List of strings. Comma separated. |
296 | `PathOption` | Directory or file path. Takes an optional `type` parameter for specifying path type (`file`, `dir` (=default) or `both`). |
297 | `RegexOption` | String representing a [Python-style regex](https://docs.python.org/library/re.html) - compiled and validated before rules are applied. |
298
299 !!! note
300 Gitlint currently does not support options for all possible types (e.g. float, list of int, etc).
301 [We could use a hand getting those implemented](contributing.md)!
302
303
304 ## Configuration Rules
305
306 _Introduced in gitlint v0.14.0_
307
308 Configuration rules are special rules that are applied once per commit and *BEFORE* any other rules are run.
309 Configuration rules are meant to dynamically change gitlint's configuration and/or the commit that is about to be
310 linted.
311 A typically use-case for this is when you want to modifying gitlint's behavior for all rules against a commit matching
312 specific circumstances.
313
314 !!! warning
315 Configuration rules can drastically change the way gitlint behaves and are typically only needed for more advanced
316 use-cases. We recommend you double check:
317
318 1. Whether gitlint already supports your use-case out-of-the-box (special call-out for [ignore rules](rules.md#i1-ignore-by-title) which allow you to ignore (parts) of your commit message).
319 2. Whether there's a [Contrib Rule](contrib_rules.md) that implements your use-case.
320 3. Whether you can implement your use-case using a regular Commit or Line user-defined rule (see above).
321
322
323 As with other user-defined rules, the easiest way to get started is by copying [`my_configuration.py` from the examples directory](https://github.com/jorisroovers/gitlint/tree/main/examples/my_configuration_rules.py) and modifying it to fit your need.
324
325 ```python
326 # -*- coding: utf-8 -*-
327 from gitlint.rules import ConfigurationRule
328 from gitlint.options import IntOption
329
330 class ReleaseConfigurationRule(ConfigurationRule):
331 """
332 This rule will modify gitlint's behavior for Release Commits.
333
334 This example might not be the most realistic for a real-world scenario,
335 but is meant to give an overview of what's possible.
336 """
337
338 # A rule MUST have a human friendly name
339 name = "release-configuration-rule"
340
341 # A rule MUST have a *unique* id, we recommend starting with UCR
342 # (for User-defined Configuration-Rule), but this can really be anything.
343 id = "UCR1"
344
345 # A rule MAY have an option_spec if its behavior should be configurable.
346 options_spec = [IntOption('custom-verbosity', 2, "Gitlint verbosity for release commits")]
347
348 def apply(self, config, commit):
349 self.log.debug("ReleaseConfigurationRule: This will be visible when running `gitlint --debug`")
350
351 # If the commit title starts with 'Release', we want to modify
352 # how all subsequent rules interpret that commit
353 if commit.message.title.startswith("Release"):
354
355 # If your Release commit messages are auto-generated, the
356 # body might contain trailing whitespace. Let's ignore that
357 config.ignore.append("body-trailing-whitespace")
358
359 # Similarly, the body lines might exceed 80 chars,
360 # let's set gitlint's limit to 200
361 # To set rule options use:
362 # config.set_rule_option(<rule-name>, <rule-option>, <value>)
363 config.set_rule_option("body-max-line-length", "line-length", 200)
364
365 # For kicks, let's set gitlint's verbosity to 2
366 # To set general options use
367 # config.set_general_option(<general-option>, <value>)
368 config.set_general_option("verbosity", 2)
369 # We can also use custom options to make this configurable
370 config.set_general_option("verbosity", self.options['custom-verbosity'].value)
371
372 # Strip any lines starting with $ from the commit message
373 # (this only affects how gitlint sees your commit message, it does
374 # NOT modify your actual commit in git)
375 commit.message.body = [line for line in commit.message.body if not line.startswith("$")]
376
377 # You can add any extra properties you want to the commit object,
378 # these will be available later on in all rules.
379 commit.my_property = "This is my property"
380 ```
381
382 For all available properties and methods on the `config` object, have a look at the
383 [LintConfig class](https://github.com/jorisroovers/gitlint/blob/main/gitlint-core/gitlint/config.py). Please do not use any
384 properties or methods starting with an underscore, as those are subject to change.
385
386
387 ## Rule requirements
388
389 As long as you stick with simple rules that are similar to the sample user-defined rules (see the
390 [examples](https://github.com/jorisroovers/gitlint/blob/main/examples/my_commit_rules.py) directory), gitlint
391 should be able to discover and execute them. While clearly you can run any python code you want in your rules,
392 you might run into some issues if you don't follow the conventions that gitlint requires.
393
394 While the [rule finding source-code](https://github.com/jorisroovers/gitlint/blob/main/gitlint-core/gitlint/rule_finder.py) is the
395 ultimate source of truth, here are some of the requirements that gitlint enforces.
396
397 ### Rule class requirements
398
399 - Rules **must** extend from `LineRule`, `CommitRule` or `ConfigurationRule`
400 - Rule classes **must** have `id` and `name` string attributes. The `options_spec` is optional,
401 but if set, it **must** be a list of gitlint Options.
402 - `CommitRule` and `LineRule` classes **must** have a `validate` method.
403 - In case of a `CommitRule`, `validate` **must** take a single `commit` parameter.
404 - In case of `LineRule`, `validate` **must** take `line` and `commit` as first and second parameters.
405 - `ConfigurationRule` classes **must** have an `apply` method that take `config` and `commit` as first and second parameters.
406 - LineRule classes **must** have a `target` class attributes that is set to either `CommitMessageTitle` or `CommitMessageBody`.
407 - User Rule id's **cannot** start with `R`, `T`, `B`, `M` or `I` as these rule ids are reserved for gitlint itself.
408 - Rules **should** have a case-insensitive unique id as only one rule can exist with a given id. While gitlint does not
409 enforce this, having multiple rules with the same id might lead to unexpected or undeterministic behavior.
410
411 ### extra-path requirements
412 - If `extra-path` is a directory, it does **not** need to be a proper python package, i.e. it doesn't require an `__init__.py` file.
413 - Python files containing user-defined rules must have a `.py` extension. Files with a different extension will be ignored.
414 - The `extra-path` will be searched non-recursively, i.e. all rule classes must be present at the top level `extra-path` directory.
415 - User rule classes must be defined in the modules that are part of `extra-path`, rules that are imported from outside the `extra-path` will be ignored.