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

时间:2019-07-06 08:54:21

标签: python gitlab

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

我当前正在使用python-gitlab软件包,我认为它仅支持files.create,后者使用提供的字符串内容创建一个新文件。就我而言,这将导致文件内容略有不同。

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

1 个答案:

答案 0 :(得分:2)

Dec. 2013 0.5 version of gitlab/python-gitlab确实提到:

  

项目:添加用于创建/更新/删除文件的方法(commit 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

May 2016, for the 0.13 version中,不推荐使用file_*方法,而是使用文件管理器。

warnings.warn("`update_file` is deprecated, "
                      "use `files.update()` instead",
                      DeprecationWarning)

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')
  

我正在寻找的是将“现有本地文件”推送到空的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'})

您可以通过以下方式check the differences在GitLab上创建(并克隆)的文件与您自己的本地文件之间

git diff --no-index --color --ws-error-highlight=new,old

我在2015 for better whitespace detection中提到了它。

OP Linightz确认in the comments

  

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

     

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