summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJoris Roovers <joris.roovers@gmail.com>2021-09-27 13:30:18 +0200
committerJoris Roovers <joris.roovers@gmail.com>2021-09-27 14:52:08 +0200
commitc5fcff0692eb84b7b43cace42e4b0eea799f52c6 (patch)
treeda0269620c081314391c72ca925ce91a87f76b86
parente6afc6b9ce0bdd90c6837b36f416bec2370288dc (diff)
Pylint 2.11.1 code fixes
Code fixes for new issues in pylint 2.11.1.
-rw-r--r--gitlint/cli.py12
-rw-r--r--gitlint/contrib/rules/conventional_commit.py4
-rw-r--r--gitlint/rules.py2
-rw-r--r--gitlint/shell.py8
-rw-r--r--gitlint/tests/rules/test_body_rules.py6
-rw-r--r--gitlint/tests/rules/test_title_rules.py2
-rw-r--r--gitlint/tests/rules/test_user_rules.py6
-rw-r--r--gitlint/tests/test_options.py2
-rw-r--r--qa/base.py10
-rw-r--r--qa/shell.py4
-rw-r--r--qa/test_hooks.py29
-rw-r--r--qa/test_stdin.py8
12 files changed, 47 insertions, 46 deletions
diff --git a/gitlint/cli.py b/gitlint/cli.py
index 45e88e7..0e9cf1a 100644
--- a/gitlint/cli.py
+++ b/gitlint/cli.py
@@ -283,12 +283,12 @@ def lint(ctx):
# ensure that these jobs don't fail if for whatever reason the specified commit range is empty.
# This behavior can be overridden by using the --fail-without-commits flag.
if number_of_commits == 0:
- LOG.debug(u'No commits in range "%s"', refspec)
+ LOG.debug('No commits in range "%s"', refspec)
if lint_config.fail_without_commits:
- raise GitLintUsageError(u'No commits in range "%s"' % refspec)
+ raise GitLintUsageError(f'No commits in range "{refspec}"')
ctx.exit(GITLINT_SUCCESS)
- LOG.debug(u'Linting %d commit(s)', number_of_commits)
+ LOG.debug('Linting %d commit(s)', number_of_commits)
general_config_builder = ctx.obj.config_builder
last_commit = gitcontext.commits[-1]
@@ -312,10 +312,8 @@ def lint(ctx):
if violations:
# Display the commit hash & new lines intelligently
if number_of_commits > 1 and commit.sha:
- linter.display.e("{0}Commit {1}:".format(
- "\n" if not first_violation or commit is last_commit else "",
- commit.sha[:10]
- ))
+ commit_separator = "\n" if not first_violation or commit is last_commit else ""
+ linter.display.e(f"{commit_separator}Commit {commit.sha[:10]}:")
linter.print_violations(violations)
first_violation = False
diff --git a/gitlint/contrib/rules/conventional_commit.py b/gitlint/contrib/rules/conventional_commit.py
index 58cad53..9c9d5cb 100644
--- a/gitlint/contrib/rules/conventional_commit.py
+++ b/gitlint/contrib/rules/conventional_commit.py
@@ -31,7 +31,7 @@ class ConventionalCommit(LineRule):
else:
line_commit_type = match.group(1)
if line_commit_type not in self.options["types"].value:
- msg = "Title does not start with one of {0}".format(', '.join(self.options['types'].value))
- violations.append(RuleViolation(self.id, msg, line))
+ opt_str = ', '.join(self.options['types'].value)
+ violations.append(RuleViolation(self.id, f"Title does not start with one of {opt_str}", line))
return violations
diff --git a/gitlint/rules.py b/gitlint/rules.py
index db21e56..aaafb7c 100644
--- a/gitlint/rules.py
+++ b/gitlint/rules.py
@@ -141,7 +141,7 @@ class LineMustNotContainWord(LineRule):
strings = self.options['words'].value
violations = []
for string in strings:
- regex = re.compile(r"\b%s\b" % string.lower(), re.IGNORECASE | re.UNICODE)
+ regex = re.compile(rf"\b{string.lower()}\b", re.IGNORECASE | re.UNICODE)
match = regex.search(line.lower())
if match:
violations.append(RuleViolation(self.id, self.violation_message.format(string), line))
diff --git a/gitlint/shell.py b/gitlint/shell.py
index 7f598ae..e05204a 100644
--- a/gitlint/shell.py
+++ b/gitlint/shell.py
@@ -11,8 +11,8 @@ from gitlint.utils import USE_SH_LIB, DEFAULT_ENCODING
def shell(cmd):
""" Convenience function that opens a given command in a shell. Does not use 'sh' library. """
- p = subprocess.Popen(cmd, shell=True)
- p.communicate()
+ with subprocess.Popen(cmd, shell=True) as p:
+ p.communicate()
if USE_SH_LIB:
@@ -57,8 +57,8 @@ else:
popen_kwargs['cwd'] = kwargs['_cwd']
try:
- p = subprocess.Popen(args, **popen_kwargs)
- result = p.communicate()
+ with subprocess.Popen(args, **popen_kwargs) as p:
+ result = p.communicate()
except FileNotFoundError as e:
raise CommandNotFound from e
diff --git a/gitlint/tests/rules/test_body_rules.py b/gitlint/tests/rules/test_body_rules.py
index a268585..812c74a 100644
--- a/gitlint/tests/rules/test_body_rules.py
+++ b/gitlint/tests/rules/test_body_rules.py
@@ -101,13 +101,13 @@ class BodyRuleTests(BaseTestCase):
expected_violation = rules.RuleViolation("B5", "Body message is too short (21<120)", "å" * 21, 3)
rule = rules.BodyMinLength({'min-length': 120})
- commit = self.gitcommit("Title\n\n%s\n" % ("å" * 21))
+ commit = self.gitcommit("Title\n\n{0}\n".format("å" * 21)) # pylint: disable=consider-using-f-string
violations = rule.validate(commit)
self.assertListEqual(violations, [expected_violation])
# Make sure we don't get the error if the body-length is exactly the min-length
rule = rules.BodyMinLength({'min-length': 8})
- commit = self.gitcommit("Tïtle\n\n%s\n" % ("å" * 8))
+ commit = self.gitcommit("Tïtle\n\n{0}\n".format("å" * 8)) # pylint: disable=consider-using-f-string
violations = rule.validate(commit)
self.assertIsNone(violations)
@@ -182,7 +182,7 @@ class BodyRuleTests(BaseTestCase):
expected_violation = rules.RuleViolation("B7", "Body does not mention changed file 'föo/test.py'", None, 4)
self.assertEqual([expected_violation], violations)
- # assert multiple errors if multiple files habe changed and are not mentioned
+ # assert multiple errors if multiple files have changed and are not mentioned
commit_msg = "This is å test\n\nHere is a mention of\nAnd here is a mention of"
commit = self.gitcommit(commit_msg, ["föo/test.py", "bar.txt"])
violations = rule.validate(commit)
diff --git a/gitlint/tests/rules/test_title_rules.py b/gitlint/tests/rules/test_title_rules.py
index e1be857..10b4aab 100644
--- a/gitlint/tests/rules/test_title_rules.py
+++ b/gitlint/tests/rules/test_title_rules.py
@@ -79,7 +79,7 @@ class TitleRuleTests(BaseTestCase):
violations = rule.validate("This is å test", None)
self.assertIsNone(violations)
- # no violation if WIP occurs inside a wor
+ # no violation if WIP occurs inside a word
violations = rule.validate("This is å wiping test", None)
self.assertIsNone(violations)
diff --git a/gitlint/tests/rules/test_user_rules.py b/gitlint/tests/rules/test_user_rules.py
index 510a829..5bf9b77 100644
--- a/gitlint/tests/rules/test_user_rules.py
+++ b/gitlint/tests/rules/test_user_rules.py
@@ -97,7 +97,7 @@ class UserRuleTests(BaseTestCase):
def test_assert_valid_rule_class(self):
class MyLineRuleClass(rules.LineRule):
id = 'UC1'
- name = u'my-lïne-rule'
+ name = 'my-lïne-rule'
target = rules.CommitMessageTitle
def validate(self):
@@ -105,14 +105,14 @@ class UserRuleTests(BaseTestCase):
class MyCommitRuleClass(rules.CommitRule):
id = 'UC2'
- name = u'my-cömmit-rule'
+ name = 'my-cömmit-rule'
def validate(self):
pass
class MyConfigurationRuleClass(rules.ConfigurationRule):
id = 'UC3'
- name = u'my-cönfiguration-rule'
+ name = 'my-cönfiguration-rule'
def apply(self):
pass
diff --git a/gitlint/tests/test_options.py b/gitlint/tests/test_options.py
index fc3ccc1..eabcfe1 100644
--- a/gitlint/tests/test_options.py
+++ b/gitlint/tests/test_options.py
@@ -197,7 +197,7 @@ class RuleOptionTests(BaseTestCase):
self.assertEqual(option.value, self.get_sample_path())
# Expect exception if path type is invalid
- option.type = u'föo'
+ option.type = 'föo'
expected = "Option tëst-directory type must be one of: 'file', 'dir', 'both' (current: 'föo')"
with self.assertRaisesMessage(RuleOptionError, expected):
option.set("haha")
diff --git a/qa/base.py b/qa/base.py
index 1f93471..0d844d4 100644
--- a/qa/base.py
+++ b/qa/base.py
@@ -87,6 +87,7 @@ class BaseTestCase(TestCase):
def create_file(parent_dir):
""" Creates a file inside a passed directory. Returns filename."""
test_filename = "test-fïle-" + str(uuid4())
+ # pylint: disable=consider-using-with
io.open(os.path.join(parent_dir, test_filename), 'a', encoding=DEFAULT_ENCODING).close()
return test_filename
@@ -159,11 +160,12 @@ class BaseTestCase(TestCase):
specified by variable_dict. """
expected_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "expected")
expected_path = os.path.join(expected_dir, filename)
- expected = io.open(expected_path, encoding=DEFAULT_ENCODING).read()
+ with io.open(expected_path, encoding=DEFAULT_ENCODING) as file:
+ expected = file.read()
- if variable_dict:
- expected = expected.format(**variable_dict)
- return expected
+ if variable_dict:
+ expected = expected.format(**variable_dict)
+ return expected
@staticmethod
def get_system_info_dict():
diff --git a/qa/shell.py b/qa/shell.py
index 97dcd2c..630843f 100644
--- a/qa/shell.py
+++ b/qa/shell.py
@@ -67,8 +67,8 @@ else:
popen_kwargs['env'] = kwargs['_env']
try:
- p = subprocess.Popen(args, **popen_kwargs)
- result = p.communicate()
+ with subprocess.Popen(args, **popen_kwargs) as p:
+ result = p.communicate()
except FileNotFoundError as exc:
raise CommandNotFound from exc
diff --git a/qa/test_hooks.py b/qa/test_hooks.py
index 32abcb0..ea58699 100644
--- a/qa/test_hooks.py
+++ b/qa/test_hooks.py
@@ -9,9 +9,9 @@ class HookTests(BaseTestCase):
""" Integration tests for gitlint commitmsg hooks"""
VIOLATIONS = ['gitlint: checking commit message...\n',
- u'1: T3 Title has trailing punctuation (.): "WIP: This ïs a title."\n',
- u'1: T5 Title contains the word \'WIP\' (case-insensitive): "WIP: This ïs a title."\n',
- u'2: B4 Second line is not empty: "Contënt on the second line"\n',
+ '1: T3 Title has trailing punctuation (.): "WIP: This ïs a title."\n',
+ '1: T5 Title contains the word \'WIP\' (case-insensitive): "WIP: This ïs a title."\n',
+ '2: B4 Second line is not empty: "Contënt on the second line"\n',
'3: B6 Body message is missing\n',
'-----------------------------------------------\n',
'gitlint: \x1b[31mYour commit message contains violations.\x1b[0m\n']
@@ -28,15 +28,17 @@ class HookTests(BaseTestCase):
# install git commit-msg hook and assert output
output_installed = gitlint("install-hook", _cwd=self.tmp_git_repo)
- expected_installed = "Successfully installed gitlint commit-msg hook in %s/.git/hooks/commit-msg\n" % \
- self.tmp_git_repo
+ expected_installed = ("Successfully installed gitlint commit-msg hook in "
+ f"{self.tmp_git_repo}/.git/hooks/commit-msg\n")
+
self.assertEqualStdout(output_installed, expected_installed)
def tearDown(self):
# uninstall git commit-msg hook and assert output
output_uninstalled = gitlint("uninstall-hook", _cwd=self.tmp_git_repo)
- expected_uninstalled = "Successfully uninstalled gitlint commit-msg hook from %s/.git/hooks/commit-msg\n" % \
- self.tmp_git_repo
+ expected_uninstalled = ("Successfully uninstalled gitlint commit-msg hook from "
+ f"{self.tmp_git_repo}/.git/hooks/commit-msg\n")
+
self.assertEqualStdout(output_uninstalled, expected_uninstalled)
def _violations(self):
@@ -60,9 +62,9 @@ class HookTests(BaseTestCase):
short_hash = self.get_last_commit_short_hash()
expected_output = ["gitlint: checking commit message...\n",
"gitlint: \x1b[32mOK\x1b[0m (no violations in commit message)\n",
- "[master %s] This ïs a title\n" % short_hash,
+ f"[master {short_hash}] This ïs a title\n",
" 1 file changed, 0 insertions(+), 0 deletions(-)\n",
- " create mode 100644 %s\n" % test_filename]
+ f" create mode 100644 {test_filename}\n"]
self.assertListEqual(expected_output, self.githook_output)
def test_commit_hook_continue(self):
@@ -76,10 +78,9 @@ class HookTests(BaseTestCase):
expected_output = self._violations()
expected_output += ["Continue with commit anyways (this keeps the current commit message)? " +
"[y(es)/n(no)/e(dit)] " +
- "[master %s] WIP: This ïs a title. Contënt on the second line\n"
- % short_hash,
+ f"[master {short_hash}] WIP: This ïs a title. Contënt on the second line\n",
" 1 file changed, 0 insertions(+), 0 deletions(-)\n",
- " create mode 100644 %s\n" % test_filename]
+ f" create mode 100644 {test_filename}\n"]
assert len(self.githook_output) == len(expected_output)
for output, expected in zip(self.githook_output, expected_output):
@@ -124,9 +125,9 @@ class HookTests(BaseTestCase):
expected_output += self._violations()[1:]
expected_output += ['Continue with commit anyways (this keeps the current commit message)? ' +
"[y(es)/n(no)/e(dit)] " +
- "[master %s] WIP: This ïs a title. Contënt on the second line\n" % short_hash,
+ f"[master {short_hash}] WIP: This ïs a title. Contënt on the second line\n",
" 1 file changed, 0 insertions(+), 0 deletions(-)\n",
- " create mode 100644 %s\n" % test_filename]
+ f" create mode 100644 {test_filename}\n"]
assert len(self.githook_output) == len(expected_output)
for output, expected in zip(self.githook_output, expected_output):
diff --git a/qa/test_stdin.py b/qa/test_stdin.py
index 18d6e7e..c98580e 100644
--- a/qa/test_stdin.py
+++ b/qa/test_stdin.py
@@ -50,7 +50,7 @@ class StdInTests(BaseTestCase):
# We need to use subprocess.Popen() here instead of sh because when passing a file_handle to sh, it will
# deal with reading the file itself instead of passing it on to gitlint as a STDIN. Since we're trying to
# test for the condition where stat.S_ISREG == True that won't work for us here.
- p = subprocess.Popen("gitlint", stdin=file_handle, cwd=self.tmp_git_repo,
- stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
- output, _ = p.communicate()
- self.assertEqual(output.decode(DEFAULT_ENCODING), self.get_expected("test_stdin/test_stdin_file_1"))
+ with subprocess.Popen("gitlint", stdin=file_handle, cwd=self.tmp_git_repo,
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as p:
+ output, _ = p.communicate()
+ self.assertEqual(output.decode(DEFAULT_ENCODING), self.get_expected("test_stdin/test_stdin_file_1"))