Skip to content

Commit d1c1f31

Browse files
authored
Merge pull request #1673 from EliahKagan/flake8
Upgrade and broaden flake8, fixing style problems and bugs
2 parents a5a6464 + c569320 commit d1c1f31

15 files changed

+64
-79
lines changed

.flake8

+1-1
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ ignore = E265,E266,E731,E704,
2626
D,
2727
RST, RST3
2828

29-
exclude = .tox,.venv,build,dist,doc,git/ext/,test
29+
exclude = .tox,.venv,build,dist,doc,git/ext/
3030

3131
rst-roles = # for flake8-RST-docstrings
3232
attr,class,func,meth,mod,obj,ref,term,var # used by sphinx

.pre-commit-config.yaml

+4-4
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
repos:
22
- repo: https://github.com/PyCQA/flake8
3-
rev: 6.0.0
3+
rev: 6.1.0
44
hooks:
55
- id: flake8
66
additional_dependencies:
77
[
8-
flake8-bugbear==22.12.6,
9-
flake8-comprehensions==3.10.1,
8+
flake8-bugbear==23.9.16,
9+
flake8-comprehensions==3.14.0,
1010
flake8-typing-imports==1.14.0,
1111
]
12-
exclude: ^doc|^git/ext/|^test/
12+
exclude: ^doc|^git/ext/
1313

1414
- repo: https://github.com/pre-commit/pre-commit-hooks
1515
rev: v4.4.0

git/objects/submodule/base.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1403,7 +1403,7 @@ def iter_items(
14031403
# END handle critical error
14041404

14051405
# Make sure we are looking at a submodule object
1406-
if type(sm) != git.objects.submodule.base.Submodule:
1406+
if type(sm) is not git.objects.submodule.base.Submodule:
14071407
continue
14081408

14091409
# fill in remaining info - saves time as it doesn't have to be parsed again

git/refs/log.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -244,7 +244,7 @@ def entry_at(cls, filepath: PathLike, index: int) -> "RefLogEntry":
244244
for i in range(index + 1):
245245
line = fp.readline()
246246
if not line:
247-
raise IndexError(f"Index file ended at line {i+1}, before given index was reached")
247+
raise IndexError(f"Index file ended at line {i + 1}, before given index was reached")
248248
# END abort on eof
249249
# END handle runup
250250

git/repo/base.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -206,7 +206,8 @@ def __init__(
206206
if expand_vars and re.search(self.re_envvars, epath):
207207
warnings.warn(
208208
"The use of environment variables in paths is deprecated"
209-
+ "\nfor security reasons and may be removed in the future!!"
209+
+ "\nfor security reasons and may be removed in the future!!",
210+
stacklevel=1,
210211
)
211212
epath = expand_path(epath, expand_vars)
212213
if epath is not None:

git/util.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1136,7 +1136,7 @@ class IterableClassWatcher(type):
11361136

11371137
def __init__(cls, name: str, bases: Tuple, clsdict: Dict) -> None:
11381138
for base in bases:
1139-
if type(base) == IterableClassWatcher:
1139+
if type(base) is IterableClassWatcher:
11401140
warnings.warn(
11411141
f"GitPython Iterable subclassed by {name}. "
11421142
"Iterable is deprecated due to naming clash since v3.1.18"

test/lib/helper.py

+15-17
Original file line numberDiff line numberDiff line change
@@ -94,17 +94,16 @@ def wrapper(self):
9494
os.mkdir(path)
9595
keep = False
9696
try:
97-
try:
98-
return func(self, path)
99-
except Exception:
100-
log.info(
101-
"Test %s.%s failed, output is at %r\n",
102-
type(self).__name__,
103-
func.__name__,
104-
path,
105-
)
106-
keep = True
107-
raise
97+
return func(self, path)
98+
except Exception:
99+
log.info(
100+
"Test %s.%s failed, output is at %r\n",
101+
type(self).__name__,
102+
func.__name__,
103+
path,
104+
)
105+
keep = True
106+
raise
108107
finally:
109108
# Need to collect here to be sure all handles have been closed. It appears
110109
# a windows-only issue. In fact things should be deleted, as well as
@@ -147,12 +146,11 @@ def repo_creator(self):
147146
prev_cwd = os.getcwd()
148147
os.chdir(rw_repo.working_dir)
149148
try:
150-
try:
151-
return func(self, rw_repo)
152-
except: # noqa E722
153-
log.info("Keeping repo after failure: %s", repo_dir)
154-
repo_dir = None
155-
raise
149+
return func(self, rw_repo)
150+
except: # noqa E722
151+
log.info("Keeping repo after failure: %s", repo_dir)
152+
repo_dir = None
153+
raise
156154
finally:
157155
os.chdir(prev_cwd)
158156
rw_repo.git.clear_cache()

test/test_commit.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -277,7 +277,7 @@ def __init__(self, *args, **kwargs):
277277
super(Child, self).__init__(*args, **kwargs)
278278

279279
child_commits = list(Child.iter_items(self.rorepo, "master", paths=("CHANGES", "AUTHORS")))
280-
assert type(child_commits[0]) == Child
280+
assert type(child_commits[0]) is Child
281281

282282
def test_iter_items(self):
283283
# pretty not allowed
@@ -525,12 +525,12 @@ def test_trailers(self):
525525

526526
# check that trailer stays empty for multiple msg combinations
527527
msgs = [
528-
f"Subject\n",
529-
f"Subject\n\nBody with some\nText\n",
530-
f"Subject\n\nBody with\nText\n\nContinuation but\n doesn't contain colon\n",
531-
f"Subject\n\nBody with\nText\n\nContinuation but\n only contains one :\n",
532-
f"Subject\n\nBody with\nText\n\nKey: Value\nLine without colon\n",
533-
f"Subject\n\nBody with\nText\n\nLine without colon\nKey: Value\n",
528+
"Subject\n",
529+
"Subject\n\nBody with some\nText\n",
530+
"Subject\n\nBody with\nText\n\nContinuation but\n doesn't contain colon\n",
531+
"Subject\n\nBody with\nText\n\nContinuation but\n only contains one :\n",
532+
"Subject\n\nBody with\nText\n\nKey: Value\nLine without colon\n",
533+
"Subject\n\nBody with\nText\n\nLine without colon\nKey: Value\n",
534534
]
535535

536536
for msg in msgs:

test/test_diff.py

-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
import ddt
88
import shutil
99
import tempfile
10-
import unittest
1110
from git import (
1211
Repo,
1312
GitCommandError,

test/test_docs.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -263,9 +263,9 @@ def test_references_and_objects(self, rw_dir):
263263
# [8-test_references_and_objects]
264264
hc = repo.head.commit
265265
hct = hc.tree
266-
hc != hct # @NoEffect
267-
hc != repo.tags[0] # @NoEffect
268-
hc == repo.head.reference.commit # @NoEffect
266+
hc != hct # noqa: B015 # @NoEffect
267+
hc != repo.tags[0] # noqa: B015 # @NoEffect
268+
hc == repo.head.reference.commit # noqa: B015 # @NoEffect
269269
# ![8-test_references_and_objects]
270270

271271
# [9-test_references_and_objects]
@@ -369,7 +369,7 @@ def test_references_and_objects(self, rw_dir):
369369
# The index contains all blobs in a flat list
370370
assert len(list(index.iter_blobs())) == len([o for o in repo.head.commit.tree.traverse() if o.type == "blob"])
371371
# Access blob objects
372-
for (_path, _stage), entry in index.entries.items():
372+
for (_path, _stage), _entry in index.entries.items():
373373
pass
374374
new_file_path = os.path.join(repo.working_tree_dir, "new-file-name")
375375
open(new_file_path, "w").close()

test/test_git.py

+7-12
Original file line numberDiff line numberDiff line change
@@ -195,17 +195,12 @@ def test_version(self):
195195
# END verify number types
196196

197197
def test_cmd_override(self):
198-
prev_cmd = self.git.GIT_PYTHON_GIT_EXECUTABLE
199-
exc = GitCommandNotFound
200-
try:
201-
# set it to something that doesn't exist, assure it raises
202-
type(self.git).GIT_PYTHON_GIT_EXECUTABLE = osp.join(
203-
"some", "path", "which", "doesn't", "exist", "gitbinary"
204-
)
205-
self.assertRaises(exc, self.git.version)
206-
finally:
207-
type(self.git).GIT_PYTHON_GIT_EXECUTABLE = prev_cmd
208-
# END undo adjustment
198+
with mock.patch.object(
199+
type(self.git),
200+
"GIT_PYTHON_GIT_EXECUTABLE",
201+
osp.join("some", "path", "which", "doesn't", "exist", "gitbinary"),
202+
):
203+
self.assertRaises(GitCommandNotFound, self.git.version)
209204

210205
def test_refresh(self):
211206
# test a bad git path refresh
@@ -250,7 +245,7 @@ def test_insert_after_kwarg_raises(self):
250245

251246
def test_env_vars_passed_to_git(self):
252247
editor = "non_existent_editor"
253-
with mock.patch.dict("os.environ", {"GIT_EDITOR": editor}): # @UndefinedVariable
248+
with mock.patch.dict(os.environ, {"GIT_EDITOR": editor}):
254249
self.assertEqual(self.git.var("GIT_EDITOR"), editor)
255250

256251
@with_rw_directory

test/test_quick_doc.py

+6-8
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,3 @@
1-
import pytest
2-
3-
41
from test.lib import TestBase
52
from test.lib.helper import with_rw_directory
63

@@ -25,10 +22,11 @@ def test_init_repo_object(self, path_to_dir):
2522
repo = Repo(path_to_dir)
2623
# ![2-test_init_repo_object]
2724

25+
del repo # Avoids "assigned to but never used" warning. Doesn't go in the docs.
26+
2827
@with_rw_directory
2928
def test_cloned_repo_object(self, local_dir):
3029
from git import Repo
31-
import git
3230

3331
# code to clone from url
3432
# [1-test_cloned_repo_object]
@@ -72,7 +70,7 @@ def test_cloned_repo_object(self, local_dir):
7270

7371
# [6-test_cloned_repo_object]
7472
commits_for_file_generator = repo.iter_commits(all=True, max_count=10, paths=update_file)
75-
commits_for_file = [c for c in commits_for_file_generator]
73+
commits_for_file = list(commits_for_file_generator)
7674
commits_for_file
7775

7876
# Outputs: [<git.Commit "SHA1-HEX_HASH-2">,
@@ -136,7 +134,7 @@ def test_cloned_repo_object(self, local_dir):
136134

137135
# Compare commit to commit
138136
# [11.3-test_cloned_repo_object]
139-
first_commit = [c for c in repo.iter_commits(all=True)][-1]
137+
first_commit = list(repo.iter_commits(all=True))[-1]
140138
diffs = repo.head.commit.diff(first_commit)
141139
for d in diffs:
142140
print(d.a_path)
@@ -154,7 +152,7 @@ def test_cloned_repo_object(self, local_dir):
154152

155153
# Previous commit tree
156154
# [13-test_cloned_repo_object]
157-
prev_commits = [c for c in repo.iter_commits(all=True, max_count=10)] # last 10 commits from all branches
155+
prev_commits = list(repo.iter_commits(all=True, max_count=10)) # last 10 commits from all branches
158156
tree = prev_commits[0].tree
159157
# ![13-test_cloned_repo_object]
160158

@@ -210,7 +208,7 @@ def print_files_from_git(root, level=0):
210208

211209
# print previous tree
212210
# [18.1-test_cloned_repo_object]
213-
commits_for_file = [c for c in repo.iter_commits(all=True, paths=print_file)]
211+
commits_for_file = list(repo.iter_commits(all=True, paths=print_file))
214212
tree = commits_for_file[-1].tree # gets the first commit tree
215213
blob = tree[print_file]
216214

test/test_remote.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ def _do_test_push_result(self, results, remote):
160160
# END error checking
161161
# END for each info
162162

163-
if any([info.flags & info.ERROR for info in results]):
163+
if any(info.flags & info.ERROR for info in results):
164164
self.assertRaises(GitCommandError, results.raise_if_error)
165165
else:
166166
# No errors, so this should do nothing

test/test_repo.py

+9-16
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,8 @@ def test_clone_from_with_path_contains_unicode(self):
252252

253253
@with_rw_directory
254254
@skip(
255-
"the referenced repository was removed, and one needs to setup a new password controlled repo under the orgs control"
255+
"""The referenced repository was removed, and one needs to set up a new
256+
password controlled repo under the org's control."""
256257
)
257258
def test_leaking_password_in_clone_logs(self, rw_dir):
258259
password = "fakepassword1234"
@@ -758,9 +759,9 @@ def test_blame_complex_revision(self, git):
758759

759760
@mock.patch.object(Git, "_call_process")
760761
def test_blame_accepts_rev_opts(self, git):
761-
res = self.rorepo.blame("HEAD", "README.md", rev_opts=["-M", "-C", "-C"])
762762
expected_args = ["blame", "HEAD", "-M", "-C", "-C", "--", "README.md"]
763763
boilerplate_kwargs = {"p": True, "stdout_as_string": False}
764+
self.rorepo.blame("HEAD", "README.md", rev_opts=["-M", "-C", "-C"])
764765
git.assert_called_once_with(*expected_args, **boilerplate_kwargs)
765766

766767
@skipIf(
@@ -846,18 +847,13 @@ def test_comparison_and_hash(self):
846847

847848
@with_rw_directory
848849
def test_tilde_and_env_vars_in_repo_path(self, rw_dir):
849-
ph = os.environ.get("HOME")
850-
try:
850+
with mock.patch.dict(os.environ, {"HOME": rw_dir}):
851851
os.environ["HOME"] = rw_dir
852852
Repo.init(osp.join("~", "test.git"), bare=True)
853853

854+
with mock.patch.dict(os.environ, {"FOO": rw_dir}):
854855
os.environ["FOO"] = rw_dir
855856
Repo.init(osp.join("$FOO", "test.git"), bare=True)
856-
finally:
857-
if ph:
858-
os.environ["HOME"] = ph
859-
del os.environ["FOO"]
860-
# end assure HOME gets reset to what it was
861857

862858
def test_git_cmd(self):
863859
# test CatFileContentStream, just to be very sure we have no fencepost errors
@@ -971,7 +967,7 @@ def _assert_rev_parse(self, name):
971967
# history with number
972968
ni = 11
973969
history = [obj.parents[0]]
974-
for pn in range(ni):
970+
for _ in range(ni):
975971
history.append(history[-1].parents[0])
976972
# END get given amount of commits
977973

@@ -1329,6 +1325,7 @@ def test_git_work_tree_env(self, rw_dir):
13291325
# move .git directory to a subdirectory
13301326
# set GIT_DIR and GIT_WORK_TREE appropriately
13311327
# check that repo.working_tree_dir == rw_dir
1328+
13321329
self.rorepo.clone(join_path_native(rw_dir, "master_repo"))
13331330

13341331
repo_dir = join_path_native(rw_dir, "master_repo")
@@ -1338,16 +1335,12 @@ def test_git_work_tree_env(self, rw_dir):
13381335
os.mkdir(new_subdir)
13391336
os.rename(old_git_dir, new_git_dir)
13401337

1341-
oldenv = os.environ.copy()
1342-
os.environ["GIT_DIR"] = new_git_dir
1343-
os.environ["GIT_WORK_TREE"] = repo_dir
1338+
to_patch = {"GIT_DIR": new_git_dir, "GIT_WORK_TREE": repo_dir}
13441339

1345-
try:
1340+
with mock.patch.dict(os.environ, to_patch):
13461341
r = Repo()
13471342
self.assertEqual(r.working_tree_dir, repo_dir)
13481343
self.assertEqual(r.working_dir, repo_dir)
1349-
finally:
1350-
os.environ = oldenv
13511344

13521345
@with_rw_directory
13531346
def test_rebasing(self, rw_dir):

test/test_submodule.py

+5-4
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ def _do_base_tests(self, rwrepo):
111111

112112
# force it to reread its information
113113
del smold._url
114-
smold.url == sm.url # @NoEffect
114+
smold.url == sm.url # noqa: B015 # @NoEffect
115115

116116
# test config_reader/writer methods
117117
sm.config_reader()
@@ -248,7 +248,7 @@ def _do_base_tests(self, rwrepo):
248248
assert csm.module_exists()
249249

250250
# tracking branch once again
251-
csm.module().head.ref.tracking_branch() is not None # @NoEffect
251+
assert csm.module().head.ref.tracking_branch() is not None
252252

253253
# this flushed in a sub-submodule
254254
assert len(list(rwrepo.iter_submodules())) == 2
@@ -480,8 +480,9 @@ def test_base_bare(self, rwrepo):
480480
File "C:\\projects\\gitpython\\git\\cmd.py", line 559, in execute
481481
raise GitCommandNotFound(command, err)
482482
git.exc.GitCommandNotFound: Cmd('git') not found due to: OSError('[WinError 6] The handle is invalid')
483-
cmdline: git clone -n --shared -v C:\\projects\\gitpython\\.git Users\\appveyor\\AppData\\Local\\Temp\\1\\tmplyp6kr_rnon_bare_test_root_module""",
484-
) # noqa E501
483+
cmdline: git clone -n --shared -v C:\\projects\\gitpython\\.git Users\\appveyor\\AppData\\Local\\Temp\\1\\tmplyp6kr_rnon_bare_test_root_module
484+
""", # noqa E501
485+
)
485486
@with_rw_repo(k_subm_current, bare=False)
486487
def test_root_module(self, rwrepo):
487488
# Can query everything without problems

0 commit comments

Comments
 (0)