0

我在 python 中使用文件操作创建了一个文本文件。我希望将文件推送到我现有的 GITLAB 存储库。

我已经尝试了下面的代码,我在本地文件夹中获取了创建的文件。

file_path = 'E:\My material\output.txt'
k= 'Fail/Pass'
with open (file_path, 'w+') as text:
    text.write('Test case :' +k)
    text.close() 

通过 python 代码将创建的文本文件移动到 GITLAB 存储库的过程或​​步骤或 file_path 中的任何修改是什么。

4

3 回答 3

0

使用 python gitlab 模块:

我们可以将文件推送到 gitlab,但您需要按照以下步骤操作:

步骤 1)将存储库克隆到本地

步骤 2)将文件添加到克隆存储库

步骤 3)将代码推送到 gitlab

代码:

import gitlab  
import base64
from gitlab import Gitlab
import shutil

callbacks = pygit2.RemoteCallbacks(pygit2.UserPass("Your_private_token", 'x-oauth-basic'))
repoClone = pygit2.clone_repository("https://gitlab.com/group/"+api_name+".git", local_clone_path,checkout_branch=target_branch,callbacks=callbacks)  # clonning the repo to local
shutil.copy(src,dst_clone_repo_path)   #copy your file to the cloned repo
repoClone.remotes.set_url("origin", "https://gitlab.com/group/"+api_name+".git")
index = repoClone.index
index.add_all()
index.write()
tree = index.write_tree()
oid = repoClone.create_commit('refs/heads/'+target_branch, author, commiter, "init commit",tree,[repoClone.head.peel().hex])
remote = repoClone.remotes["origin"]
credentials = pygit2.UserPass("your_private_token", 'x-oauth-basic')  # passing credentials
remote.credentials = credentials
remote.push(['refs/heads/'+target_branch],callbacks=callbacks) # push the code to the gitlab repo
于 2019-07-29T12:38:59.183 回答
0

你的意思是用 Python 执行 Shell 命令吗?假设这个新创建的文件和这个 python 脚本都在与您要提交的远程存储库连接的特定本地 git 存储库下。我们的计划是将所有 bash 命令打包到os.system.

import os 
os.system('git add E:\My material\output.txt; git commit -m "anything"; git push -u origin master')

更新

import os 
os.system('cd /local/repo; mv E:\My material\output.txt .; git add output.txt; git commit -m "anything"; git push -u origin master')
于 2019-07-07T13:45:15.367 回答
0

聚会有点晚了,但是:

使用 gitlab python 库,您可以执行以下操作:


def commit_file(project_id: int, file_path: str, gitlab_url: str, private_token: str, branch: str = "main") -> bool:
    """Commit a file to the repository
    
    Parameters
    ----------
    project_id: int
        the project id to commit into. E.g. 1582
    file_path: str
        the file path to commit. NOTE: expecting a path relative to the
        repo path. This will also be used as the path to commit into.
        If you want to use absolute local path you will also have to 
        pass a parameter for the file relative repo path
    gitlab_url: str
        The gitlab url. E.g. https://gitlab.example.com
    private_token: str
        Private access token. See doc for more details
    branch: str
        The branch you are working in. See note below for more about this
    """
    gl = gitlab.Gitlab(gitlab_url, private_token=private_token)

    try:
        # get the project by the project id
        project = gl.projects.get(project_id)
        
        # read the file contents
        with open(file_path, 'r') as fin:
            content = fin.read()

        file_data = {'file_path': file_path,
                 'branch': branch,
                 'content': content,
                 'author_email': "your@email.com", # don't think this is required
                 'commit_message': 'Created a file'}

        resp = project.files.create(file_data)
        # do something with resp
    except gitlab.exceptions.GitlabGetError as get_error:
        # project does not exists
        print(f"could not find no project with id {project_id}: {get_error}")
        return False
    except gitlab.exceptions.GitlabCreateError as create_error:
        # project does not exists
        print(f"could not create file: {create_error}")
        return False

    return True

示例基于gitlab 项目文件文档python-gitlab 包文档

请注意,如果您想在新分支中创建文件,您还必须提供一个start_branch属性:

file_data = {'file_path': file_path,
                 'branch': your_new_branch,
                 'start_branch': base_branch,
                 'content': content,
                 'author_email': "your@email.com",
                 'commit_message': 'Created a file in new branch'}

另外,如果你不喜欢使用 python-gitlab 包,你可以直接使用 rest api(使用 request 或类似的东西。相关文档在这里

于 2021-04-22T05:42:06.050 回答