Example usage for org.eclipse.jgit.api Git fetch

List of usage examples for org.eclipse.jgit.api Git fetch

Introduction

In this page you can find the example usage for org.eclipse.jgit.api Git fetch.

Prototype

public FetchCommand fetch() 

Source Link

Document

Return a command object to execute a Fetch command

Usage

From source file:sh.isaac.provider.sync.git.SyncServiceGIT.java

License:Apache License

/**
 * Link and fetch from remote./*  w ww  . j  a v a2  s.c  om*/
 *
 * @param remoteAddress the remote address
 * @param username the username
 * @param password the password
 * @throws IllegalArgumentException the illegal argument exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws AuthenticationException the authentication exception
 * @see sh.isaac.api.sync.SyncFiles#linkAndFetchFromRemote(java.io.File, java.lang.String, java.lang.String, java.lang.String)
 */
@Override
public void linkAndFetchFromRemote(String remoteAddress, String username, char[] password)
        throws IllegalArgumentException, IOException, AuthenticationException {
    LOG.info("linkAndFetchFromRemote called - folder: {}, remoteAddress: {}, username: {}", this.localFolder,
            remoteAddress, username);

    Repository r = null;
    Git git = null;

    try {
        final File gitFolder = new File(this.localFolder, ".git");

        r = new FileRepository(gitFolder);

        if (!gitFolder.isDirectory()) {
            LOG.debug("Root folder does not contain a .git subfolder.  Creating new git repository.");
            r.create();
        }

        relinkRemote(remoteAddress, username, password);
        git = new Git(r);

        final CredentialsProvider cp = new UsernamePasswordCredentialsProvider(username,
                ((password == null) ? new char[] {} : password));

        LOG.debug("Fetching");

        final FetchResult fr = git.fetch().setCheckFetchedObjects(true).setCredentialsProvider(cp).call();

        LOG.debug("Fetch messages: {}", fr.getMessages());

        boolean remoteHasMaster = false;
        final Collection<Ref> refs = git.lsRemote().setCredentialsProvider(cp).call();

        for (final Ref ref : refs) {
            if ("refs/heads/master".equals(ref.getName())) {
                remoteHasMaster = true;
                LOG.debug("Remote already has 'heads/master'");
                break;
            }
        }

        if (remoteHasMaster) {
            // we need to fetch and (maybe) merge - get onto origin/master.
            LOG.debug("Fetching from remote");

            final String fetchResult = git.fetch().setCredentialsProvider(cp).call().getMessages();

            LOG.debug("Fetch Result: {}", fetchResult);
            LOG.debug("Resetting to origin/master");
            git.reset().setMode(ResetType.MIXED).setRef("origin/master").call();

            // Get the files from master that we didn't have in our working folder
            LOG.debug("Checking out missing files from origin/master");

            for (final String missing : git.status().call().getMissing()) {
                LOG.debug("Checkout {}", missing);
                git.checkout().addPath(missing).call();
            }

            for (final String newFile : makeInitialFilesAsNecessary(this.localFolder)) {
                LOG.debug("Adding and committing {}", newFile);
                git.add().addFilepattern(newFile).call();
                git.commit().setMessage("Adding " + newFile).setAuthor(username, "42").call();

                for (final PushResult pr : git.push().setCredentialsProvider(cp).call()) {
                    LOG.debug("Push Message: {}", pr.getMessages());
                }
            }
        } else {
            // just push
            // make sure we have something to push
            for (final String newFile : makeInitialFilesAsNecessary(this.localFolder)) {
                LOG.debug("Adding and committing {}", newFile);
                git.add().addFilepattern(newFile).call();
            }

            git.commit().setMessage("Adding initial files").setAuthor(username, "42").call();
            LOG.debug("Pushing repository");

            for (final PushResult pr : git.push().setCredentialsProvider(cp).call()) {
                LOG.debug("Push Result: {}", pr.getMessages());
            }
        }

        LOG.info("linkAndFetchFromRemote Complete.  Current status: " + statusToString(git.status().call()));
    } catch (final TransportException te) {
        if (te.getMessage().contains("Auth fail") || te.getMessage().contains("not authorized")) {
            LOG.info("Auth fail", te);
            throw new AuthenticationException("Auth fail");
        } else {
            LOG.error("Unexpected", te);
            throw new IOException("Internal error", te);
        }
    } catch (final GitAPIException e) {
        LOG.error("Unexpected", e);
        throw new IOException("Internal error", e);
    } finally {
        if (git != null) {
            git.close();
        }

        if (r != null) {
            r.close();
        }
    }
}

From source file:to.sauerkraut.krautadmin.core.Toolkit.java

License:Open Source License

public static boolean updateFromGit(final File repositoryDirectory, final URI repositoryUri) throws Exception {
    final String unexpectedExceptionText = "incremental plugin-update from git failed";
    final String upstream = "refs/remotes/origin/master";
    boolean hasUpdated = false;
    Git gitRepo = null;

    try {/*w ww .j  ava 2 s  .  c o  m*/
        gitRepo = Git.open(repositoryDirectory);
        // first reset local changes
        gitRepo.reset().setMode(ResetCommand.ResetType.HARD).call();
        LOG.info("starting incremental plugin-update from git...");
        gitRepo.fetch().setRemote(Constants.DEFAULT_REMOTE_NAME).call();
        final RebaseResult rebaseResult = gitRepo.rebase().setStrategy(MergeStrategy.THEIRS)
                .setUpstream(upstream).setUpstreamName(upstream).call();
        final Status rebaseStatus = rebaseResult.getStatus();
        if (rebaseStatus.isSuccessful()) {
            if (!(Status.UP_TO_DATE.equals(rebaseStatus))) {
                hasUpdated = true;
            }
        } else {
            throw new WTFException(unexpectedExceptionText);
        }

        if (hasUpdated) {
            LOG.info("incremental plugin-update from git successful");
        } else {
            LOG.info("plugin-files are up-to-date");
        }
    } finally {
        try {
            if (gitRepo != null) {
                gitRepo.close();
            }
        } catch (Exception closex) {
            LOG.debug("closing git repo failed");
        }
    }

    return hasUpdated;
}