Skip to content

Commit 56ea296

Browse files
authored
Ruff: additional style enforcement (#407)
Enable additional styling rules for ruff and fix related violations.
1 parent 5dc7a58 commit 56ea296

20 files changed

+118
-144
lines changed

docs/index.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,8 @@ useful throughout the years.
3030
- **User-defined rules:** Want to do more then what gitlint offers out of the box? Write your own [user defined rules](user_defined_rules.md).
3131
- **Full unicode support:** Lint your Russian, Chinese or Emoji commit messages with ease!
3232
- **Production-ready:** Gitlint checks a lot of the boxes you're looking for: actively maintained, high unit test coverage, integration tests,
33-
python code standards (pep8, pylint), good documentation, widely used, proven track record.
33+
python code standards ([black](https://github.com/psf/black), [ruff](https://github.com/charliermarsh/ruff)),
34+
good documentation, widely used, proven track record.
3435

3536
## Getting Started
3637
### Installation

gitlint-core/gitlint/cli.py

Lines changed: 17 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,6 @@
4242
class GitLintUsageError(GitlintError):
4343
"""Exception indicating there is an issue with how gitlint is used."""
4444

45-
pass
46-
4745

4846
def setup_logging():
4947
"""Setup gitlint logging"""
@@ -247,40 +245,40 @@ def __init__(self, config, config_builder, commit_hash, refspec, msg_filename, g
247245

248246

249247
# fmt: off
250-
@click.group(invoke_without_command=True, context_settings={'max_content_width': 120},
248+
@click.group(invoke_without_command=True, context_settings={"max_content_width": 120},
251249
epilog="When no COMMAND is specified, gitlint defaults to 'gitlint lint'.")
252-
@click.option('--target', envvar='GITLINT_TARGET',
250+
@click.option("--target", envvar="GITLINT_TARGET",
253251
type=click.Path(exists=True, resolve_path=True, file_okay=False, readable=True),
254252
help="Path of the target git repository. [default: current working directory]")
255-
@click.option('-C', '--config', envvar='GITLINT_CONFIG',
253+
@click.option("-C", "--config", envvar="GITLINT_CONFIG",
256254
type=click.Path(exists=True, dir_okay=False, readable=True, resolve_path=True),
257255
help=f"Config file location [default: {DEFAULT_CONFIG_FILE}]")
258-
@click.option('-c', multiple=True,
256+
@click.option("-c", multiple=True,
259257
help="Config flags in format <rule>.<option>=<value> (e.g.: -c T1.line-length=80). " +
260258
"Flag can be used multiple times to set multiple config values.") # pylint: disable=bad-continuation
261-
@click.option('--commit', envvar='GITLINT_COMMIT', default=None, help="Hash (SHA) of specific commit to lint.")
262-
@click.option('--commits', envvar='GITLINT_COMMITS', default=None,
259+
@click.option("--commit", envvar="GITLINT_COMMIT", default=None, help="Hash (SHA) of specific commit to lint.")
260+
@click.option("--commits", envvar="GITLINT_COMMITS", default=None,
263261
help="The range of commits (refspec or comma-separated hashes) to lint. [default: HEAD]")
264-
@click.option('-e', '--extra-path', envvar='GITLINT_EXTRA_PATH',
262+
@click.option("-e", "--extra-path", envvar="GITLINT_EXTRA_PATH",
265263
help="Path to a directory or python module with extra user-defined rules",
266264
type=click.Path(exists=True, resolve_path=True, readable=True))
267-
@click.option('--ignore', envvar='GITLINT_IGNORE', default="", help="Ignore rules (comma-separated by id or name).")
268-
@click.option('--contrib', envvar='GITLINT_CONTRIB', default="",
265+
@click.option("--ignore", envvar="GITLINT_IGNORE", default="", help="Ignore rules (comma-separated by id or name).")
266+
@click.option("--contrib", envvar="GITLINT_CONTRIB", default="",
269267
help="Contrib rules to enable (comma-separated by id or name).")
270-
@click.option('--msg-filename', type=click.File(encoding=gitlint.utils.DEFAULT_ENCODING),
268+
@click.option("--msg-filename", type=click.File(encoding=gitlint.utils.DEFAULT_ENCODING),
271269
help="Path to a file containing a commit-msg.")
272-
@click.option('--ignore-stdin', envvar='GITLINT_IGNORE_STDIN', is_flag=True,
270+
@click.option("--ignore-stdin", envvar="GITLINT_IGNORE_STDIN", is_flag=True,
273271
help="Ignore any stdin data. Useful for running in CI server.")
274-
@click.option('--staged', envvar='GITLINT_STAGED', is_flag=True,
272+
@click.option("--staged", envvar="GITLINT_STAGED", is_flag=True,
275273
help="Attempt smart guesses about meta info (like author name, email, branch, changed files, etc) " +
276274
"for staged commits.")
277-
@click.option('--fail-without-commits', envvar='GITLINT_FAIL_WITHOUT_COMMITS', is_flag=True,
275+
@click.option("--fail-without-commits", envvar="GITLINT_FAIL_WITHOUT_COMMITS", is_flag=True,
278276
help="Hard fail when the target commit range is empty.")
279-
@click.option('-v', '--verbose', envvar='GITLINT_VERBOSITY', count=True, default=0,
280-
help="Verbosity, more v's for more verbose output (e.g.: -v, -vv, -vvv). [default: -vvv]", )
281-
@click.option('-s', '--silent', envvar='GITLINT_SILENT', is_flag=True,
277+
@click.option("-v", "--verbose", envvar="GITLINT_VERBOSITY", count=True, default=0,
278+
help="Verbosity, use multiple times for more verbose output (e.g.: -v, -vv, -vvv). [default: -vvv]", )
279+
@click.option("-s", "--silent", envvar="GITLINT_SILENT", is_flag=True,
282280
help="Silent mode (no output). Takes precedence over -v, -vv, -vvv.")
283-
@click.option('-d', '--debug', envvar='GITLINT_DEBUG', help="Enable debugging output.", is_flag=True)
281+
@click.option("-d", "--debug", envvar="GITLINT_DEBUG", help="Enable debugging output.", is_flag=True)
284282
@click.version_option(version=gitlint.__version__)
285283
@click.pass_context
286284
def cli( # pylint: disable=too-many-arguments

gitlint-core/gitlint/config.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -296,7 +296,7 @@ def set_general_option(self, option_name, option_value):
296296
if not hasattr(self, attr_name) or attr_name[0] == "_":
297297
raise LintConfigError(f"'{option_name}' is not a valid gitlint option")
298298

299-
# else:
299+
# else
300300
setattr(self, attr_name, option_value)
301301

302302
def __eq__(self, other):
@@ -386,7 +386,7 @@ def delete_rules_by_attr(self, attr_name, attr_val):
386386
"""Deletes all rules from the collection that match a given attribute name and value"""
387387
# Create a new list based on _rules.values() because in python 3, values() is a ValuesView as opposed to a list
388388
# This means you can't modify the ValueView while iterating over it.
389-
for rule in [r for r in self._rules.values()]: # pylint: disable=unnecessary-comprehension
389+
for rule in list(self._rules.values()):
390390
if hasattr(rule, attr_name) and (getattr(rule, attr_name) == attr_val):
391391
del self._rules[rule.id]
392392

gitlint-core/gitlint/exception.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,2 @@
11
class GitlintError(Exception):
22
"""Based Exception class for all gitlint exceptions"""
3-
4-
pass

gitlint-core/gitlint/git.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,6 @@
2121
class GitContextError(GitlintError):
2222
"""Exception indicating there is an issue with the git context"""
2323

24-
pass
25-
2624

2725
class GitNotInstalledError(GitContextError):
2826
def __init__(self):

gitlint-core/gitlint/options.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,6 @@ def __init__(self, name, value, description):
3737
@abstractmethod
3838
def set(self, value):
3939
"""Validates and sets the option's value"""
40-
pass # pragma: no cover
4140

4241
def __str__(self):
4342
return f"({self.name}: {self.value} ({self.description}))"

gitlint-core/gitlint/rule_finder.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ def find_rule_classes(extra_path):
5555
importlib.import_module(module)
5656

5757
except Exception as e:
58-
raise rules.UserRuleError(f"Error while importing extra-path module '{module}': {e}")
58+
raise rules.UserRuleError(f"Error while importing extra-path module '{module}': {e}") from e
5959

6060
# Find all rule classes in the module. We do this my inspecting all members of the module and checking
6161
# 1) is it a class, if not, skip
@@ -138,13 +138,13 @@ def assert_valid_rule_class(clazz, rule_type="User-defined"): # pylint: disable
138138
if not hasattr(clazz, "validate") or not inspect.isroutine(clazz.validate):
139139
raise rules.UserRuleError(f"{rule_type} rule class '{clazz.__name__}' must have a 'validate' method")
140140
# Configuration rules must have an `apply` method
141-
elif issubclass(clazz, rules.ConfigurationRule):
141+
elif issubclass(clazz, rules.ConfigurationRule): # noqa: SIM102
142142
if not hasattr(clazz, "apply") or not inspect.isroutine(clazz.apply):
143143
msg = f"{rule_type} Configuration rule class '{clazz.__name__}' must have an 'apply' method"
144144
raise rules.UserRuleError(msg)
145145

146146
# LineRules must have a valid target: rules.CommitMessageTitle or rules.CommitMessageBody
147-
if issubclass(clazz, rules.LineRule):
147+
if issubclass(clazz, rules.LineRule): # noqa: SIM102
148148
if clazz.target not in [rules.CommitMessageTitle, rules.CommitMessageBody]:
149149
msg = (
150150
f"The target attribute of the {rule_type.lower()} LineRule class '{clazz.__name__}' "

gitlint-core/gitlint/rules.py

Lines changed: 1 addition & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -50,40 +50,28 @@ def __str__(self):
5050
class ConfigurationRule(Rule):
5151
"""Class representing rules that can dynamically change the configuration of gitlint during runtime."""
5252

53-
pass
54-
5553

5654
class CommitRule(Rule):
5755
"""Class representing rules that act on an entire commit at once"""
5856

59-
pass
60-
6157

6258
class LineRule(Rule):
6359
"""Class representing rules that act on a line by line basis"""
6460

65-
pass
66-
6761

6862
class LineRuleTarget:
6963
"""Base class for LineRule targets. A LineRuleTarget specifies where a given rule will be applied
7064
(e.g. commit message title, commit message body).
7165
Each LineRule MUST have a target specified."""
7266

73-
pass
74-
7567

7668
class CommitMessageTitle(LineRuleTarget):
7769
"""Target class used for rules that apply to a commit message title"""
7870

79-
pass
80-
8171

8272
class CommitMessageBody(LineRuleTarget):
8373
"""Target class used for rules that apply to a commit message body"""
8474

85-
pass
86-
8775

8876
class RuleViolation:
8977
"""Class representing a violation of a rule. I.e.: When a rule is broken, the rule will instantiate this class
@@ -107,8 +95,6 @@ def __str__(self):
10795
class UserRuleError(GitlintError):
10896
"""Error used to indicate that an error occurred while trying to load a user rule"""
10997

110-
pass
111-
11298

11399
class MaxLineLength(LineRule):
114100
name = "max-line-length"
@@ -319,7 +305,7 @@ def validate(self, commit):
319305
for needs_mentioned_file in self.options["files"].value:
320306
# if a file that we need to look out for is actually changed, then check whether it occurs
321307
# in the commit msg body
322-
if needs_mentioned_file in commit.changed_files:
308+
if needs_mentioned_file in commit.changed_files: # noqa: SIM102
323309
if needs_mentioned_file not in " ".join(commit.message.body):
324310
violation_message = f"Body does not mention changed file '{needs_mentioned_file}'"
325311
violations.append(RuleViolation(self.id, violation_message, None, len(commit.message.body) + 1))

gitlint-core/gitlint/shell.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,6 @@ def shell(cmd):
2727
class CommandNotFound(Exception):
2828
"""Exception indicating a command was not found during execution"""
2929

30-
pass
31-
3230
class ShResult:
3331
"""Result wrapper class. We use this to more easily migrate from using https://amoffat.github.io/sh/ to using
3432
the builtin subprocess module"""
@@ -45,8 +43,6 @@ def __str__(self):
4543
class ErrorReturnCode(ShResult, Exception):
4644
"""ShResult subclass for unexpected results (acts as an exception)."""
4745

48-
pass
49-
5046
def git(*command_parts, **kwargs):
5147
"""Git shell wrapper.
5248
Implemented as separate function here, so we can do a 'sh' style imports:

gitlint-core/gitlint/tests/base.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -173,11 +173,11 @@ def assertRaisesMessage(self, expected_exception, expected_msg): # pylint: disa
173173
exception_msg = str(exc)
174174
if exception_msg != expected_msg:
175175
error = f"Right exception, wrong message:\n got: {exception_msg}\n expected: {expected_msg}"
176-
raise self.fail(error)
176+
raise self.fail(error) from exc
177177
# else: everything is fine, just return
178178
return
179179
except Exception as exc:
180-
raise self.fail(f"Expected '{expected_exception.__name__}' got '{exc.__class__.__name__}'")
180+
raise self.fail(f"Expected '{expected_exception.__name__}' got '{exc.__class__.__name__}'") from exc
181181

182182
# No exception raised while we expected one
183183
raise self.fail(f"Expected to raise {expected_exception.__name__}, didn't get an exception at all")

gitlint-core/gitlint/tests/cli/test_cli.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -218,8 +218,7 @@ def test_lint_commit(self, sh, _):
218218
self.assertEqual(result.exit_code, 2)
219219

220220
@patch("gitlint.cli.get_stdin_data", return_value=False)
221-
@patch("gitlint.git.sh")
222-
def test_lint_commit_negative(self, sh, _):
221+
def test_lint_commit_negative(self, _):
223222
"""Negative test for --commit option"""
224223

225224
# Try using --commit and --commits at the same time (not allowed)

0 commit comments

Comments
 (0)