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();
Kasper Hansen
  • 6,307
  • 21
  • 70
  • 106
  • 1
    Imo it doesn't look that bad. I suppose you could try extracting the duplicate parts outside of the if/else? – Amongalen Feb 19 '20 at 08:51
  • Here is an alteranative approach you could consider: https://stackoverflow.com/a/74492221/511804 – Alexandr Nov 18 '22 at 15:54

0 Answers0