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

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

Introduction

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

Prototype

public DeleteBranchCommand branchDelete() 

Source Link

Document

Return a command object used to delete branches

Usage

From source file:io.fabric8.git.internal.GitDataStore.java

License:Apache License

/**
 * Performs a pull so the git repo is pretty much up to date before we start performing operations on it.
 *
 * @param git                 The {@link Git} instance to use.
 * @param credentialsProvider The {@link CredentialsProvider} to use.
 * @param doDeleteBranches    Flag that determines if local branches that don't exist in remote should get deleted.
 *///from   w  w w . ja v a2  s .  co m
protected void doPull(Git git, CredentialsProvider credentialsProvider, boolean doDeleteBranches) {
    assertValid();
    try {
        Repository repository = git.getRepository();
        StoredConfig config = repository.getConfig();
        String url = config.getString("remote", remoteRef.get(), "url");
        if (Strings.isNullOrBlank(url)) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("No remote repository defined for the git repository at "
                        + GitHelpers.getRootGitDirectory(git) + " so not doing a pull");
            }
            return;
        }
        /*
        String branch = repository.getBranch();
        String mergeUrl = config.getString("branch", branch, "merge");
        if (Strings.isNullOrBlank(mergeUrl)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("No merge spec for branch." + branch + ".merge in the git repository at "
                    + GitHelpers.getRootGitDirectory(git) + " so not doing a pull");
        }
        return;
        }
        */
        if (LOG.isDebugEnabled()) {
            LOG.debug("Performing a fetch in git repository " + GitHelpers.getRootGitDirectory(git)
                    + " on remote URL: " + url);
        }

        boolean hasChanged = false;
        try {
            FetchResult result = git.fetch().setTimeout(gitTimeout).setCredentialsProvider(credentialsProvider)
                    .setRemote(remoteRef.get()).call();
            if (LOG.isDebugEnabled()) {
                LOG.debug("Git fetch result: {}", result.getMessages());
            }
            lastFetchWarning = null;
        } catch (Exception ex) {
            String fetchWarning = ex.getMessage();
            if (!fetchWarning.equals(lastFetchWarning)) {
                LOG.warn("Fetch failed because of: " + fetchWarning);
                LOG.debug("Fetch failed - the error will be ignored", ex);
                lastFetchWarning = fetchWarning;
            }
            return;
        }

        // Get local and remote branches
        Map<String, Ref> localBranches = new HashMap<String, Ref>();
        Map<String, Ref> remoteBranches = new HashMap<String, Ref>();
        Set<String> gitVersions = new HashSet<String>();
        for (Ref ref : git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call()) {
            if (ref.getName().startsWith("refs/remotes/" + remoteRef.get() + "/")) {
                String name = ref.getName().substring(("refs/remotes/" + remoteRef.get() + "/").length());
                remoteBranches.put(name, ref);
                gitVersions.add(name);
            } else if (ref.getName().startsWith("refs/heads/")) {
                String name = ref.getName().substring(("refs/heads/").length());
                localBranches.put(name, ref);
                gitVersions.add(name);
            }
        }

        // Check git commits
        for (String version : gitVersions) {
            // Delete unneeded local branches.
            //Check if any remote branches was found as a guard for unwanted deletions.
            if (remoteBranches.isEmpty()) {
                //Do nothing
            } else if (!remoteBranches.containsKey(version)) {
                //We never want to delete the master branch.
                if (doDeleteBranches && !version.equals(MASTER_BRANCH)) {
                    try {
                        git.branchDelete().setBranchNames(localBranches.get(version).getName()).setForce(true)
                                .call();
                    } catch (CannotDeleteCurrentBranchException ex) {
                        git.checkout().setName(MASTER_BRANCH).setForce(true).call();
                        git.branchDelete().setBranchNames(localBranches.get(version).getName()).setForce(true)
                                .call();
                    }
                    removeVersion(version);
                    hasChanged = true;
                }
            }
            // Create new local branches
            else if (!localBranches.containsKey(version)) {
                addVersion(version);
                git.checkout().setCreateBranch(true).setName(version)
                        .setStartPoint(remoteRef.get() + "/" + version)
                        .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).setForce(true).call();
                hasChanged = true;
            } else {
                String localCommit = localBranches.get(version).getObjectId().getName();
                String remoteCommit = remoteBranches.get(version).getObjectId().getName();
                if (!localCommit.equals(remoteCommit)) {
                    git.clean().setCleanDirectories(true).call();
                    git.checkout().setName("HEAD").setForce(true).call();
                    git.checkout().setName(version).setForce(true).call();
                    MergeResult result = git.merge().setStrategy(MergeStrategy.THEIRS)
                            .include(remoteBranches.get(version).getObjectId()).call();
                    if (result.getMergeStatus() != MergeResult.MergeStatus.ALREADY_UP_TO_DATE
                            && hasChanged(git, localCommit, remoteCommit)) {
                        hasChanged = true;
                    }
                    // TODO: handle conflicts
                }
            }
        }
        if (hasChanged) {
            LOG.debug("Changed after pull!");
            if (credentialsProvider != null) {
                // TODO lets test if the profiles directory is present after checking out version 1.0?
                getProfilesDirectory(git);
            }
            fireChangeNotifications();
        }
    } catch (Throwable ex) {
        LOG.debug("Failed to pull from the remote git repo " + GitHelpers.getRootGitDirectory(git), ex);
        LOG.warn("Failed to pull from the remote git repo " + GitHelpers.getRootGitDirectory(git) + " due "
                + ex.getMessage() + ". This exception is ignored.");
    }
}

From source file:io.fabric8.git.internal.GitHelpers.java

License:Apache License

public static boolean removeBranch(Git git, String branch) throws GitAPIException {
    IllegalStateAssertion.assertFalse("master".equals(branch), "Cannot remove master branch");
    if (localBranchExists(git, branch)) {
        String current = currentBranch(git);
        if (equals(current, branch)) {
            checkoutBranch(git, "master");
        }//  w  w w  .j  ava 2s  . c om
        List<String> list = git.branchDelete().setBranchNames(branch).setForce(true).call();
        LOGGER.debug("Deleted branch {} with results: {}", branch, list);
        return true;
    } else {
        LOGGER.debug("Branch {} not found!", branch);
        return true;
    }
}

From source file:io.fabric8.git.zkbridge.Bridge.java

License:Apache License

private void updateLocal(Git git, CuratorFramework zookeeper, CredentialsProvider credentialsProvider)
        throws Exception {
    String remoteName = "origin";

    try {/*from  www  .j a  v  a2 s.  c  o  m*/
        git.fetch().setCredentialsProvider(credentialsProvider).setRemote(remoteName).call();
    } catch (Exception e) {
        // Ignore fetch exceptions
        return;
    }

    // Get local and remote branches
    Map<String, Ref> localBranches = new HashMap<String, Ref>();
    Map<String, Ref> remoteBranches = new HashMap<String, Ref>();
    Set<String> gitVersions = new HashSet<String>();
    for (Ref ref : git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call()) {
        if (ref.getName().startsWith("refs/remotes/" + remoteName + "/")) {
            String name = ref.getName().substring(("refs/remotes/" + remoteName + "/").length());
            if (!"master".equals(name) && !name.endsWith("-tmp")) {
                remoteBranches.put(name, ref);
                gitVersions.add(name);
            }
        } else if (ref.getName().startsWith("refs/heads/")) {
            String name = ref.getName().substring(("refs/heads/").length());
            if (!name.equals("master") && !name.endsWith("-tmp")) {
                localBranches.put(name, ref);
                gitVersions.add(name);
            }
        }
    }

    // Check git commmits
    for (String version : gitVersions) {
        // Delete unneeded local branches
        if (!remoteBranches.containsKey(version)) {
            git.branchDelete().setBranchNames(localBranches.get(version).getName()).setForce(true).call();
        }
        // Create new local branches
        else if (!localBranches.containsKey(version)) {
            git.branchCreate().setName(version).call();
            git.reset().setMode(ResetCommand.ResetType.HARD).setRef(remoteBranches.get(version).getName())
                    .call();
        } else {
            String localCommit = localBranches.get(version).getObjectId().getName();
            String remoteCommit = remoteBranches.get(version).getObjectId().getName();
            if (!localCommit.equals(remoteCommit)) {
                git.clean().setCleanDirectories(true).call();
                git.checkout().setName("HEAD").setForce(true).call();
                git.checkout().setName(version).setForce(true).call();
                MergeResult result = git.merge().setStrategy(MergeStrategy.THEIRS)
                        .include(remoteBranches.get(version).getObjectId()).call();
                // TODO: handle conflicts
            }
        }
    }
}

From source file:io.fabric8.git.zkbridge.Bridge.java

License:Apache License

private static void update(Git git, CuratorFramework zookeeper, CredentialsProvider credentialsProvider)
        throws Exception {
    String remoteName = "origin";

    boolean remoteAvailable = false;
    try {// ww w.  ja v a2 s. c o  m
        git.fetch().setCredentialsProvider(credentialsProvider).setRemote(remoteName).call();
        remoteAvailable = true;
    } catch (Exception e) {
        // Ignore fetch exceptions
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Unable to fetch master", e);
        } else if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Unable to fetch master: " + e.getClass().getName() + ": " + e.getMessage());
        }
    }

    // Handle versions in git and not in zookeeper
    Map<String, Ref> localBranches = new HashMap<String, Ref>();
    Map<String, Ref> remoteBranches = new HashMap<String, Ref>();
    Set<String> gitVersions = new HashSet<String>();
    for (Ref ref : git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call()) {
        if (ref.getName().startsWith("refs/remotes/" + remoteName + "/")) {
            String name = ref.getName().substring(("refs/remotes/" + remoteName + "/").length());
            if (!"master".equals(name) && !name.endsWith("-tmp")) {
                remoteBranches.put(name, ref);
                gitVersions.add(name);
            }
        } else if (ref.getName().startsWith("refs/heads/")) {
            String name = ref.getName().substring(("refs/heads/").length());
            if (!name.equals("master") && !name.endsWith("-tmp")) {
                localBranches.put(name, ref);
                gitVersions.add(name);
            }
        }
    }
    List<String> zkVersions = getChildren(zookeeper, ZkPath.CONFIG_VERSIONS.getPath());
    createDefault(zookeeper, "/fabric/configs/git", null);
    Properties versionsMetadata = loadProps(zookeeper, "/fabric/configs/git");

    boolean allDone = true;
    // Check no modifs in zookeeper
    String lastModified = Long.toString(lastModified(zookeeper, ZkPath.CONFIG_VERSIONS.getPath()));
    if (!lastModified.equals(versionsMetadata.get("zk-lastmodified"))) {
        allDone = false;
    }
    // Check the versions in zk and git are the same
    if (zkVersions.size() != gitVersions.size() || !zkVersions.containsAll(gitVersions)) {
        allDone = false;
    }
    // Check all local and remote branches exists
    if (gitVersions.size() != localBranches.size() || !localBranches.keySet().containsAll(gitVersions)) {
        allDone = false;
    }
    // If remote is available, check that all remote branches exist
    if (remoteAvailable && !remoteBranches.keySet().containsAll(gitVersions)) {
        allDone = false;
    }
    // Check git commmits
    if (allDone) {
        for (String version : zkVersions) {
            String zkCommit = versionsMetadata.get(version);
            String localCommit = localBranches.get(version).getObjectId().getName();
            String remoteCommit = remoteAvailable ? remoteBranches.get(version).getObjectId().getName() : null;
            if (!localCommit.equals(zkCommit) || remoteCommit != null && !localCommit.equals(remoteCommit)) {
                allDone = false;
                break;
            }
        }
    }
    if (allDone) {
        return;
    }

    // ZooKeeper -> Git changes
    for (String version : zkVersions) {
        String zkNode = ZkPath.CONFIG_VERSION.getPath(version);

        // Checkout updated version
        List<Ref> allBranches = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call();
        Ref local = null;
        Ref remote = null;
        Ref tmp = null;
        for (Ref ref : allBranches) {
            if (ref.getName().equals("refs/remotes/" + remoteName + "/" + version)) {
                remote = ref;
            } else if (ref.getName().equals("refs/heads/" + version)) {
                local = ref;
            } else if (ref.getName().equals("refs/heads/" + version + "-tmp")) {
                tmp = ref;
            }
        }
        if (local == null) {
            git.branchCreate().setName(version).call();
        }
        if (tmp == null) {
            git.branchCreate().setName(version + "-tmp").call();
        }
        git.clean().setCleanDirectories(true).call();
        git.checkout().setName("HEAD").setForce(true).call();
        git.checkout().setName(version).setForce(true).call();
        if (remoteAvailable && remote != null) {
            MergeResult result = git.merge().setStrategy(MergeStrategy.THEIRS).include(remote.getObjectId())
                    .call();
            // TODO: check merge conflicts
        }
        git.checkout().setName(version + "-tmp").setForce(true).call();
        String gitCommit = versionsMetadata.get(version);
        if (gitCommit != null) {
            try {
                git.reset().setMode(ResetCommand.ResetType.HARD).setRef(gitCommit).call();
            } catch (Exception e) {
                // Ignore, we did our best
                if (LOGGER.isTraceEnabled()) {
                    LOGGER.trace("Unable to reset branch to commit", e);
                } else if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Unable to reset branch to commit " + gitCommit + ": " + e.getClass().getName()
                            + ": " + e.getMessage());
                }
            }
        }

        // Apply changes to git
        syncVersionFromZkToGit(git, zookeeper, zkNode);

        if (git.status().call().isClean()) {
            git.checkout().setName(version).setForce(true).call();
        } else {
            ObjectId rev = git.commit().setMessage("Merge zookeeper updates in version " + version).call()
                    .getId();
            git.checkout().setName(version).setForce(true).call();
            MergeResult result = git.merge().setStrategy(MergeStrategy.OURS).include(rev).call();
            // TODO: check merge conflicts
        }
        if (remoteAvailable) {
            git.push().setCredentialsProvider(credentialsProvider).setRefSpecs(new RefSpec(version)).call();
        }

        // Apply changes to zookeeper
        syncVersionFromGitToZk(git, zookeeper, zkNode);

        versionsMetadata.put(version, git.getRepository().getRef("HEAD").getObjectId().getName());
    }
    // Iterate through known git versions
    for (String version : gitVersions) {
        String state = versionsMetadata.get(version);
        if (zkVersions.contains(version)) {
            continue;
        }
        // The version is not known to zookeeper, so create it
        if (state == null) {
            if (localBranches.containsKey(version)) {
                if (remoteAvailable) {
                    git.push().setRefSpecs(new RefSpec(version)).call();
                }
            } else {
                git.branchCreate().setName(version).call();
                git.reset().setMode(ResetCommand.ResetType.HARD).setRef(remoteBranches.get(version).getName())
                        .call();
            }
            git.checkout().setName(version).setForce(true).call();
            // Sync zookeeper
            String zkNode = ZkPath.CONFIG_VERSION.getPath(version);
            create(zookeeper, zkNode);
            create(zookeeper, ZkPath.CONFIG_VERSIONS_PROFILES.getPath(version));
            create(zookeeper, ZkPath.CONFIG_VERSIONS_CONTAINERS.getPath(version));
            syncVersionFromGitToZk(git, zookeeper, zkNode);
            // Flag version as active
            versionsMetadata.put(version, git.getRepository().getRef("HEAD").getObjectId().getName());
        }
        // The version has been deleted from zookeeper so delete it in git
        else {
            git.checkout().setName("master").setForce(true).call();
            git.branchDelete().setBranchNames(version, version + "-tmp").setForce(true).call();
            git.push().setRefSpecs(new RefSpec(version + ":")).call();
            versionsMetadata.remove(version);
        }
    }
    versionsMetadata.put("zk-lastmodified",
            Long.toString(lastModified(zookeeper, ZkPath.CONFIG_VERSIONS.getPath())));
    setPropertiesAsMap(zookeeper, "/fabric/configs/git", versionsMetadata);
}

From source file:org.eclipse.egit.ui.test.team.actions.CompareActionsTest.java

License:Open Source License

@Test
public void testCompareWithPreviousWithMerge() throws Exception {
    Repository repo = lookupRepository(repositoryFile);

    Git git = new Git(repo);
    ObjectId masterId = repo.resolve("refs/heads/master");
    Ref newBranch = git.checkout().setCreateBranch(true).setStartPoint(commitOfTag.name()).setName("toMerge")
            .call();//  w ww  .j  ava2  s. c  om
    ByteArrayInputStream bis = new ByteArrayInputStream("Modified".getBytes());
    ResourcesPlugin.getWorkspace().getRoot().getProject(PROJ1).getFolder(FOLDER).getFile(FILE2).setContents(bis,
            false, false, null);
    bis.close();
    git.commit().setAll(true).setMessage("To be merged").call();
    git.merge().include(masterId).call();
    String menuLabel = util.getPluginLocalizedValue("CompareWithPreviousAction.label");
    SWTBotShell selectDialog = openCompareWithDialog(menuLabel, UIText.CommitSelectDialog_WindowTitle);
    assertEquals(2, selectDialog.bot().table().rowCount());
    selectDialog.close();
    // cleanup: checkout again master and delete merged branch
    git.checkout().setName("refs/heads/master").call();
    git.branchDelete().setBranchNames(newBranch.getName()).setForce(true).call();
}

From source file:org.eclipse.egit.ui.test.team.actions.ReplaceActionsTest.java

License:Open Source License

@Test
public void testReplaceWithPreviousWithMerge() throws Exception {
    Repository repo = lookupRepository(repositoryFile);
    Git git = new Git(repo);
    ObjectId masterId = repo.resolve("refs/heads/master");
    Ref newBranch = git.checkout().setCreateBranch(true).setStartPoint(commitOfTag.name()).setName("toMerge")
            .call();// w  ww.  j a  v  a2 s  .co  m
    ByteArrayInputStream bis = new ByteArrayInputStream("Modified".getBytes());
    ResourcesPlugin.getWorkspace().getRoot().getProject(PROJ1).getFolder(FOLDER).getFile(FILE2).setContents(bis,
            false, false, null);
    bis.close();
    PersonIdent committer = new PersonIdent("COMMITTER", "a.c@d", new Date(),
            TimeZone.getTimeZone("GMT-03:30"));
    git.commit().setAll(true).setCommitter(committer).setMessage("To be merged").call();
    git.merge().include(masterId).call();
    String newContent = getTestFileContent();
    String menuLabel = util.getPluginLocalizedValue("replaceWithPreviousVersionAction.label");
    clickReplaceWith(menuLabel);
    bot.shell(UIText.DiscardChangesAction_confirmActionTitle).bot().button(IDialogConstants.OK_LABEL).click();
    SWTBotShell selectDialog = bot.shell(UIText.CommitSelectDialog_WindowTitle);
    assertEquals(2, selectDialog.bot().table().rowCount());
    selectDialog.close();
    // we have closed, so nothing should have changed
    String oldContent = getTestFileContent();
    assertTrue(newContent.equals(oldContent));

    clickReplaceWith(menuLabel);
    bot.shell(UIText.DiscardChangesAction_confirmActionTitle).bot().button(IDialogConstants.OK_LABEL).click();
    selectDialog = bot.shell(UIText.CommitSelectDialog_WindowTitle);
    selectDialog.bot().table().select(1);
    selectDialog.bot().button(IDialogConstants.OK_LABEL).click();
    TestUtil.joinJobs(org.eclipse.egit.ui.JobFamilies.DISCARD_CHANGES);
    oldContent = getTestFileContent();
    assertFalse(newContent.equals(oldContent));
    // cleanup: checkout again master and delete merged branch
    git.checkout().setName("refs/heads/master").call();
    git.branchDelete().setBranchNames(newBranch.getName()).setForce(true).call();
}

From source file:org.eclipse.orion.server.git.servlets.GitBranchHandlerV1.java

License:Open Source License

private boolean handleDelete(HttpServletRequest request, HttpServletResponse response, String path)
        throws IOException, JSONException, ServletException, URISyntaxException, CoreException,
        JGitInternalException, GitAPIException {
    // FIXME: what if there is a branch named "file"?
    Path p = new Path(path);
    if (p.segment(1).equals("file")) { //$NON-NLS-1$
        // branch details: expected path /git/branch/{name}/file/{path}
        File gitDir = GitUtils.getGitDir(p.removeFirstSegments(1));
        Repository db = new FileRepository(gitDir);
        Git git = new Git(db);

        DeleteBranchCommand cc = git.branchDelete();
        cc.setBranchNames(p.segment(0));
        // TODO: the force flag should be passed in the API call
        cc.setForce(true);/*  www .  j ava 2s . c  om*/
        cc.call();

        // TODO: do something with the result, and handle any exceptions
        return true;
    }
    return false;
}

From source file:org.exist.git.xquery.BranchDelete.java

License:Open Source License

@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {

    try {/*from w  w  w . j  a  va 2  s .  c  o  m*/
        String localPath = args[0].getStringValue();
        if (!(localPath.endsWith("/")))
            localPath += File.separator;

        Git git = Git.open(new Resource(localPath), FS);

        git.branchDelete().setBranchNames(args[1].getStringValue()).call();

        return BooleanValue.TRUE;
    } catch (Throwable e) {
        throw new XPathException(this, Module.EXGIT001, e);
    }
}

From source file:org.flowerplatform.web.git.GitService.java

License:Open Source License

@RemoteInvocation
public boolean deleteBranch(ServiceInvocationContext context, List<PathFragment> path) {
    try {//w  ww . java2  s .  c  om
        RefNode node = (RefNode) GenericTreeStatefulService.getNodeByPathFor(path, null);
        GenericTreeStatefulService service = GenericTreeStatefulService.getServiceFromPathWithRoot(path);
        NodeInfo nodeInfo = service.getVisibleNodes().get(node);
        Repository repository = node.getRepository();

        Git git = new Git(repository);

        git.branchDelete().setBranchNames(node.getRef().getName()).setForce(true).call();

        // delete working directory
        String branchName = node.getRef().getName().substring(Constants.R_HEADS.length());
        File mainRepoFile = repository.getDirectory().getParentFile();
        File wdirFile = new File(mainRepoFile.getParentFile(), GitUtils.WORKING_DIRECTORY_PREFIX + branchName);
        if (wdirFile.exists()) {
            GitPlugin.getInstance().getUtils().delete(wdirFile);
        }

        dispatchContentUpdate(nodeInfo.getParent().getNode());
        return true;
    } catch (GitAPIException e) {
        logger.debug(CommonPlugin.getInstance().getMessage("error"), path, e);
        context.getCommunicationChannel().appendOrSendCommand(
                new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"),
                        e.getMessage(), DisplaySimpleMessageClientCommand.ICON_ERROR));
        return false;
    }
}

From source file:org.fusesource.fabric.git.internal.GitDataStore.java

License:Apache License

/**
 * Performs a pull so the git repo is pretty much up to date before we start performing operations on it
 *///from w  ww  .  j  a  v a  2  s .  c  o  m
protected void doPull(Git git, CredentialsProvider credentialsProvider) {
    assertValid();
    try {
        Repository repository = git.getRepository();
        StoredConfig config = repository.getConfig();
        String url = config.getString("remote", remote, "url");
        if (Strings.isNullOrBlank(url)) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("No remote repository defined for the git repository at "
                        + GitHelpers.getRootGitDirectory(git) + " so not doing a pull");
            }
            return;
        }
        /*
        String branch = repository.getBranch();
        String mergeUrl = config.getString("branch", branch, "merge");
        if (Strings.isNullOrBlank(mergeUrl)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("No merge spec for branch." + branch + ".merge in the git repository at "
                    + GitHelpers.getRootGitDirectory(git) + " so not doing a pull");
        }
        return;
        }
        */
        if (LOG.isDebugEnabled()) {
            LOG.debug("Performing a fetch in git repository " + GitHelpers.getRootGitDirectory(git)
                    + " on remote URL: " + url);
        }

        boolean hasChanged = false;
        try {
            git.fetch().setCredentialsProvider(credentialsProvider).setRemote(remote).call();
        } catch (Exception e) {
            LOG.debug("Fetch failed. Ignoring");
            return;
        }

        // Get local and remote branches
        Map<String, Ref> localBranches = new HashMap<String, Ref>();
        Map<String, Ref> remoteBranches = new HashMap<String, Ref>();
        Set<String> gitVersions = new HashSet<String>();
        for (Ref ref : git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call()) {
            if (ref.getName().startsWith("refs/remotes/" + remote + "/")) {
                String name = ref.getName().substring(("refs/remotes/" + remote + "/").length());
                if (!name.endsWith("-tmp")) {
                    remoteBranches.put(name, ref);
                    gitVersions.add(name);
                }
            } else if (ref.getName().startsWith("refs/heads/")) {
                String name = ref.getName().substring(("refs/heads/").length());
                if (!name.endsWith("-tmp")) {
                    localBranches.put(name, ref);
                    gitVersions.add(name);
                }
            }
        }

        // Check git commmits
        for (String version : gitVersions) {
            // Delete unneeded local branches.
            //Check if any remote branches was found as a guard for unwanted deletions.
            if (!remoteBranches.containsKey(version) && !remoteBranches.isEmpty()) {
                //We never want to delete the master branch.
                if (!version.equals(MASTER_BRANCH)) {
                    try {
                        git.branchDelete().setBranchNames(localBranches.get(version).getName()).setForce(true)
                                .call();
                    } catch (CannotDeleteCurrentBranchException ex) {
                        git.checkout().setName(MASTER_BRANCH).setForce(true).call();
                        git.branchDelete().setBranchNames(localBranches.get(version).getName()).setForce(true)
                                .call();
                    }
                    hasChanged = true;
                }
            }
            // Create new local branches
            else if (!localBranches.containsKey(version)) {
                git.checkout().setCreateBranch(true).setName(version).setStartPoint(remote + "/" + version)
                        .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).setForce(true).call();
                hasChanged = true;
            } else {
                String localCommit = localBranches.get(version).getObjectId().getName();
                String remoteCommit = remoteBranches.get(version).getObjectId().getName();
                if (!localCommit.equals(remoteCommit)) {
                    git.clean().setCleanDirectories(true).call();
                    git.checkout().setName("HEAD").setForce(true).call();
                    git.checkout().setName(version).setForce(true).call();
                    MergeResult result = git.merge().setStrategy(MergeStrategy.THEIRS)
                            .include(remoteBranches.get(version).getObjectId()).call();
                    if (result.getMergeStatus() != MergeResult.MergeStatus.ALREADY_UP_TO_DATE) {
                        hasChanged = true;
                    }
                    // TODO: handle conflicts
                }
            }
        }
        if (hasChanged) {
            LOG.debug("Changed after pull!");
            if (credentialsProvider != null) {
                // TODO lets test if the profiles directory is present after checking out version 1.0?
                File profilesDirectory = getProfilesDirectory(git);
            }
            fireChangeNotifications();
        }
    } catch (Throwable e) {
        LOG.error("Failed to pull from the remote git repo " + GitHelpers.getRootGitDirectory(git)
                + ". Reason: " + e, e);
    }
}