Search code examples
javagitlabgitlab-api

How to create a merge request using Gitlab4J?


I made some changes to my project and commited them using JGit, I'm wokring on Gitlab! Usually when we do this manually, Gitlab generates a popup at the top of the repository that requests for the creation of a merge request. I used Gitlab4J for cloning my repositories and I noticed that there's also an API for the merge requests, does anyone knows how to use it?


Solution

  • I figured out how to do it, here's the code snippet:

    GITLAB.getMergeRequestApi().createMergeRequest(
                    projectIdOrPath, 
                    sourceBranch, 
                    targetBranch, 
                    title, 
                    description, 
                    assigneeId)
    

    If you want to recover the projectIdOrPath using your local repository you can add this code snippet that uses JGit and Gitlab4J ProjectApi:

    private Project getProject(Git localRepo) throws GitLabApiException {
       return GITLAB.getProjectApi().getProjects().parallelStream()
          .filter(p -> p.getHttpUrlToRepo()
          .equals(localRepo.getRepository().getConfig().getString("remote", "origin", "url")))
          .findAny().orElse(null);
    }
    

    And for the assigneeId you can get it using this code snippet which uses the approver's username:

    GITLAB.getUserApi().getUser(approver).getId()