Skip to content

Commit e4360ae

Browse files
committed
feat(cmd): add the strip_newline flag
This commit adds the `strip_newline` flag to the `Git.execute` method. When this flag is set to `True`, it will trim the trailing `\n`. The default value is `True` for backward compatibility. Setting it to `False` is helpful for, e.g., the `git show` output, especially with the binary file, as the missing `\n` may invalidate the file.
1 parent 0b33576 commit e4360ae

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

Diff for: git/cmd.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@
5555
execute_kwargs = {'istream', 'with_extended_output',
5656
'with_exceptions', 'as_process', 'stdout_as_string',
5757
'output_stream', 'with_stdout', 'kill_after_timeout',
58-
'universal_newlines', 'shell', 'env', 'max_chunk_size'}
58+
'universal_newlines', 'shell', 'env', 'max_chunk_size', 'strip_newline'}
5959

6060
log = logging.getLogger(__name__)
6161
log.addHandler(logging.NullHandler())
@@ -738,6 +738,7 @@ def execute(self,
738738
shell: Union[None, bool] = None,
739739
env: Union[None, Mapping[str, str]] = None,
740740
max_chunk_size: int = io.DEFAULT_BUFFER_SIZE,
741+
strip_newline: bool = True,
741742
**subprocess_kwargs: Any
742743
) -> Union[str, bytes, Tuple[int, Union[str, bytes], str], AutoInterrupt]:
743744
"""Handles executing the command on the shell and consumes and returns
@@ -810,6 +811,8 @@ def execute(self,
810811
effects on a repository. For example, stale locks in case of git gc could
811812
render the repository incapable of accepting changes until the lock is manually
812813
removed.
814+
:param strip_newline:
815+
Whether to strip the trailing '\n' of the command output.
813816
814817
:return:
815818
* str(output) if extended_output = False (Default)
@@ -944,7 +947,7 @@ def _kill_process(pid: int) -> None:
944947
if not universal_newlines:
945948
stderr_value = stderr_value.encode(defenc)
946949
# strip trailing "\n"
947-
if stdout_value.endswith(newline): # type: ignore
950+
if stdout_value.endswith(newline) and strip_newline: # type: ignore
948951
stdout_value = stdout_value[:-1]
949952
if stderr_value.endswith(newline): # type: ignore
950953
stderr_value = stderr_value[:-1]

Diff for: test/test_repo.py

+10
Original file line numberDiff line numberDiff line change
@@ -1098,3 +1098,13 @@ def test_rebasing(self, rw_dir):
10981098
except GitCommandError:
10991099
pass
11001100
self.assertEqual(r.currently_rebasing_on(), commitSpanish)
1101+
1102+
@with_rw_directory
1103+
def test_do_not_strip_newline(self, rw_dir):
1104+
r = Repo.init(rw_dir)
1105+
fp = osp.join(rw_dir, 'hello.txt')
1106+
with open(fp, 'w') as fs:
1107+
fs.write("hello\n")
1108+
r.git.add(Git.polish_url(fp))
1109+
r.git.commit(message="init")
1110+
self.assertEqual(r.git.show("HEAD:hello.txt", strip_newline=False), 'hello\n')

0 commit comments

Comments
 (0)