Search code examples
javagitgitlabpushrepo

Pushing a file to existing GitLab repo using Java?


I would like to know if there is a way to push a file using java, to an existing repository on GitLab.

Suppose, my java source code produces an output file (say a configuration file like config.xml or gitlab-ci.yml). I want to push only this file to a remote repository on GitLab. Is this possible? I guess using JGit is the solution. But, I have no idea how to use it, to push to an existing repo without creating a new repo.

Side Note: To give clarity to my question, the scenario I am facing is, I have a code that generates a yaml file which will be used to configure GitLab CI that runs another source code.

Thanks in advance.


Solution

  • Well I can see two ways of solving this issue.

    1) Using simple ProcessBuilder and executing shell commands that will add and push the given file to the repo. It will be executed inside the folder which means that it will be in the scope of the local repository of the project.

    2) Using JGit, in order to to this You would need to set the repository path correctly :

    Repository existingRepo = new FileRepositoryBuilder()
        .setGitDir(new File("[Your project path]"))
        .build();
    

    Then You can use Porcelain API to add and push the file of Your need.

    The only thing You need to consider is the fact that it should be a little easier to provide credentials using Jgit.