如何使用 python 将现有文件推送到 gitlab 存储库

Lin*_*htz 5 python gitlab

有没有办法像git commitgit push命令一样将现有文件推送到 python 中的 gitlab 项目存储库,而不是创建新文件?

我目前正在使用python-gitlab包,我认为它只支持files.create使用提供的字符串内容创建新文件。在我的例子中,这会导致文件内容略有不同。

我正在寻找一种方法将 python 中的文件原封不动地推送到存储库中,任何人都可以帮忙吗?

Von*_*onC 4

2013 年12月 0.5 版本的 gitlab/python-gitlab确实提到了:

项目:添加创建/更新/删除文件的方法(提交 ba39e88

因此应该有一种方法来更新现有文件,而不是创建新文件。

def update_file(self, path, branch, content, message):
    url = "/projects/%s/repository/files" % self.id
    url += "?file_path=%s&branch_name=%s&content=%s&commit_message=%s" % \
        (path, branch, content, message)
    r = self.gitlab.rawPut(url)
    if r.status_code != 200:
        raise GitlabUpdateError
Run Code Online (Sandbox Code Playgroud)

2016 年5月,对于 0.13 版本,这些file_*方法已被弃用,取而代之的是文件管理器。

warnings.warn("`update_file` is deprecated, "
                      "use `files.update()` instead",
                      DeprecationWarning)
Run Code Online (Sandbox Code Playgroud)

这已记录在0.15, Aug. 2016中。
docs/gl_objects/projects.rst

更新一个文件。
必须以纯文本或 base64 编码文本的形式上传整个内容:

f.content = 'new content'
f.save(branch='master', commit_message='Update testfile')

# or for binary data
# Note: decode() is required with python 3 for data serialization. You can omit
# it with python 2
f.content = base64.b64encode(open('image.png').read()).decode()
f.save(branch='master', commit_message='Update testfile', encoding='base64')
Run Code Online (Sandbox Code Playgroud)

我正在寻找的是将“现有本地文件”推送到空的 GitLab 项目存储库

要创建新文件:

f = project.files.create({'file_path': 'testfile.txt',
                          'branch': 'master',
                          'content': file_content,
                          'author_email': 'test@example.com',
                          'author_name': 'yourname',
                          'encoding': 'text',
                          'commit_message': 'Create testfile'})
Run Code Online (Sandbox Code Playgroud)

您可以使用以下命令检查在 GitLab 上创建(和克隆)的文件与您自己的本地文件之间的差异

git diff --no-index --color --ws-error-highlight=new,old
Run Code Online (Sandbox Code Playgroud)

我在2015 年提到过它是为了更好的空白检测

OP Linightz在评论中 确认:

创建后的文件python-gitlab在每一行结尾处都缺少一个空格(0x0D)。
所以我想你是对的。
但是,我尝试添加core.autocrlf设置或newline=''在文件打开语句中添加或以二进制方式读取并使用不同的编码进行解码,但以上均不起作用。

我决定只使用 python 中的 shell 命令来推送文件以避免所有这些麻烦,t