2

I am looking at the eclipse jgit library. It should be able to do both SSH and HTTPS connections and need either to be fed an ssh session or user credentials each time doing push, clone, etc. But I don't know a proper way of doing it when using method chaining.

if (isSSH(repository)) {
        call = git
            .push()
            .setTransportConfigCallback(transport -> {
                SshTransport sshTransport = (SshTransport) transport;
                sshTransport.setSshSessionFactory(getSshSession(repository));
            })
            .setPushAll()
            .call();
}
else {
        call = git
            .push()
            .setCredentialsProvider(prepareCredentialsProvider(repository))
            .setPushAll()
            .call();
}

Is it possible to simplify it by either making it conditional or making a custom "prepareConnection" method to replace the setTransportConfigCallback and setCredentialsProvider?

Both setTransportConfigCallback and setCredentialsProvider are in a this class:

public abstract class TransportCommand<C extends GitCommand, T> extends
        GitCommand<T> {
    public C setTransportConfigCallback(
            final TransportConfigCallback transportConfigCallback) {
        this.transportConfigCallback = transportConfigCallback;
        return self();
    }

    public C setCredentialsProvider(
            final CredentialsProvider credentialsProvider) {
        this.credentialsProvider = credentialsProvider;
        return self();
    }
    ...

EDIT

My solution so far is to add this method:

private GitCommand prepareConnection(TransportCommand cmd, Repository repository) {

    if (isSSH(repository))
        return cmd.setTransportConfigCallback(transport -> {
            SshTransport sshTransport = (SshTransport) transport;
            sshTransport.setSshSessionFactory(getSshSession(repository));
        });
    else
        return cmd.setCredentialsProvider(prepareCredentialsProvider(repository));
}

It can be used like this:

Iterable<PushResult> call = ((PushCommand) prepareConnection(git.push(), repository))
                    .setPushAll()
                    .call();
2
  • 1
    Imo it doesn't look that bad. I suppose you could try extracting the duplicate parts outside of the if/else? Commented Feb 19, 2020 at 8:51
  • Here is an alteranative approach you could consider: stackoverflow.com/a/74492221/511804 Commented Nov 18, 2022 at 15:54

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.