Skip to content

Commit cbde921

Browse files
authored
Merge pull request #1 from daobook/sourcery/xin
Sourcery refactored xin branch
2 parents 60850fb + a1eddff commit cbde921

33 files changed

+512
-713
lines changed

git/cmd.py

Lines changed: 65 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -292,28 +292,32 @@ def refresh(cls, path: Union[None, PathLike] = None) -> bool:
292292
# revert to whatever the old_git was
293293
cls.GIT_PYTHON_GIT_EXECUTABLE = old_git
294294

295-
if old_git is None:
296-
# on the first refresh (when GIT_PYTHON_GIT_EXECUTABLE is
297-
# None) we only are quiet, warn, or error depending on the
298-
# GIT_PYTHON_REFRESH value
299-
300-
# determine what the user wants to happen during the initial
301-
# refresh we expect GIT_PYTHON_REFRESH to either be unset or
302-
# be one of the following values:
303-
# 0|q|quiet|s|silence
304-
# 1|w|warn|warning
305-
# 2|r|raise|e|error
306-
307-
mode = os.environ.get(cls._refresh_env_var, "raise").lower()
308-
309-
quiet = ["quiet", "q", "silence", "s", "none", "n", "0"]
310-
warn = ["warn", "w", "warning", "1"]
311-
error = ["error", "e", "raise", "r", "2"]
312-
313-
if mode in quiet:
314-
pass
315-
elif mode in warn or mode in error:
316-
err = dedent("""\
295+
if old_git is not None:
296+
# after the first refresh (when GIT_PYTHON_GIT_EXECUTABLE
297+
# is no longer None) we raise an exception
298+
raise GitCommandNotFound("git", err)
299+
300+
# on the first refresh (when GIT_PYTHON_GIT_EXECUTABLE is
301+
# None) we only are quiet, warn, or error depending on the
302+
# GIT_PYTHON_REFRESH value
303+
304+
# determine what the user wants to happen during the initial
305+
# refresh we expect GIT_PYTHON_REFRESH to either be unset or
306+
# be one of the following values:
307+
# 0|q|quiet|s|silence
308+
# 1|w|warn|warning
309+
# 2|r|raise|e|error
310+
311+
mode = os.environ.get(cls._refresh_env_var, "raise").lower()
312+
313+
quiet = ["quiet", "q", "silence", "s", "none", "n", "0"]
314+
warn = ["warn", "w", "warning", "1"]
315+
error = ["error", "e", "raise", "r", "2"]
316+
317+
if mode in quiet:
318+
pass
319+
elif mode in warn or mode in error:
320+
err = dedent("""\
317321
%s
318322
All git commands will error until this is rectified.
319323
@@ -326,43 +330,38 @@ def refresh(cls, path: Union[None, PathLike] = None) -> bool:
326330
Example:
327331
export %s=%s
328332
""") % (
329-
err,
330-
cls._refresh_env_var,
331-
"|".join(quiet),
332-
"|".join(warn),
333-
"|".join(error),
334-
cls._refresh_env_var,
335-
quiet[0])
336-
337-
if mode in warn:
338-
print("WARNING: %s" % err)
339-
else:
340-
raise ImportError(err)
333+
err,
334+
cls._refresh_env_var,
335+
"|".join(quiet),
336+
"|".join(warn),
337+
"|".join(error),
338+
cls._refresh_env_var,
339+
quiet[0])
340+
341+
if mode in warn:
342+
print("WARNING: %s" % err)
341343
else:
342-
err = dedent("""\
344+
raise ImportError(err)
345+
else:
346+
err = dedent("""\
343347
%s environment variable has been set but it has been set with an invalid value.
344348
345349
Use only the following values:
346350
- %s: for no warning or exception
347351
- %s: for a printed warning
348352
- %s: for a raised exception
349353
""") % (
350-
cls._refresh_env_var,
351-
"|".join(quiet),
352-
"|".join(warn),
353-
"|".join(error))
354-
raise ImportError(err)
355-
356-
# we get here if this was the init refresh and the refresh mode
357-
# was not error, go ahead and set the GIT_PYTHON_GIT_EXECUTABLE
358-
# such that we discern the difference between a first import
359-
# and a second import
360-
cls.GIT_PYTHON_GIT_EXECUTABLE = cls.git_exec_name
361-
else:
362-
# after the first refresh (when GIT_PYTHON_GIT_EXECUTABLE
363-
# is no longer None) we raise an exception
364-
raise GitCommandNotFound("git", err)
365-
354+
cls._refresh_env_var,
355+
"|".join(quiet),
356+
"|".join(warn),
357+
"|".join(error))
358+
raise ImportError(err)
359+
360+
# we get here if this was the init refresh and the refresh mode
361+
# was not error, go ahead and set the GIT_PYTHON_GIT_EXECUTABLE
362+
# such that we discern the difference between a first import
363+
# and a second import
364+
cls.GIT_PYTHON_GIT_EXECUTABLE = cls.git_exec_name
366365
return has_git
367366

368367
@classmethod
@@ -485,12 +484,11 @@ def wait(self, stderr: Union[None, str, bytes] = b'') -> int:
485484
p_stderr = None
486485

487486
def read_all_from_possibly_closed_stream(stream: Union[IO[bytes], None]) -> bytes:
488-
if stream:
489-
try:
490-
return stderr_b + force_bytes(stream.read())
491-
except ValueError:
492-
return stderr_b or b''
493-
else:
487+
if not stream:
488+
return stderr_b or b''
489+
try:
490+
return stderr_b + force_bytes(stream.read())
491+
except ValueError:
494492
return stderr_b or b''
495493

496494
# END status handling
@@ -529,12 +527,7 @@ def read(self, size: int = -1) -> bytes:
529527
bytes_left = self._size - self._nbr
530528
if bytes_left == 0:
531529
return b''
532-
if size > -1:
533-
# assure we don't try to read past our limit
534-
size = min(bytes_left, size)
535-
else:
536-
# they try to read all, make sure its not more than what remains
537-
size = bytes_left
530+
size = min(bytes_left, size) if size > -1 else bytes_left
538531
# END check early depletion
539532
data = self._stream.read(size)
540533
self._nbr += len(data)
@@ -551,10 +544,7 @@ def readline(self, size: int = -1) -> bytes:
551544

552545
# clamp size to lowest allowed value
553546
bytes_left = self._size - self._nbr
554-
if size > -1:
555-
size = min(bytes_left, size)
556-
else:
557-
size = bytes_left
547+
size = min(bytes_left, size) if size > -1 else bytes_left
558548
# END handle size
559549

560550
data = self._stream.readline(size)
@@ -602,8 +592,7 @@ def next(self) -> bytes:
602592
return line
603593

604594
def __del__(self) -> None:
605-
bytes_left = self._size - self._nbr
606-
if bytes_left:
595+
if bytes_left := self._size - self._nbr:
607596
# read and discard - seeking is impossible within a stream
608597
# includes terminating newline
609598
self._stream.read(bytes_left + 1)
@@ -1040,19 +1029,13 @@ def custom_environment(self, **kwargs: Any) -> Iterator[None]:
10401029
self.update_environment(**old_env)
10411030

10421031
def transform_kwarg(self, name: str, value: Any, split_single_char_options: bool) -> List[str]:
1043-
if len(name) == 1:
1044-
if value is True:
1045-
return ["-%s" % name]
1046-
elif value not in (False, None):
1047-
if split_single_char_options:
1048-
return ["-%s" % name, "%s" % value]
1049-
else:
1050-
return ["-%s%s" % (name, value)]
1051-
else:
1052-
if value is True:
1053-
return ["--%s" % dashify(name)]
1054-
elif value is not False and value is not None:
1055-
return ["--%s=%s" % (dashify(name), value)]
1032+
if value is True:
1033+
return ["-%s" % name] if len(name) == 1 else ["--%s" % dashify(name)]
1034+
elif value not in (False, None):
1035+
if split_single_char_options:
1036+
return ["-%s" % name, "%s" % value]
1037+
else:
1038+
return ["-%s%s" % (name, value)]
10561039
return []
10571040

10581041
def transform_kwargs(self, split_single_char_options: bool = True, **kwargs: Any) -> List[str]:

git/config.py

Lines changed: 22 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -92,10 +92,7 @@ def __new__(cls, name: str, bases: Tuple, clsdict: Dict[str, Any]) -> 'MetaParse
9292
clsdict[name] = method_with_values
9393
# END for each name/method pair
9494
# END for each base
95-
# END if mutating methods configuration is set
96-
97-
new_type = super(MetaParserBuilder, cls).__new__(cls, name, bases, clsdict)
98-
return new_type
95+
return super(MetaParserBuilder, cls).__new__(cls, name, bases, clsdict)
9996

10097

10198
def needs_values(func: Callable[..., _T]) -> Callable[..., _T]:
@@ -311,16 +308,15 @@ def __init__(self, file_or_files: Union[None, PathLike, 'BytesIO', Sequence[Unio
311308

312309
if file_or_files is not None:
313310
self._file_or_files: Union[PathLike, 'BytesIO', Sequence[Union[PathLike, 'BytesIO']]] = file_or_files
314-
else:
315-
if config_level is None:
316-
if read_only:
317-
self._file_or_files = [get_config_path(cast(Lit_config_levels, f))
318-
for f in CONFIG_LEVELS
319-
if f != 'repository']
320-
else:
321-
raise ValueError("No configuration level or configuration files specified")
311+
elif config_level is None:
312+
if read_only:
313+
self._file_or_files = [get_config_path(cast(Lit_config_levels, f))
314+
for f in CONFIG_LEVELS
315+
if f != 'repository']
322316
else:
323-
self._file_or_files = [get_config_path(config_level)]
317+
raise ValueError("No configuration level or configuration files specified")
318+
else:
319+
self._file_or_files = [get_config_path(config_level)]
324320

325321
self._read_only = read_only
326322
self._dirty = False
@@ -371,15 +367,14 @@ def release(self) -> None:
371367
return
372368

373369
try:
374-
try:
375-
self.write()
376-
except IOError:
377-
log.error("Exception during destruction of GitConfigParser", exc_info=True)
378-
except ReferenceError:
379-
# This happens in PY3 ... and usually means that some state cannot be written
380-
# as the sections dict cannot be iterated
381-
# Usually when shutting down the interpreter, don'y know how to fix this
382-
pass
370+
self.write()
371+
except IOError:
372+
log.error("Exception during destruction of GitConfigParser", exc_info=True)
373+
except ReferenceError:
374+
# This happens in PY3 ... and usually means that some state cannot be written
375+
# as the sections dict cannot be iterated
376+
# Usually when shutting down the interpreter, don'y know how to fix this
377+
pass
383378
finally:
384379
if self._lock is not None:
385380
self._lock._release_lock()
@@ -510,7 +505,7 @@ def _included_paths(self) -> List[Tuple[str, str]]:
510505
value = osp.expanduser(value)
511506

512507
if not any(value.startswith(s) for s in ["./", "/"]):
513-
value = "**/" + value
508+
value = f'**/{value}'
514509
if value.endswith("/"):
515510
value += "**"
516511

@@ -524,9 +519,10 @@ def _included_paths(self) -> List[Tuple[str, str]]:
524519
),
525520
value
526521
)
527-
if self._repo.git_dir:
528-
if fnmatch.fnmatchcase(str(self._repo.git_dir), value):
529-
paths += self.items(section)
522+
if self._repo.git_dir and fnmatch.fnmatchcase(
523+
str(self._repo.git_dir), value
524+
):
525+
paths += self.items(section)
530526

531527
elif keyword == "onbranch":
532528
try:

git/diff.py

Lines changed: 11 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -125,17 +125,16 @@ def diff(self, other: Union[Type['Index'], 'Tree', 'Commit', None, str, object]
125125
:note:
126126
On a bare repository, 'other' needs to be provided as Index or as
127127
as Tree/Commit, or a git command error will occur"""
128-
args: List[Union[PathLike, Diffable, Type['Diffable.Index'], object]] = []
129-
args.append("--abbrev=40") # we need full shas
130-
args.append("--full-index") # get full index paths, not only filenames
128+
args: List[Union[PathLike, Diffable, Type['Diffable.Index'], object]] = [
129+
'--abbrev=40',
130+
'--full-index',
131+
'-M',
132+
]
131133

132-
args.append("-M") # check for renames, in both formats
133134
if create_patch:
134135
args.append("-p")
135136
else:
136-
args.append("--raw")
137-
args.append("-z")
138-
137+
args.extend(("--raw", "-z"))
139138
# in any way, assure we don't see colored output,
140139
# fixes https://github.com/gitpython-developers/GitPython/issues/172
141140
args.append('--no-color')
@@ -339,11 +338,9 @@ def __init__(self, repo: 'Repo',
339338
self.score = score
340339

341340
def __eq__(self, other: object) -> bool:
342-
for name in self.__slots__:
343-
if getattr(self, name) != getattr(other, name):
344-
return False
345-
# END for each name
346-
return True
341+
return all(
342+
getattr(self, name) == getattr(other, name) for name in self.__slots__
343+
)
347344

348345
def __ne__(self, other: object) -> bool:
349346
return not (self == other)
@@ -362,10 +359,7 @@ def __str__(self) -> str:
362359
line = None # temp line
363360
line_length = 0 # line length
364361
for b, n in zip((self.a_blob, self.b_blob), ('lhs', 'rhs')):
365-
if b:
366-
line = "\n%s: %o | %s" % (n, b.mode, b.hexsha)
367-
else:
368-
line = "\n%s: None" % n
362+
line = "\n%s: %o | %s" % (n, b.mode, b.hexsha) if b else "\n%s: None" % n
369363
# END if blob is not None
370364
line_length = max(len(line), line_length)
371365
msg += line
@@ -392,13 +386,8 @@ def __str__(self) -> str:
392386
msg += 'OMITTED BINARY DATA'
393387
# end handle encoding
394388
msg += '\n---'
395-
# END diff info
396-
397-
# Python2 silliness: have to assure we convert our likely to be unicode object to a string with the
398-
# right encoding. Otherwise it tries to convert it using ascii, which may fail ungracefully
399-
res = h + msg
400389
# end
401-
return res
390+
return h + msg
402391

403392
@ property
404393
def a_path(self) -> Optional[str]:
@@ -549,9 +538,6 @@ def _handle_diff_line(lines_bytes: bytes, repo: 'Repo', index: DiffIndex) -> Non
549538
a_path = a_path_str.encode(defenc)
550539
b_path = b_path_str.encode(defenc)
551540
rename_from, rename_to = a_path, b_path
552-
elif change_type == 'T':
553-
# Nothing to do
554-
pass
555541
# END add/remove handling
556542

557543
diff = Diff(repo, a_path, b_path, a_blob_id, b_blob_id, old_mode, new_mode,

0 commit comments

Comments
 (0)