Skip to content

Commit 0414bf7

Browse files
committed
Replace extra occurrences of str with fspath
1 parent 91d4cc5 commit 0414bf7

File tree

14 files changed

+68
-70
lines changed

14 files changed

+68
-70
lines changed

git/config.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -578,7 +578,7 @@ def _included_paths(self) -> List[Tuple[str, str]]:
578578
value,
579579
)
580580
if self._repo.git_dir:
581-
if fnmatch.fnmatchcase(str(self._repo.git_dir), value):
581+
if fnmatch.fnmatchcase(os.fspath(self._repo.git_dir), value):
582582
paths += self.items(section)
583583

584584
elif keyword == "onbranch":

git/index/base.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -404,10 +404,10 @@ def _iter_expand_paths(self: "IndexFile", paths: Sequence[PathLike]) -> Iterator
404404
def raise_exc(e: Exception) -> NoReturn:
405405
raise e
406406

407-
r = str(self.repo.working_tree_dir)
407+
r = os.fspath(self.repo.working_tree_dir)
408408
rs = r + os.sep
409409
for path in paths:
410-
abs_path = str(path)
410+
abs_path = os.fspath(path)
411411
if not osp.isabs(abs_path):
412412
abs_path = osp.join(r, path)
413413
# END make absolute path
@@ -434,7 +434,7 @@ def raise_exc(e: Exception) -> NoReturn:
434434
# characters.
435435
if abs_path not in resolved_paths:
436436
for f in self._iter_expand_paths(glob.glob(abs_path)):
437-
yield str(f).replace(rs, "")
437+
yield os.fspath(f).replace(rs, "")
438438
continue
439439
# END glob handling
440440
try:
@@ -569,7 +569,7 @@ def resolve_blobs(self, iter_blobs: Iterator[Blob]) -> "IndexFile":
569569
for blob in iter_blobs:
570570
stage_null_key = (blob.path, 0)
571571
if stage_null_key in self.entries:
572-
raise ValueError("Path %r already exists at stage 0" % str(blob.path))
572+
raise ValueError("Path %r already exists at stage 0" % os.fspath(blob.path))
573573
# END assert blob is not stage 0 already
574574

575575
# Delete all possible stages.
@@ -656,10 +656,10 @@ def _to_relative_path(self, path: PathLike) -> PathLike:
656656
return path
657657
if self.repo.bare:
658658
raise InvalidGitRepositoryError("require non-bare repository")
659-
if not osp.normpath(str(path)).startswith(str(self.repo.working_tree_dir)):
659+
if not osp.normpath(os.fspath(path)).startswith(os.fspath(self.repo.working_tree_dir)):
660660
raise ValueError("Absolute path %r is not in git repository at %r" % (path, self.repo.working_tree_dir))
661661
result = os.path.relpath(path, self.repo.working_tree_dir)
662-
if str(path).endswith(os.sep) and not result.endswith(os.sep):
662+
if os.fspath(path).endswith(os.sep) and not result.endswith(os.sep):
663663
result += os.sep
664664
return result
665665

@@ -731,7 +731,7 @@ def _entries_for_paths(
731731
for path in paths:
732732
if osp.isabs(path):
733733
abspath = path
734-
gitrelative_path = path[len(str(self.repo.working_tree_dir)) + 1 :]
734+
gitrelative_path = path[len(os.fspath(self.repo.working_tree_dir)) + 1 :]
735735
else:
736736
gitrelative_path = path
737737
if self.repo.working_tree_dir:
@@ -1359,11 +1359,11 @@ def make_exc() -> GitCommandError:
13591359
try:
13601360
self.entries[(co_path, 0)]
13611361
except KeyError:
1362-
folder = str(co_path)
1362+
folder = os.fspath(co_path)
13631363
if not folder.endswith("/"):
13641364
folder += "/"
13651365
for entry in self.entries.values():
1366-
if str(entry.path).startswith(folder):
1366+
if os.fspath(entry.path).startswith(folder):
13671367
p = entry.path
13681368
self._write_path_to_stdin(proc, p, p, make_exc, fprogress, read_from_stdout=False)
13691369
checked_out_files.append(p)

git/index/fun.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ def run_commit_hook(name: str, index: "IndexFile", *args: str) -> None:
8787
return
8888

8989
env = os.environ.copy()
90-
env["GIT_INDEX_FILE"] = safe_decode(str(index.path))
90+
env["GIT_INDEX_FILE"] = safe_decode(os.fspath(index.path))
9191
env["GIT_EDITOR"] = ":"
9292
cmd = [hp]
9393
try:
@@ -167,7 +167,7 @@ def write_cache(
167167
beginoffset = tell()
168168
write(entry.ctime_bytes) # ctime
169169
write(entry.mtime_bytes) # mtime
170-
path_str = str(entry.path)
170+
path_str = os.fspath(entry.path)
171171
path: bytes = force_bytes(path_str, encoding=defenc)
172172
plen = len(path) & CE_NAMEMASK # Path length
173173
assert plen == len(path), "Path %s too long to fit into index" % entry.path

git/index/util.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ def git_working_dir(func: Callable[..., _T]) -> Callable[..., _T]:
106106
@wraps(func)
107107
def set_git_working_dir(self: "IndexFile", *args: Any, **kwargs: Any) -> _T:
108108
cur_wd = os.getcwd()
109-
os.chdir(str(self.repo.working_tree_dir))
109+
os.chdir(os.fspath(self.repo.working_tree_dir))
110110
try:
111111
return func(self, *args, **kwargs)
112112
finally:

git/objects/blob.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
__all__ = ["Blob"]
77

88
from mimetypes import guess_type
9+
import os
910
import sys
1011

1112
if sys.version_info >= (3, 8):
@@ -44,5 +45,5 @@ def mime_type(self) -> str:
4445
"""
4546
guesses = None
4647
if self.path:
47-
guesses = guess_type(str(self.path))
48+
guesses = guess_type(os.fspath(self.path))
4849
return guesses and guesses[0] or self.DEFAULT_MIME_TYPE

git/objects/submodule/base.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -352,7 +352,7 @@ def _clone_repo(
352352
module_abspath_dir = osp.dirname(module_abspath)
353353
if not osp.isdir(module_abspath_dir):
354354
os.makedirs(module_abspath_dir)
355-
module_checkout_path = osp.join(str(repo.working_tree_dir), path)
355+
module_checkout_path = osp.join(os.fspath(repo.working_tree_dir), path)
356356

357357
if url.startswith("../"):
358358
remote_name = repo.active_branch.tracking_branch().remote_name
@@ -541,7 +541,7 @@ def add(
541541
if sm.exists():
542542
# Reretrieve submodule from tree.
543543
try:
544-
sm = repo.head.commit.tree[str(path)]
544+
sm = repo.head.commit.tree[os.fspath(path)]
545545
sm._name = name
546546
return sm
547547
except KeyError:
@@ -1016,7 +1016,7 @@ def move(self, module_path: PathLike, configuration: bool = True, module: bool =
10161016
return self
10171017
# END handle no change
10181018

1019-
module_checkout_abspath = join_path_native(str(self.repo.working_tree_dir), module_checkout_path)
1019+
module_checkout_abspath = join_path_native(os.fspath(self.repo.working_tree_dir), module_checkout_path)
10201020
if osp.isfile(module_checkout_abspath):
10211021
raise ValueError("Cannot move repository onto a file: %s" % module_checkout_abspath)
10221022
# END handle target files
@@ -1313,7 +1313,7 @@ def set_parent_commit(self, commit: Union[Commit_ish, str, None], check: bool =
13131313
# If check is False, we might see a parent-commit that doesn't even contain the
13141314
# submodule anymore. in that case, mark our sha as being NULL.
13151315
try:
1316-
self.binsha = pctree[str(self.path)].binsha
1316+
self.binsha = pctree[os.fspath(self.path)].binsha
13171317
except KeyError:
13181318
self.binsha = self.NULL_BIN_SHA
13191319

@@ -1395,7 +1395,7 @@ def rename(self, new_name: str) -> "Submodule":
13951395
destination_module_abspath = self._module_abspath(self.repo, self.path, new_name)
13961396
source_dir = mod.git_dir
13971397
# Let's be sure the submodule name is not so obviously tied to a directory.
1398-
if str(destination_module_abspath).startswith(str(mod.git_dir)):
1398+
if os.fspath(destination_module_abspath).startswith(os.fspath(mod.git_dir)):
13991399
tmp_dir = self._module_abspath(self.repo, self.path, str(uuid.uuid4()))
14001400
os.renames(source_dir, tmp_dir)
14011401
source_dir = tmp_dir

git/refs/reference.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
__all__ = ["Reference"]
55

6+
import os
67
from git.util import IterableObj, LazyMixin
78

89
from .symbolic import SymbolicReference, T_References
@@ -65,7 +66,7 @@ def __init__(self, repo: "Repo", path: PathLike, check_path: bool = True) -> Non
6566
If ``False``, you can provide any path.
6667
Otherwise the path must start with the default path prefix of this type.
6768
"""
68-
if check_path and not str(path).startswith(self._common_path_default + "/"):
69+
if check_path and not os.fspath(path).startswith(self._common_path_default + "/"):
6970
raise ValueError(f"Cannot instantiate {self.__class__.__name__!r} from path {path}")
7071
self.path: str # SymbolicReference converts to string at the moment.
7172
super().__init__(repo, path)

git/refs/symbolic.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ def __init__(self, repo: "Repo", path: PathLike, check_path: bool = False) -> No
7979
self.path = path
8080

8181
def __str__(self) -> str:
82-
return str(self.path)
82+
return os.fspath(self.path)
8383

8484
def __repr__(self) -> str:
8585
return '<git.%s "%s">' % (self.__class__.__name__, self.path)
@@ -103,7 +103,7 @@ def name(self) -> str:
103103
In case of symbolic references, the shortest assumable name is the path
104104
itself.
105105
"""
106-
return str(self.path)
106+
return os.fspath(self.path)
107107

108108
@property
109109
def abspath(self) -> PathLike:
@@ -178,7 +178,7 @@ def _check_ref_name_valid(ref_path: PathLike) -> None:
178178
"""
179179
previous: Union[str, None] = None
180180
one_before_previous: Union[str, None] = None
181-
for c in str(ref_path):
181+
for c in os.fspath(ref_path):
182182
if c in " ~^:?*[\\":
183183
raise ValueError(
184184
f"Invalid reference '{ref_path}': references cannot contain spaces, tildes (~), carets (^),"
@@ -212,7 +212,7 @@ def _check_ref_name_valid(ref_path: PathLike) -> None:
212212
raise ValueError(f"Invalid reference '{ref_path}': references cannot end with a forward slash (/)")
213213
elif previous == "@" and one_before_previous is None:
214214
raise ValueError(f"Invalid reference '{ref_path}': references cannot be '@'")
215-
elif any(component.endswith(".lock") for component in str(ref_path).split("/")):
215+
elif any(component.endswith(".lock") for component in os.fspath(ref_path).split("/")):
216216
raise ValueError(
217217
f"Invalid reference '{ref_path}': references cannot have slash-separated components that end with"
218218
" '.lock'"
@@ -235,7 +235,7 @@ def _get_ref_info_helper(
235235
tokens: Union[None, List[str], Tuple[str, str]] = None
236236
repodir = _git_dir(repo, ref_path)
237237
try:
238-
with open(os.path.join(repodir, str(ref_path)), "rt", encoding="UTF-8") as fp:
238+
with open(os.path.join(repodir, os.fspath(ref_path)), "rt", encoding="UTF-8") as fp:
239239
value = fp.read().rstrip()
240240
# Don't only split on spaces, but on whitespace, which allows to parse lines like:
241241
# 60b64ef992065e2600bfef6187a97f92398a9144 branch 'master' of git-server:/path/to/repo
@@ -614,7 +614,7 @@ def to_full_path(cls, path: Union[PathLike, "SymbolicReference"]) -> PathLike:
614614
full_ref_path = path
615615
if not cls._common_path_default:
616616
return full_ref_path
617-
if not str(path).startswith(cls._common_path_default + "/"):
617+
if not os.fspath(path).startswith(cls._common_path_default + "/"):
618618
full_ref_path = "%s/%s" % (cls._common_path_default, path)
619619
return full_ref_path
620620

@@ -706,7 +706,7 @@ def _create(
706706
if not force and os.path.isfile(abs_ref_path):
707707
target_data = str(target)
708708
if isinstance(target, SymbolicReference):
709-
target_data = str(target.path)
709+
target_data = os.fspath(target.path)
710710
if not resolve:
711711
target_data = "ref: " + target_data
712712
with open(abs_ref_path, "rb") as fd:
@@ -842,7 +842,7 @@ def _iter_items(
842842

843843
# Read packed refs.
844844
for _sha, rela_path in cls._iter_packed_refs(repo):
845-
if rela_path.startswith(str(common_path)):
845+
if rela_path.startswith(os.fspath(common_path)):
846846
rela_paths.add(rela_path)
847847
# END relative path matches common path
848848
# END packed refs reading
@@ -931,4 +931,4 @@ def from_path(cls: Type[T_References], repo: "Repo", path: PathLike) -> T_Refere
931931

932932
def is_remote(self) -> bool:
933933
""":return: True if this symbolic reference points to a remote branch"""
934-
return str(self.path).startswith(self._remote_common_path_default + "/")
934+
return os.fspath(self.path).startswith(self._remote_common_path_default + "/")

git/repo/base.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -554,7 +554,7 @@ def tag(self, path: PathLike) -> TagReference:
554554

555555
@staticmethod
556556
def _to_full_tag_path(path: PathLike) -> str:
557-
path_str = str(path)
557+
path_str = os.fspath(path)
558558
if path_str.startswith(TagReference._common_path_default + "/"):
559559
return path_str
560560
if path_str.startswith(TagReference._common_default + "/"):
@@ -959,7 +959,7 @@ def is_dirty(
959959
if not submodules:
960960
default_args.append("--ignore-submodules")
961961
if path:
962-
default_args.extend(["--", str(path)])
962+
default_args.extend(["--", os.fspath(path)])
963963
if index:
964964
# diff index against HEAD.
965965
if osp.isfile(self.index.path) and len(self.git.diff("--cached", *default_args)):

git/util.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -272,9 +272,9 @@ def stream_copy(source: BinaryIO, destination: BinaryIO, chunk_size: int = 512 *
272272
def join_path(a: PathLike, *p: PathLike) -> PathLike:
273273
R"""Join path tokens together similar to osp.join, but always use ``/`` instead of
274274
possibly ``\`` on Windows."""
275-
path = str(a)
275+
path = os.fspath(a)
276276
for b in p:
277-
b = str(b)
277+
b = os.fspath(b)
278278
if not b:
279279
continue
280280
if b.startswith("/"):
@@ -290,18 +290,18 @@ def join_path(a: PathLike, *p: PathLike) -> PathLike:
290290
if sys.platform == "win32":
291291

292292
def to_native_path_windows(path: PathLike) -> PathLike:
293-
path = str(path)
293+
path = os.fspath(path)
294294
return path.replace("/", "\\")
295295

296296
def to_native_path_linux(path: PathLike) -> str:
297-
path = str(path)
297+
path = os.fspath(path)
298298
return path.replace("\\", "/")
299299

300300
to_native_path = to_native_path_windows
301301
else:
302302
# No need for any work on Linux.
303303
def to_native_path_linux(path: PathLike) -> str:
304-
return str(path)
304+
return os.fspath(path)
305305

306306
to_native_path = to_native_path_linux
307307

@@ -372,7 +372,7 @@ def is_exec(fpath: str) -> bool:
372372
progs = []
373373
if not path:
374374
path = os.environ["PATH"]
375-
for folder in str(path).split(os.pathsep):
375+
for folder in os.fspath(path).split(os.pathsep):
376376
folder = folder.strip('"')
377377
if folder:
378378
exe_path = osp.join(folder, program)
@@ -397,7 +397,7 @@ def _cygexpath(drive: Optional[str], path: str) -> str:
397397
p = cygpath(p)
398398
elif drive:
399399
p = "/proc/cygdrive/%s/%s" % (drive.lower(), p)
400-
p_str = str(p) # ensure it is a str and not AnyPath
400+
p_str = os.fspath(p) # ensure it is a str and not AnyPath
401401
return p_str.replace("\\", "/")
402402

403403

@@ -418,7 +418,7 @@ def _cygexpath(drive: Optional[str], path: str) -> str:
418418

419419
def cygpath(path: str) -> str:
420420
"""Use :meth:`git.cmd.Git.polish_url` instead, that works on any environment."""
421-
path = str(path) # Ensure is str and not AnyPath.
421+
path = os.fspath(path) # Ensure is str and not AnyPath.
422422
# Fix to use Paths when 3.5 dropped. Or to be just str if only for URLs?
423423
if not path.startswith(("/cygdrive", "//", "/proc/cygdrive")):
424424
for regex, parser, recurse in _cygpath_parsers:
@@ -438,7 +438,7 @@ def cygpath(path: str) -> str:
438438

439439

440440
def decygpath(path: PathLike) -> str:
441-
path = str(path)
441+
path = os.fspath(path)
442442
m = _decygpath_regex.match(path)
443443
if m:
444444
drive, rest_path = m.groups()
@@ -497,7 +497,7 @@ def is_cygwin_git(git_executable: Union[None, PathLike]) -> bool:
497497
elif git_executable is None:
498498
return False
499499
else:
500-
return _is_cygwin_git(str(git_executable))
500+
return _is_cygwin_git(os.fspath(git_executable))
501501

502502

503503
def get_user_id() -> str:

0 commit comments

Comments
 (0)