批量导入存储库到GitLab(自托管)

3
我有大约50个git仓库想要导入到GitLab实例中。它们不在GitHub/GitLab/任何地方,只是因为SVN git转换而作为结果存储在我的硬盘上。
有什么好的方法可以将它们全部导入?
我考虑编写一个命令行脚本或Java/Python等小程序,但我不确定是否应该直接使用Gitlab API、使用glab还是是否已经有内置的东西可以使这项任务更容易。

请注意,在GitHub上实现这一点有些困难,但如果您需要使用GitHub的方式,请参见命令行gh命令([tag:github-cli])。由于自动化存储库创建取决于托管站点,因此没有通用的Git答案。 - torek
2个回答

4

您最好使用一个简单的脚本来完成这个任务。好消息是,只要您有足够的权限创建存储库的命名空间,您就可以通过将项目推送到该命名空间来轻松创建项目。

例如,您可以像这样创建一个新项目:

git remote add origin ssh://git@gitlab.example.com/mynamespace/my-newproject.git
git push -u origin --all

您将会看到您的GitLab实例返回以下消息,指示项目已被创建:
remote:
remote: The private project mynamespace/my-newprojct was successfully created.
remote:
remote: To configure the remote, run:
remote:   git remote add origin git@gitlab.example.com:mynamespace/my-newprojct.git
remote:
remote: To view the project, visit:
remote:   https://gitlab.example.com/mynamespace/my-newproject
remote:

假设您有一个有效(最好是无密码)的SSH配置,那么存储库名称可以用作项目标识符(不含空格、特殊字符等),并且包含转换后的存储库的扁平结构,例如:
/path/to/converted/repos
├── my-great-repo1
├── my-great-repo2

在Python中,像这样的代码应该可以正常工作...
import os
import subprocess
from typing import Generator, Tuple

# change these values
GITLAB_NAMESPACE = "gitlab.example.com/mynamespace"
CONVERTED_REPOS_ROOT = "/path/to/converted/repos"


def iter_git_repos(root) -> Generator[Tuple[str, str], None, None]:
    for name in os.listdir(root):
        path = os.path.join(root, name)
        if not os.path.isdir(path):
            continue  # skip files
        git_directory = os.path.join(path, ".git")
        if not os.path.exists(git_directory):
            continue  # skip directories that are not git repos
        yield name, path


for name, path in iter_git_repos(CONVERTED_REPOS_ROOT):
    os.chdir(path)
    origin_url = f"ssh://git@{GITLAB_NAMESPACE}/{name}.git"

    # set the remote (use `set-url` instead of `add` if an origin already exists)
    subprocess.run(["git", "remote", "add", "origin", origin_url], check=True)
    # push all branches
    subprocess.run(["git", "push", "-u", "origin", "--all"], check=True)
    # push all tags
    subprocess.run(["git", "push", "-u", "origin", "--tags"], check=True)

1
最终,我使用gitlab-rake导入了这些代码库:
我将服务器上的代码库复制到一个专门的目录中,将所有权更改为 git 用户和组,并运行以下命令:https://docs.gitlab.com/ee/raketasks/import.html
gitlab-rake gitlab:import:repos["/var/opt/gitlab/git-data/repository-import-$(date "+%Y-%m-%d")"]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接