如何使用 jgit 将现有存储库克隆到新的 github 实例?

How to use jgit to clone the existing repositories to new github instance?

我们有两个单独的 GitHub 实例 运行。一个 GitHub 个实例是 https://github.dev.host.com,另一个 github 个实例是 https://github.host.com。我在 https://github.dev.host.com 中有各种存储库,我需要将其迁移到这个新的 github 实例 https://github.host.com.

我正在使用 JGit,因为我正在使用 Java。例如 - 以下是 https://github.dev.host.com 实例中存在的存储库,我需要将其迁移到新的 github 实例 https://github.host.com

https://github.dev.host.com/Database/ClientService
https://github.dev.host.com/Database/Interest

因为我正在使用 JGit,所以我想通过 Java 代码在我的新 GitHub 实例中创建上述两个存储库。在 运行 我的 Java 代码之后,我应该看到所有上述存储库及其所有分支和内容从我的 https://github.dev.host.com 进入我的新 Github 实例 https://github.host.com 作为显示如下 -

https://github.host.com/Database/ClientService
https://github.host.com/Database/Interest

我只需要迭代我在旧 github 实例中拥有的所有存储库列表,如果它们没有在我的新 github 中包含所有内容和分支退出,则创建它们实例。如果它们已经存在,则覆盖从旧实例到新实例的所有更改。

这可以使用 JGit 来完成吗?我还可以通过我的用户名和密码 https 访问我的两个 github 实例。

到目前为止,我只能做一些基本的事情,如下所示,这是我通过教程学到的。

public class CreateNewRepository {

    public static void main(String[] args) throws IOException {
        // prepare a new folder
        File localPath = File.createTempFile("TestGitRepository", "");
        localPath.delete();

        // create the directory
        Repository repository = FileRepositoryBuilder.create(new File(localPath, ".git"));
        repository.create();

        System.out.println("Having repository: " + repository.getDirectory());

        repository.close();

        FileUtils.deleteDirectory(localPath);
    }
}

任何建议都会有很大帮助,因为这是我第一次使用 JGit。

一个可行的方法是将存储库从 source 服务器克隆到一个临时位置,然后从那里将其推送到 destination服务器。

您可以像这样使用 JGit 克隆存储库:

Git.cloneRepository()
  .setCredentialsProvider( new UsernamePasswordCredentialsProvider( "user", "password" ) );
  .setURI( remoteRepoUrl )
  .setDirectory( localDirectory )
  .setCloneAllBranches( true )
  .call();

要将刚刚克隆的存储库传输到目的地,您必须先在目标服务器上创建一个存储库。 JGit 和 Git 都不支持这一步。 GitHub 提供了一个 REST API,让您 create repositories. The developer pages 还可以列出可用于此 API 的语言绑定,其中有 Java。

一旦(空)存储库存在,您就可以从临时副本推送到远程:

  Git git = Git.open( localDirectory );
  git.push()
    .setCredentialsProvider( new UsernamePasswordCredentialsProvider( "user",  "password" ) );
    .setRemote( newRemoteRepoUrl )
    .setForce( true )
    .setPushAll()
    .setPushTags()
    .call()

可以找到有关身份验证的更多信息here

请注意,如果源存储库包含标签,则必须在克隆后将这些标签单独提取到临时存储库中。