Home > Blockchain >  How to programmatically create a GitHub repository?
How to programmatically create a GitHub repository?

Time:12-10

I have to use Java to programmatically create a GitHub repository and push code to it. Please advise on the best method to use. Also please share any code snippet or related links for the utility.

I referred jgit library, has anyone used it? I also referred hub, gh and command line utility.

CodePudding user response:

You can use the GitHub Rest API.

Generate a Personal Access Token from Settings > Developers Settings > Personal Access Tokens

Once generated use that to call the endpoint -

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

with body

{"name": "REPO_NAME"}

and Header

Authorization: token PERSONAL_ACCESS_TOKEN

Example Curl:

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

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

CodePudding user response:

The gitlab4j api is a great library to do so : 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>

I'm using to read files from repo, commit and create merge requests :

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);
    }

how to create a new repo, a new master branch and your first commit :

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", "[email protected]",
                    "author", action);
            // yoru first commit 
        }

for github you can use 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();
    }
}

commiting multiple files :

    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", "[email protected]", new Date())
            .committer("committer", "[email protected]", new Date())
            .parent(mainRef.getObject().getSha())
            .create();
    String commitSha = commit.getSHA1();
    mainRef.updateTo(commitSha);
  • Related