【问题标题】:How to create a new branch, push a text file and send merge request to a gitlab repository using Python?如何使用 Python 创建新分支、推送文本文件并将合并请求发送到 gitlab 存储库?
【发布时间】:2022-01-18 21:18:43
【问题描述】:

我发现 https://github.com/python-gitlab/python-gitlab,但是我无法理解文档中的示例。

【问题讨论】:

    标签: python gitlab


    【解决方案1】:

    查看python-gitlab,我没有看到您要查找的某些内容。在这种情况下,我建议您将其拆分并使用更基本的工具和库来执行各个步骤。

    前两部分不需要使用 Gitlab API 来做。您基本上可以使用 Python 使用 git.exe 并针对您的磁盘执行克隆、分支、编辑和提交调用。在某些方面,这更容易,因为您可以自己复制呼叫。你可以使用GitPython

    我建议您通过其中一种方法来执行此操作,而不是尝试通过 Gitlab API 执行此操作。如果您在本地(甚至在 CI 内部)进行分支工作,则更容易理解、调试和调查。

    将代码推送到分支后,您可以使用 Gitlab 的 API 通过 REST(例如 requests 库)创建合并请求。创建 MR 的描述位于 https://docs.gitlab.com/ee/api/merge_requests.html#create-mr,并且大部分字段都是可选的,因此最小值如下所示:

    {
      "id": "some-user%2Fsome-project",
      "source_branch": "name_of_your_mr_branch",
      "target_branch": "main",
      "title": "Automated Merge Request..."
    }
    

    这是一个authenticated POST 调用(创建)。在这些链接之间,您应该拥有执行此操作所需的大部分内容。

    【讨论】:

      【解决方案2】:

      没错,我们在文档中找不到任何测试。这是您问题的基本答案。

      如果您想要一个完整的工作脚本,我已将其附在此处: https://github.com/gitshashwat/general_purpose_scripts/blob/main/usecase_gitlab_python.py

      分解以下步骤:

      为您创建一个 authkey:按照此处的步骤操作:https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html

      为你的项目创建一个 gitlab 服务器实例

      server = gitlab.Gitlab('https://gitlab.example.com', private_token=YOUR_API_TOKEN)
      project = server.projects.get(PROJECT_ID)
      

      使用以下方法创建分支:

      branch = project.branches.create(
          {"branch": branch_name, "ref": project.default_branch}
      )
      

      使用以下方式上传文件:

      project.files.create(
          {
              "file_path": file_name,
              "branch": branch.name,
              "content": "data to be written",
              "encoding": "text",  # or 'base64'; useful for binary files
              "author_email": AUTHOR_EMAIL, # Optional
              "author_name": AUTHOR_NAME,  # Optional
              "commit_message": "Create file",
          }
      )
      

      使用以下命令创建合并请求:

      project.mergerequests.create(
          {
              "source_branch": branch.name,
              "target_branch": project.default_branch,
              "title": "merge request title",
          }
      )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-11-29
        • 1970-01-01
        • 2017-01-10
        • 1970-01-01
        • 2021-10-21
        • 2016-04-23
        • 2020-08-07
        相关资源
        最近更新 更多