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:org.springframework.cloud.config.server.environment.JGitEnvironmentRepository.java

License:Apache License

private FetchResult fetch(Git git, String label) {
    FetchCommand fetch = git.fetch();
    fetch.setRemote("origin");
    fetch.setTagOpt(TagOpt.FETCH_TAGS);/* w  w w  . ja  va  2s .c  o m*/

    setTimeout(fetch);
    try {
        setCredentialsProvider(fetch);
        FetchResult result = fetch.call();
        if (result.getTrackingRefUpdates() != null && result.getTrackingRefUpdates().size() > 0) {
            logger.info("Fetched for remote " + label + " and found " + result.getTrackingRefUpdates().size()
                    + " updates");
        }
        return result;
    } catch (Exception ex) {
        String message = "Could not fetch remote for " + label + " remote: "
                + git.getRepository().getConfig().getString("remote", "origin", "url");
        warn(message, ex);
        return null;
    }
}

From source file:org.springframework.cloud.config.server.environment.JGitEnvironmentRepositoryTests.java

License:Apache License

@Test
public void testFetchException() throws Exception {

    Git git = mock(Git.class);
    CloneCommand cloneCommand = mock(CloneCommand.class);
    MockGitFactory factory = new MockGitFactory(git, cloneCommand);
    JGitEnvironmentRepository repo = new JGitEnvironmentRepository(this.environment);
    this.repository.setGitFactory(factory);

    //refresh()->shouldPull
    StatusCommand statusCommand = mock(StatusCommand.class);
    Status status = mock(Status.class);
    when(git.status()).thenReturn(statusCommand);
    Repository repository = mock(Repository.class);
    when(git.getRepository()).thenReturn(repository);
    StoredConfig storedConfig = mock(StoredConfig.class);
    when(repository.getConfig()).thenReturn(storedConfig);
    when(storedConfig.getString("remote", "origin", "url")).thenReturn("http://example/git");
    when(statusCommand.call()).thenReturn(status);
    when(status.isClean()).thenReturn(true);

    //refresh()->fetch
    FetchCommand fetchCommand = mock(FetchCommand.class);
    when(git.fetch()).thenReturn(fetchCommand);
    when(fetchCommand.setRemote(anyString())).thenReturn(fetchCommand);
    when(fetchCommand.call()).thenThrow(new InvalidRemoteException("invalid mock remote")); //here is our exception we are testing

    //refresh()->checkout
    CheckoutCommand checkoutCommand = mock(CheckoutCommand.class);
    //refresh()->checkout->containsBranch
    ListBranchCommand listBranchCommand = mock(ListBranchCommand.class);
    when(git.checkout()).thenReturn(checkoutCommand);
    when(git.branchList()).thenReturn(listBranchCommand);
    List<Ref> refs = new ArrayList<>();
    Ref ref = mock(Ref.class);
    refs.add(ref);/* ww  w .  jav a  2  s  .co m*/
    when(ref.getName()).thenReturn("/master");
    when(listBranchCommand.call()).thenReturn(refs);

    //refresh()->merge
    MergeCommand mergeCommand = mock(MergeCommand.class);
    when(git.merge()).thenReturn(mergeCommand);
    when(mergeCommand.call()).thenThrow(new NotMergedException()); //here is our exception we are testing

    //refresh()->return git.getRepository().getRef("HEAD").getObjectId().getName();
    Ref headRef = mock(Ref.class);
    when(repository.getRef(anyString())).thenReturn(headRef);

    ObjectId newObjectId = ObjectId.fromRaw(new int[] { 1, 2, 3, 4, 5 });
    when(headRef.getObjectId()).thenReturn(newObjectId);

    SearchPathLocator.Locations locations = this.repository.getLocations("bar", "staging", null);
    assertEquals(locations.getVersion(), newObjectId.getName());
}

From source file:org.springframework.cloud.config.server.environment.JGitEnvironmentRepositoryTests.java

License:Apache License

@Test
public void testMergeException() throws Exception {

    Git git = mock(Git.class);
    CloneCommand cloneCommand = mock(CloneCommand.class);
    MockGitFactory factory = new MockGitFactory(git, cloneCommand);
    JGitEnvironmentRepository repo = new JGitEnvironmentRepository(this.environment);
    this.repository.setGitFactory(factory);

    //refresh()->shouldPull
    StatusCommand statusCommand = mock(StatusCommand.class);
    Status status = mock(Status.class);
    when(git.status()).thenReturn(statusCommand);
    Repository repository = mock(Repository.class);
    when(git.getRepository()).thenReturn(repository);
    StoredConfig storedConfig = mock(StoredConfig.class);
    when(repository.getConfig()).thenReturn(storedConfig);
    when(storedConfig.getString("remote", "origin", "url")).thenReturn("http://example/git");
    when(statusCommand.call()).thenReturn(status);
    when(status.isClean()).thenReturn(true);

    //refresh()->fetch
    FetchCommand fetchCommand = mock(FetchCommand.class);
    FetchResult fetchResult = mock(FetchResult.class);
    when(git.fetch()).thenReturn(fetchCommand);
    when(fetchCommand.setRemote(anyString())).thenReturn(fetchCommand);
    when(fetchCommand.call()).thenReturn(fetchResult);
    when(fetchResult.getTrackingRefUpdates()).thenReturn(Collections.EMPTY_LIST);

    //refresh()->checkout
    CheckoutCommand checkoutCommand = mock(CheckoutCommand.class);
    //refresh()->checkout->containsBranch
    ListBranchCommand listBranchCommand = mock(ListBranchCommand.class);
    when(git.checkout()).thenReturn(checkoutCommand);
    when(git.branchList()).thenReturn(listBranchCommand);
    List<Ref> refs = new ArrayList<>();
    Ref ref = mock(Ref.class);
    refs.add(ref);/*from   w ww.j  av a2  s  .  c om*/
    when(ref.getName()).thenReturn("/master");
    when(listBranchCommand.call()).thenReturn(refs);

    //refresh()->merge
    MergeCommand mergeCommand = mock(MergeCommand.class);
    when(git.merge()).thenReturn(mergeCommand);
    when(mergeCommand.call()).thenThrow(new NotMergedException()); //here is our exception we are testing

    //refresh()->return git.getRepository().getRef("HEAD").getObjectId().getName();
    Ref headRef = mock(Ref.class);
    when(repository.getRef(anyString())).thenReturn(headRef);

    ObjectId newObjectId = ObjectId.fromRaw(new int[] { 1, 2, 3, 4, 5 });
    when(headRef.getObjectId()).thenReturn(newObjectId);

    SearchPathLocator.Locations locations = this.repository.getLocations("bar", "staging", "master");
    assertEquals(locations.getVersion(), newObjectId.getName());
}

From source file:org.springframework.cloud.config.server.environment.JGitEnvironmentRepositoryTests.java

License:Apache License

@Test
public void testResetHardException() throws Exception {

    Git git = mock(Git.class);
    CloneCommand cloneCommand = mock(CloneCommand.class);
    MockGitFactory factory = new MockGitFactory(git, cloneCommand);
    JGitEnvironmentRepository repo = new JGitEnvironmentRepository(this.environment);
    this.repository.setGitFactory(factory);

    //refresh()->shouldPull
    StatusCommand statusCommand = mock(StatusCommand.class);
    Status status = mock(Status.class);
    when(git.status()).thenReturn(statusCommand);
    Repository repository = mock(Repository.class);
    when(git.getRepository()).thenReturn(repository);
    StoredConfig storedConfig = mock(StoredConfig.class);
    when(repository.getConfig()).thenReturn(storedConfig);
    when(storedConfig.getString("remote", "origin", "url")).thenReturn("http://example/git");
    when(statusCommand.call()).thenReturn(status);
    when(status.isClean()).thenReturn(true).thenReturn(false);

    //refresh()->fetch
    FetchCommand fetchCommand = mock(FetchCommand.class);
    FetchResult fetchResult = mock(FetchResult.class);
    when(git.fetch()).thenReturn(fetchCommand);
    when(fetchCommand.setRemote(anyString())).thenReturn(fetchCommand);
    when(fetchCommand.call()).thenReturn(fetchResult);
    when(fetchResult.getTrackingRefUpdates()).thenReturn(Collections.EMPTY_LIST);

    //refresh()->checkout
    CheckoutCommand checkoutCommand = mock(CheckoutCommand.class);
    //refresh()->checkout->containsBranch
    ListBranchCommand listBranchCommand = mock(ListBranchCommand.class);
    when(git.checkout()).thenReturn(checkoutCommand);
    when(git.branchList()).thenReturn(listBranchCommand);
    List<Ref> refs = new ArrayList<>();
    Ref ref = mock(Ref.class);
    refs.add(ref);//  w  w  w . java2 s. co m
    when(ref.getName()).thenReturn("/master");
    when(listBranchCommand.call()).thenReturn(refs);

    //refresh()->merge
    MergeCommand mergeCommand = mock(MergeCommand.class);
    when(git.merge()).thenReturn(mergeCommand);
    when(mergeCommand.call()).thenThrow(new NotMergedException()); //here is our exception we are testing

    //refresh()->hardReset
    ResetCommand resetCommand = mock(ResetCommand.class);
    when(git.reset()).thenReturn(resetCommand);
    when(resetCommand.call()).thenReturn(ref);

    //refresh()->return git.getRepository().getRef("HEAD").getObjectId().getName();
    Ref headRef = mock(Ref.class);
    when(repository.getRef(anyString())).thenReturn(headRef);

    ObjectId newObjectId = ObjectId.fromRaw(new int[] { 1, 2, 3, 4, 5 });
    when(headRef.getObjectId()).thenReturn(newObjectId);

    SearchPathLocator.Locations locations = this.repository.getLocations("bar", "staging", "master");
    assertEquals(locations.getVersion(), newObjectId.getName());
}

From source file:org.springframework.cloud.config.server.JGitEnvironmentRepository.java

License:Apache License

private void tryFetch(Git git) {
    try {/*from  w ww.ja  v a2s .  c  o  m*/
        FetchCommand fetch = git.fetch();
        if (hasText(getUsername())) {
            setCredentialsProvider(fetch);
        }
        fetch.call();
    } catch (Exception e) {
        logger.warn("Remote repository not available");
    }
}

From source file:org.wso2.carbon.appfactory.repository.mgt.git.JGitAgent.java

License:Apache License

/**
 * Fetch a branch to FETCH_HEAD/*from   w w  w . j  av a  2s. c  o m*/
 *
 * @param remoteRepoUrl remote repository url
 * @param fetchBranch   branch to fetch
 * @param repoFile      repository directory where .git exists. If not exists will get cloned using {@code
 *                      remoteRepoUrl}
 * @return success
 * @throws RepositoryMgtException
 */
public boolean fetch(String remoteRepoUrl, String fetchBranch, File repoFile) throws RepositoryMgtException {
    try {
        Git gitRepo = getGitRepository(remoteRepoUrl, repoFile);
        gitRepo.fetch().setRemote(remoteRepoUrl).setRefSpecs(new RefSpec(HEAD_REF_PREFIX + fetchBranch))
                .setCredentialsProvider(getCredentialsProvider()).call();
        return true;
    } catch (RepositoryMgtException e) {
        String msg = "Error while fetching : " + fetchBranch + " due to " + e.getMessage()
                + " from GitAPIException";
        log.error(msg, e);
        throw new RepositoryMgtException(msg, e);
    } catch (GitAPIException e) {
        String msg = "Error while fetching : " + fetchBranch + " due to " + e.getMessage()
                + " from GitAPIException";
        log.error(msg, e);
        throw new RepositoryMgtException(msg, e);
    }
}

From source file:org.z2env.impl.helper.GitTools.java

License:Apache License

/**
 * Clones the given remote repository into the given destination folder. The method clones all branches but doesn't perform a checkout.
 *   //from   www .  j av a  2  s.co  m
 * @param remoteUri URI of the remote repository
 * @param destFolder local destination folder
 * @param credentials user credentials
 * @return the cloned repository
 * @throws IOException if something went wrong
 */
public static Repository cloneRepository(URIish remoteUri, File destFolder, CredentialsProvider credentials,
        int timeout) throws IOException {

    // workaround for http://redmine.z2-environment.net/issues/902:
    // split clone into its piece in order to get the chance to set "core.autocrlf"
    Git gitResult;
    try {
        gitResult = Git.init().setBare(false).setDirectory(destFolder).call();
    } catch (Exception e) {
        throw new IOException("Failed to initialize a new Git repository at " + destFolder.getAbsolutePath(),
                e);
    }

    Repository repo = gitResult.getRepository();

    // setting "core.autocrlf=false" helps to solve http://redmine.z2-environment.net/issues/902
    StoredConfig config = repo.getConfig();
    config.setString(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_AUTOCRLF,
            String.valueOf(false));

    // add origin - clone all branches
    RemoteConfig remoteCfg = null;
    try {
        remoteCfg = new RemoteConfig(config, "origin");
    } catch (URISyntaxException e) {
        throw new IOException("Failed to configure origin repository", e);
    }
    remoteCfg.addURI(remoteUri);
    remoteCfg.addFetchRefSpec(new RefSpec("+refs/heads/*:refs/remotes/origin/*"));
    remoteCfg.update(config);
    config.save();

    // fetch all branches from origin
    try {
        gitResult.fetch().setRemote("origin").setCredentialsProvider(credentials).setTimeout(timeout).call();
    } catch (Exception e) {
        throw new IOException("Failed to fetch from origin!", e);
    }

    return repo;
}

From source file:org.zanata.sync.jobs.plugin.git.service.impl.GitSyncService.java

License:Open Source License

protected static void doGitFetch(Git git) throws GitAPIException {
    log.info("doing git fetch");
    FetchResult result = git.fetch().call();
    log.info("git fetch result: {}", result.getMessages());
}

From source file:org.zanata.sync.plugin.git.service.impl.GitSyncService.java

License:Open Source License

private void doGitFetch(File destPath) {
    try {/*from   w  w  w . j  a  v a 2 s . co  m*/
        Git git = Git.open(destPath);
        git.fetch().setRemote("origin").call();
    } catch (IOException ioe) {
        // ignore
    } catch (Exception e) {
        log.error("fail to call git pull", e);
        throw new RepoSyncException(e);
    }
}

From source file:replicatorg.app.ui.panels.UpdateChecker.java

License:Open Source License

private void updateFilaments() {
    final FileRepositoryBuilder repoBuilder = new FileRepositoryBuilder();
    final Git git;
    final Status repoStatus;
    final RemoteAddCommand remoteAddCmd;
    ResetCommand resetCmd;/* w  ww  .  j  a v a  2  s  .co  m*/
    CheckoutCommand checkoutCmd;
    final String currentBranch, newBranch;
    final List<Ref> branchList;
    Repository filamentsRepo;
    boolean branchFoundLocally = false;
    RevCommit stash = null;

    repoBuilder.setMustExist(true);
    repoBuilder.setGitDir(new File(FILAMENTS_REPO_PATH + ".git"));

    try {
        try {
            Base.writeLog("Attempting to open repo at " + FILAMENTS_REPO_PATH, this.getClass());
            filamentsRepo = repoBuilder.build();
        } catch (RepositoryNotFoundException ex) {
            try {
                Base.writeLog("Repository wasn't initialized, initializing it to the given URL: "
                        + FILAMENTS_REPO_URL, this.getClass());
                repoBuilder.setMustExist(false);
                filamentsRepo = repoBuilder.build();
                filamentsRepo.create();
            } catch (IOException ex1) {
                Base.writeLog("IOException while attempting to initialize repository, not updating filaments",
                        this.getClass());
                return;
            }
        }

        currentBranch = filamentsRepo.getBranch();

    } catch (IOException ex) {
        Base.writeLog("IOException while attempting to open repository, not updating filaments",
                this.getClass());
        return;
    }

    git = new Git(filamentsRepo);

    try {
        // it should be only 1, but it shortens the code needed, as the call()
        // method returns an iterable
        for (RevCommit commit : git.log().setMaxCount(1).call()) {
            Base.writeLog("Current commit hash: " + commit, this.getClass());
        }
    } catch (GitAPIException ex) {
        Base.writeLog(
                "GitAPIException while attempting to get current commit's hash. Not a critical error, so proceeding with update",
                this.getClass());
    }

    try {
        remoteAddCmd = git.remoteAdd();
        remoteAddCmd.setName("origin");
        remoteAddCmd.setUri(new URIish(FILAMENTS_REPO_URL));
        remoteAddCmd.call();
    } catch (URISyntaxException ex) {
        Base.writeLog("Invalid git filament repo remote URL!", this.getClass());
        return;
    } catch (GitAPIException ex) {
        Base.writeLog("GitAPIException thrown when adding remote to git filament repo", this.getClass());
        return;
    }

    try {

        if (currentBranch.equals(FILAMENTS_REPO_BRANCH) == false) {
            Base.writeLog("Repo branch is " + currentBranch + " and it should be " + FILAMENTS_REPO_BRANCH
                    + ", searching for it", this.getClass());
            checkoutCmd = git.checkout();
            checkoutCmd.setName(FILAMENTS_REPO_BRANCH);

            branchList = git.branchList().call();

            for (Ref ref : branchList) {
                if (ref.getName().contains(FILAMENTS_REPO_BRANCH)) {
                    Base.writeLog("Correct branch was found locally", this.getClass());
                    branchFoundLocally = true;
                    break;
                }
            }

            if (branchFoundLocally == false) {
                Base.writeLog(
                        "No correct branch was found locally, attempting to checkout a new branch tracking the remote",
                        this.getClass());
                checkoutCmd.setCreateBranch(true);
                checkoutCmd.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK);
                checkoutCmd.setStartPoint(FILAMENTS_REPO_BRANCH);
                git.fetch().call();
            }

            RevCommit backup = null;
            if (git.status().call().isClean() == false) {
                git.add().addFilepattern(".").call();
                backup = git.commit().setMessage("local backup of user modifications").call();
            }

            newBranch = checkoutCmd.call().getName();

            if (newBranch.contains(FILAMENTS_REPO_BRANCH) == false) {
                Base.writeLog("Unable to change to correct branch, aborting update", this.getClass());
                return;
            } else {
                Base.writeLog("Changed to correct branch, " + newBranch, this.getClass());
            }

            try {
                for (RevCommit commit : git.log().setMaxCount(1).call()) {
                    Base.writeLog("Commit hash after branch change: " + commit, this.getClass());

                }
            } catch (GitAPIException ex) {
                // we don't want all the process to stop just because we couldn't acquire the hash here,
                // hence this catch
                Base.writeLog(
                        "GitAPIException while attempting to get current commit's hash, after changing branch. Not a critical error, so proceeding with update",
                        this.getClass());
            }

            if (backup != null) {
                // TODO: restore backup of user modifications
                //git.cherryPick().setNoCommit(true).include(backup).call();
            }
        }

        repoStatus = git.status().call();

        checkoutCmd = git.checkout();
        checkoutCmd.setName(FILAMENTS_REPO_BRANCH);
        checkoutCmd.call();

        git.fetch();
        resetCmd = git.reset();
        resetCmd.setMode(ResetType.HARD);
        resetCmd.call();

        git.pull().call();

        /*
        repoStatus = git.status().call();
        if (repoStatus.hasUncommittedChanges()) {
        Base.writeLog("Repo has uncommited changes, stashing and pulling...", this.getClass());
        stash = git.stashCreate().call();
        git.pull().call();
        git.stashApply().call();        // will apply the last stash made
        git.stashDrop().call();         // remove the last stash made
        } else {
        Base.writeLog("Repo has no uncommited changes, a simple pull will suffice", this.getClass());
        git.pull().call();
        }
        */

        Base.writeLog("Filament update concluded successfully!", this.getClass());

        try {
            for (RevCommit commit : git.log().setMaxCount(1).call()) {
                Base.writeLog("Commit hash after update process finished: " + commit, this.getClass());

            }
        } catch (GitAPIException ex) {
            // we don't want all the process to stop just because we couldn't acquire the hash here,
            // hence this catch
            Base.writeLog(
                    "GitAPIException while attempting to get current commit's hash, after the process finished with success. Not a critical error, so proceeding with update",
                    this.getClass());
        }
    } catch (GitAPIException ex) {
        Base.writeLog("GitAPIException while attempting to update filaments, aborting update", this.getClass());
        try {
            resetCmd = git.reset();
            resetCmd.setMode(ResetType.HARD);
            resetCmd.call();

            if (stash != null) {
                git.stashApply().call();
                git.stashDrop().call();
            }

        } catch (GitAPIException ex1) {
            Base.writeLog("GitAPIException while attempting to reset after an error, uh oh...",
                    this.getClass());
        }
    }

}