Is there a way to checkout code from Bitbucker server (stash) from within Java code

1k views Asked by At

We are maintaining some JavaScript code within BitBucket. We want to be able to checkout JavaScript code from Bitbucket and be able to access the .js file within our Java application.

Is there a way to checkout code using Java. Is there some library available which can do this for us.

For example, when I want to checkout a git repository from git client, I would execute the command git clone https://bitbucketserverhost/PROJECT/repo.git This will create a folder with the repo name in current directory and checkout all the source files in that folder.

Is there a way to do git clone from within Java. Basically I want the Java code to read latest JavaScript files committed by developers within Bitbucket, access it as a file to be able to read its contents and then compare it with some other file.

1

There are 1 answers

0
user55926 On BEST ANSWER

I ended up using Eclipse's jGit library for checking out code from BitBucket in Java. Added the below maven dependency.

<dependency>
    <groupId>org.eclipse.jgit</groupId>
    <artifactId>org.eclipse.jgit</artifactId>
    <version>4.8.0.201706111038-r</version>
</dependency>   

Below line of code can be used to code can be used to create a clone.

import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.CloneCommand;
import org.eclipse.jgit.api.errors.GitAPIException;
import java.io.File;

class Test {
    public static void main(String[] args){
        CloneCommand clone = Git.cloneRepository().setURI(uri).setDirectory(new File(checkoutDir));
        try {
            clone.call();
        } 
        catch (GitAPIException e) {
            System.err.println(e.getMessage());
            e.printStackTrace(System.err);
        }
    }
}

where uri is the git URI of the repository that we use in git clone command. It is important to note that I have not specified my credentials anywhere in the code because the repository was public. If the repo you are trying to clone, is not public, you need to add more code.