如何使用 python 从 git 存储库下载单个文件

问题描述 投票:0回答:5

我想使用 python 从我的 git 存储库下载单个文件。

目前我正在使用

gitpython
lib。 Git clone 可以正常使用以下代码,但我不想下载整个目录。

import os
from git import Repo
git_url = '[email protected]:/home2/git/stack.git'
repo_dir = '/root/gitrepo/'
if __name__ == "__main__":
    Repo.clone_from(git_url, repo_dir, branch='master', bare=True)
    print("OK")
python python-3.x git gitpython
5个回答
4
投票

不要将 Git 存储库视为文件的集合,而是快照的集合。 Git 不允许您选择要下载的文件,但允许您选择要下载的快照数量:

git clone [email protected]:/home2/git/stack.git

将下载所有文件的所有快照,而

git clone --depth 1 [email protected]:/home2/git/stack.git

只会下载所有文件的最新快照。您仍然会下载所有文件,但至少会保留所有历史记录。

在这些文件中,你可以简单地选择一个你想要的,然后删除其余的:

import os
import git
import shutil
import tempfile

# Create temporary dir
t = tempfile.mkdtemp()
# Clone into temporary dir
git.Repo.clone_from('[email protected]:/home2/git/stack.git', t, branch='master', depth=1)
# Copy desired file from temporary dir
shutil.move(os.path.join(t, 'setup.py'), '.')
# Remove temporary dir
shutil.rmtree(t)

3
投票

你也可以在python中使用

subprocess

import subprocess

args = ['git', 'clone', '--depth=1', '[email protected]:/home2/git/stack.git']
res = subprocess.Popen(args, stdout=subprocess.PIPE)
output, _error = res.communicate()

if not _error:
    print(output)
else:
    print(_error)

但是,您的主要问题仍然存在。

Git 不支持下载部分存储库。你必须下载所有这些。但是你应该可以用 GitHub 做到这一点。 参考


0
投票

您需要索取文件的原始版本!你可以从 raw.github.com 得到它


0
投票

我不想将其标记为直接重复,因为它没有完全反映这个问题的范围,但根据 this SO post,路西法在他的回答中所说的部分内容似乎是可行的。简而言之,git 不允许部分下载,但某些提供商(如 GitHub)可以通过原始内容进行下载。
话虽这么说,Python 确实提供了许多不同的库供下载,最著名的是 urllib.request.


0
投票

您可以使用此功能从特定分支下载单个文件内容。此代码仅使用

requests
库。

def download_single_file(
    repo_owner: str,
    repo_name: str,
    access_token: str,
    file_path: str,
    branch: str = "main",
    destination_path: str = None,
):
    if destination_path is None:
        destination_path = "./" + file_path

    url = f"https://api.github.com/repos/{repo_owner}/{repo_name}/contents/{file_path}?ref={branch}"

    # Set the headers with the access token and API version
    headers = {
        "Accept": "application/vnd.github+json",
        "Authorization": f"Bearer {access_token}",
    }

    # Send a GET request to the API endpoint
    response = requests.get(url, headers=headers)

    # Check if the request was successful
    if response.status_code == 200:
        # Get the content data from the response
        content_data = response.json()

        # Extract the content and decode it from base64
        content_base64 = content_data.get("content")
        content_bytes = base64.b64decode(content_base64)
        content = content_bytes.decode("utf-8")

        # Set the local destination path

        # Save the file content to the local destination path
        with open(destination_path, "w") as file:
            file.write(content)

        print("File downloaded successfully.")
    else:
        print(
            "Request failed. Check the repository owner, repository name, access token, and API version."
        )
    ```
© www.soinside.com 2019 - 2024. All rights reserved.