java 如何通过编程创建GitHub仓库?

b5buobof  于 2022-12-28  发布在  Java
关注(0)|答案(3)|浏览(192)

我必须使用Java编程创建一个GitHub存储库,并将代码推送到它。请建议最佳使用方法。也请分享任何代码片段或实用程序的相关链接。
我提到了jgit库,有人用过吗?我也提到了hub,gh和命令行工具。

2izufjch

2izufjch1#

您可以使用GitHub Rest API。
Settings > Developers Settings > Personal Access Tokens生成个人访问令牌
一旦生成,使用它调用端点-

https://api.github.com/user/repo

带主体

{"name": "REPO_NAME"}

和标题

Authorization: token PERSONAL_ACCESS_TOKEN

curl 示例:

curl -H "Authorization: token PERSONAL_ACCESS TOKEN" https://api.github.com/user/repos -d '{"name": "REPO_NAME"}'

参考文件:https://docs.github.com/en/rest/repos/repos?apiVersion=2022-11-28#create-a-repository-for-the-authenticated-user

x6h2sr28

x6h2sr282#

gitlab4j API是一个很好的库:https://github.com/gitlab4j/gitlab4j-api

<!-- https://mvnrepository.com/artifact/org.gitlab4j/gitlab4j-api -->
    <dependency>
        <groupId>org.gitlab4j</groupId>
        <artifactId>gitlab4j-api</artifactId>
        <version>5.0.1</version>
    </dependency>

我正在使用从repo读取文件、提交和创建合并请求:

try {
        var branchName = "BRANCH-" + random.nextLong();
        var action = new CommitAction();
        action.withContent(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(data))
                .withFilePath(JSON_FILE_PATH).setAction(Action.UPDATE);
        try (var glapi = new GitLabApi(GIT_HOSTNAME, token)) {
            glapi.enableRequestResponseLogging(java.util.logging.Level.INFO);
            glapi.getCommitsApi().createCommit(REPO_NAME, branchName, message, VERSION, null, null, action);
            return glapi.getMergeRequestApi().createMergeRequest(DB_REPO_NAME, branchName, VERSION, message,
                    message, ADMIN_USER_ID);
        }
    } catch (Exception ex) {
        throw new DataException(ex);
    }

如何创建一个新的存储库、一个新的主分支和第一次提交:

try (var glapi = new GitLabApi("https://gitlab.com/", token)) {
            var projectApi = glapi.getProjectApi();
            var project = projectApi.createProject("my-repo");
            // my-repo created
            var action = new CommitAction();
            action.withContent("### ignore some files ###").withFilePath(".gitignore").setAction(Action.CREATE);
            glapi.getCommitsApi().createCommit("my-repo", "master", "my first commit", "master", "author@mail.com",
                    "author", action);
            // yoru first commit 
        }

对于github,您可以使用https://github.com/hub4j/github-api

@Test
public void testCreateRepoPublic() throws Exception {
    initGithubInstance();
    GHUser myself = gitHub.getMyself();
    String repoName = "test-repo-public";
    GHRepository repo = gitHub.createRepository(repoName).private_(false).create();
    try {
        assertThat(repo.isPrivate(), is(false));
        repo.setPrivate(true);
        assertThat(myself.getRepository(repoName).isPrivate(), is(true));
        repo.setPrivate(false);
        assertThat(myself.getRepository(repoName).isPrivate(), is(false));
    } finally {
        repo.delete();
    }
}

提交多个文件:

var repo = github.getRepository("my-repo");
    GHRef mainRef = repo.getRef("heads/master");
    String mainTreeSha = repo.getTreeRecursive("master", 1).getSha();
    GHTreeBuilder treeBuilder = repo.createTree().baseTree(mainTreeSha);
    treeBuilder.add("file1.txt", Files.readAllBytes(Path.of("file1.txt"), false);
    treeBuilder.add("file2.json", Files.readAllBytes(Path.of("file2.json"), false);
    treeBuilder.add("dir1/dir2/file3.xml", Files.readAllBytes(Path.of("dir1/dir2/file3.xml"), false);
  
    String treeSha = treeBuilder.create().getSha();
    GHCommit commit = repo.createCommit()
            .tree(treeSha)
            .message("adding multiple files example")
            .author("author", "author@mail.com", new Date())
            .committer("committer", "committer@mail.com", new Date())
            .parent(mainRef.getObject().getSha())
            .create();
    String commitSha = commit.getSHA1();
    mainRef.updateTo(commitSha);

使用Eclipse jgit

<!-- https://mvnrepository.com/artifact/org.eclipse.jgit/org.eclipse.jgit -->
    <dependency>
        <groupId>org.eclipse.jgit</groupId>
        <artifactId>org.eclipse.jgit</artifactId>
        <version>6.2.0.202206071550-r</version>
    </dependency>

示例:

// to use basic auth
    var credentials = new UsernamePasswordCredentialsProvider("user", "password");

    // to clone a repository
    Git.cloneRepository().setURI("https://github.com/my-repo.git").setCredentialsProvider(credentials).call();

    // to init a new repository
    Git.init().setDirectory(new File("/opt/my-repo")).setInitialBranch("master").call();

    // to use a cloned repo
    var git = Git.open(new File("/opt/my-repo"));

    // to pull changes from remote
    git.pull().setCredentialsProvider(credentials).call();

    // to stage one file
    git.add().setUpdate(true).addFilepattern("dir/file.txt").call();

    // to stage all files in a directory
    git.add().setUpdate(true).addFilepattern("dir").call();

    // to create a commit with the staged files
    git.commit().setMessage("just adding some files.").call();

    // to push changes to remote
    git.push().call();
v440hwme

v440hwme3#

我尝试使用jgit向GitHub repo添加文件。Commit正在创建,但文件没有添加,在addfilepattern中-我也尝试了.“”。下面是我的代码片段:

Git.cloneRepository().setURI("https://github.com/"+org+"/"+repo+".git").setCredentialsProvider(credentialsProvider).setDirectory(new File(Gitpath)).setCloneAllBranches(true).call();

Git.init().setDirectory(new File(Gitpath)).setInitialBranch("main").call();

var git = Git.open(new File(Gitpath));
git.add().setUpdate(true).addFilepattern(directoryName+fileName).call();
git.commit().setMessage("Adding files.").call();
git.push().setCredentialsProvider(credentialsProvider).call();

相关问题