使用 gitpython 模块,我正在编写 python 脚本来一一检查所有修改文件的 git diff --> git add 。最后我想提交所有这些更改,但我没有找到该命令的确切语法。
我正在尝试使用下面的代码,“git add”工作完美,但“git commit”给出错误。
import git
repo = git.Repo(os.getcwd())
files = repo.git.diff(None, name_only=True)
for f in files.split('\n'):
show_diff(f)
repo.git.add(f)
repo.git.commit('test commit', author='[email protected]')
这是我看到的错误,cmd 参数中似乎缺少一些东西。
In [10]: repo.git.commit("test commit", author="[email protected]")
---------------------------------------------------------------------------
GitCommandError Traceback (most recent call last)
<ipython-input-10-b4505b7c53c2> in <module>()
----> 1 repo.git.commit("test commit", author="[email protected]")
c:\python27\lib\site-packages\git\cmd.pyc in <lambda>(*args, **kwargs)
421 if name[0] == '_':
422 return LazyMixin.__getattr__(self, name)
--> 423 return lambda *args, **kwargs: self._call_process(name, *args, **kwargs)
424
425 def set_persistent_git_options(self, **kwargs):
c:\python27\lib\site-packages\git\cmd.pyc in _call_process(self, method, *args, **kwargs)
866 call.extend(args)
867
--> 868 return self.execute(call, **_kwargs)
869
870 def _parse_object_header(self, header_line):
c:\python27\lib\site-packages\git\cmd.pyc in execute(self, command, istream, with_extended_output, with_exceptions, as_process, output_stream, stdout_as_string, kill_after_timeout, with_stdout, universal_newlines, shell, **subprocess_kwargs)
684
685 if with_exceptions and status != 0:
--> 686 raise GitCommandError(command, status, stderr_value, stdout_value)
687
688 if isinstance(stdout_value, bytes) and stdout_as_string: # could also be output_stream
GitCommandError: Cmd('git') failed due to: exit code(1)
cmdline: git commit [email protected] test commit
stderr: 'error: pathspec 'test commit' did not match any file(s) known to git.'
解决了这个问题,需要在commit命令中添加“-m”标志,如下:
repo.git.commit('-m', 'test commit', author='[email protected]')
您还可以使用
repo.index
:
repo.index.add(relative_path)
repo.index.commit("message")
参见 https://gitpython.readthedocs.io/en/stable/quickstart.html#add-file-to-staging-area