Example usage for org.eclipse.jgit.lib StoredConfig getString

List of usage examples for org.eclipse.jgit.lib StoredConfig getString

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib StoredConfig getString.

Prototype

public String getString(final String section, String subsection, final String name) 

Source Link

Document

Get string value or null if not found.

Usage

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

License:Apache License

@Override
public synchronized PullPolicyResult doPull(GitContext context, CredentialsProvider credentialsProvider,
        boolean allowVersionDelete) {
    Repository repository = git.getRepository();
    StoredConfig config = repository.getConfig();
    String remoteUrl = config.getString("remote", remoteRef, "url");
    if (remoteUrl == null) {
        LOGGER.debug("No remote repository defined, so not doing a pull");
        return new AbstractPullPolicyResult();
    }/*from  w  w w .java  2 s  .co m*/

    LOGGER.info("Performing a pull on remote URL: {}", remoteUrl);

    Exception lastException = null;
    try {
        git.fetch().setTimeout(gitTimeout).setCredentialsProvider(credentialsProvider).setRemote(remoteRef)
                .call();
    } catch (GitAPIException | JGitInternalException ex) {
        lastException = ex;
    }

    // No meaningful processing after GitAPIException
    if (lastException != null) {
        LOGGER.warn("Pull failed because of: {}", lastException.toString());
        return new AbstractPullPolicyResult(lastException);
    }

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

        boolean localUpdate = false;
        boolean remoteUpdate = false;
        Set<String> versions = new TreeSet<>();

        // Remote repository has no branches, force a push
        if (remoteBranches.isEmpty()) {
            LOGGER.debug("Pulled from an empty remote repository");
            return new AbstractPullPolicyResult(versions, false, !localBranches.isEmpty(), null);
        } else {
            LOGGER.debug("Processing remote branches: {}", remoteBranches);
        }

        // Verify master branch and do a checkout of it when we have it locally (already)
        IllegalStateAssertion.assertTrue(remoteBranches.containsKey(GitHelpers.MASTER_BRANCH),
                "Remote repository does not have a master branch");
        if (localBranches.containsKey(GitHelpers.MASTER_BRANCH)) {
            git.checkout().setName(GitHelpers.MASTER_BRANCH).setForce(true).call();
        }

        // Iterate over all local/remote branches
        for (String branch : allBranches) {

            // Delete a local branch that does not exist remotely, but not master 
            boolean allowDelete = allowVersionDelete && !GitHelpers.MASTER_BRANCH.equals(branch);
            if (localBranches.containsKey(branch) && !remoteBranches.containsKey(branch)) {
                if (allowDelete) {
                    LOGGER.debug("Deleting local branch: {}", branch);
                    git.branchDelete().setBranchNames(branch).setForce(true).call();
                    localUpdate = true;
                } else {
                    remoteUpdate = true;
                }
            }

            // Create a local branch that exists remotely
            else if (!localBranches.containsKey(branch) && remoteBranches.containsKey(branch)) {
                LOGGER.debug("Adding local branch: {}", branch);
                git.checkout().setCreateBranch(true).setName(branch).setStartPoint(remoteRef + "/" + branch)
                        .setUpstreamMode(SetupUpstreamMode.TRACK).setForce(true).call();
                versions.add(branch);
                localUpdate = true;
            }

            // Update a local branch that also exists remotely
            else if (localBranches.containsKey(branch) && remoteBranches.containsKey(branch)) {
                ObjectId localObjectId = localBranches.get(branch).getObjectId();
                ObjectId remoteObjectId = remoteBranches.get(branch).getObjectId();
                String localCommit = localObjectId.getName();
                String remoteCommit = remoteObjectId.getName();
                if (!localCommit.equals(remoteCommit)) {
                    git.clean().setCleanDirectories(true).call();
                    git.checkout().setName("HEAD").setForce(true).call();
                    git.checkout().setName(branch).setForce(true).call();
                    MergeResult mergeResult = git.merge().setFastForward(FastForwardMode.FF_ONLY)
                            .include(remoteObjectId).call();
                    MergeStatus mergeStatus = mergeResult.getMergeStatus();
                    LOGGER.debug("Updating local branch {} with status: {}", branch, mergeStatus);
                    if (mergeStatus == MergeStatus.FAST_FORWARD) {
                        localUpdate = true;
                    } else if (mergeStatus == MergeStatus.ALREADY_UP_TO_DATE) {
                        remoteUpdate = true;
                    } else if (mergeStatus == MergeStatus.ABORTED) {
                        LOGGER.debug("Cannot fast forward branch {}, attempting rebase", branch);
                        RebaseResult rebaseResult = git.rebase().setUpstream(remoteCommit).call();
                        RebaseResult.Status rebaseStatus = rebaseResult.getStatus();
                        if (rebaseStatus == RebaseResult.Status.OK) {
                            localUpdate = true;
                            remoteUpdate = true;
                        } else {
                            LOGGER.warn("Rebase on branch {} failed, restoring remote branch", branch);
                            git.rebase().setOperation(Operation.ABORT).call();
                            git.checkout().setName(GitHelpers.MASTER_BRANCH).setForce(true).call();
                            git.branchDelete().setBranchNames(branch).setForce(true).call();
                            git.checkout().setCreateBranch(true).setName(branch)
                                    .setStartPoint(remoteRef + "/" + branch)
                                    .setUpstreamMode(SetupUpstreamMode.TRACK).setForce(true).call();
                            localUpdate = true;
                        }
                    }
                }
                versions.add(branch);
            }
        }

        PullPolicyResult result = new AbstractPullPolicyResult(versions, localUpdate, remoteUpdate, null);
        LOGGER.info("Pull result: {}", result);
        return result;
    } catch (Exception ex) {
        return new AbstractPullPolicyResult(ex);
    }
}

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

License:Apache License

@Override
public synchronized PushPolicyResult doPush(GitContext context, CredentialsProvider credentialsProvider) {

    StoredConfig config = git.getRepository().getConfig();
    String remoteUrl = config.getString("remote", remoteRef, "url");
    if (remoteUrl == null) {
        LOGGER.debug("No remote repository defined, so not doing a push");
        return new AbstractPushPolicyResult();
    }/*from  w  w  w. j  a  v a  2 s  .  c om*/

    LOGGER.info("Pushing last change to: {}", remoteUrl);

    Iterator<PushResult> resit = null;
    Exception lastException = null;
    try {
        resit = git.push().setTimeout(gitTimeout).setCredentialsProvider(credentialsProvider).setPushAll()
                .call().iterator();
    } catch (GitAPIException | JGitInternalException ex) {
        lastException = ex;
    }

    // Allow the commit to stay in the repository in case of push failure
    if (lastException != null) {
        LOGGER.warn("Cannot push because of: {}", lastException.toString());
        return new AbstractPushPolicyResult(lastException);
    }

    List<PushResult> pushResults = new ArrayList<>();
    List<RemoteRefUpdate> acceptedUpdates = new ArrayList<>();
    List<RemoteRefUpdate> rejectedUpdates = new ArrayList<>();

    // Collect the updates that are not ok
    while (resit.hasNext()) {
        PushResult pushResult = resit.next();
        pushResults.add(pushResult);
        for (RemoteRefUpdate refUpdate : pushResult.getRemoteUpdates()) {
            Status status = refUpdate.getStatus();
            if (status == Status.OK || status == Status.UP_TO_DATE) {
                acceptedUpdates.add(refUpdate);
            } else {
                rejectedUpdates.add(refUpdate);
            }
        }
    }

    // Reset to the last known good rev and make the commit/push fail
    for (RemoteRefUpdate rejectedRef : rejectedUpdates) {
        LOGGER.warn("Rejected push: {}" + rejectedRef);
        String refName = rejectedRef.getRemoteName();
        String branch = refName.substring(refName.lastIndexOf('/') + 1);
        try {
            GitHelpers.checkoutBranch(git, branch);
            FetchResult fetchResult = git.fetch().setTimeout(gitTimeout)
                    .setCredentialsProvider(credentialsProvider).setRemote(remoteRef)
                    .setRefSpecs(new RefSpec("refs/heads/" + branch)).call();
            Ref fetchRef = fetchResult.getAdvertisedRef("refs/heads/" + branch);
            git.branchRename().setOldName(branch).setNewName(branch + "-tmp").call();
            git.checkout().setCreateBranch(true).setName(branch).setStartPoint(fetchRef.getObjectId().getName())
                    .call();
            git.branchDelete().setBranchNames(branch + "-tmp").setForce(true).call();
        } catch (GitAPIException ex) {
            LOGGER.warn("Cannot reset branch {}, because of: {}", branch, ex.toString());
        }
    }

    PushPolicyResult result = new AbstractPushPolicyResult(pushResults, acceptedUpdates, rejectedUpdates,
            lastException);
    LOGGER.info("Push result: {}", result);
    return result;
}

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

License:Apache License

/**
 * Pushes any committed changes to the remote repo
 *//*  w w  w .j a va2  s.c  o m*/
protected Iterable<PushResult> doPush(Git git, GitContext gitContext, CredentialsProvider credentialsProvider)
        throws Exception {
    assertValid();
    try {
        Repository repository = git.getRepository();
        StoredConfig config = repository.getConfig();
        String url = config.getString("remote", remoteRef.get(), "url");
        if (Strings.isNullOrBlank(url)) {
            LOG.info("No remote repository defined yet for the git repository at "
                    + GitHelpers.getRootGitDirectory(git) + " so not doing a push");
            return Collections.emptyList();
        }

        return git.push().setTimeout(gitTimeout).setCredentialsProvider(credentialsProvider).setPushAll()
                .call();
    } catch (Throwable ex) {
        // log stacktrace at debug level
        LOG.warn("Failed to push from the remote git repo " + GitHelpers.getRootGitDirectory(git) + " due "
                + ex.getMessage() + ". This exception is ignored.");
        LOG.debug("Failed to push from the remote git repo " + GitHelpers.getRootGitDirectory(git)
                + ". This exception is ignored.", ex);
        return Collections.emptyList();
    }
}

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   ww w.ja  va  2s .  c o  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

protected static void configureBranch(Git git, String branch, String remote) {
    // lets update the merge config
    if (Strings.isNotBlank(branch)) {
        StoredConfig config = git.getRepository().getConfig();
        if (Strings.isNullOrBlank(config.getString("branch", branch, "remote"))
                || Strings.isNullOrBlank(config.getString("branch", branch, "merge"))) {
            config.setString("branch", branch, "remote", remote);
            config.setString("branch", branch, "merge", "refs/heads/" + branch);
            try {
                config.save();//from   w w w  .j  a v  a 2 s.  co m
            } catch (IOException e) {
                LOGGER.error("Failed to configure the branch configuration to " + getRootGitDirectory(git)
                        + " with branch " + branch + " on remote repo: " + remote + ". " + e, e);
            }
        }
    }
}

From source file:io.fabric8.itests.basic.git.GitUtils.java

License:Apache License

public static String getRemote(Git git, String remote) throws GitAPIException {
    StoredConfig config = git.getRepository().getConfig();
    return config.getString("remote", remote, "url");
}

From source file:io.fabric8.maven.CreateBranchMojo.java

License:Apache License

protected void configureBranch(String branch) {
    // lets update the merge config
    if (Strings.isNotBlank(branch) && hasRemoteRepo()) {
        StoredConfig config = git.getRepository().getConfig();
        if (Strings.isNullOrBlank(config.getString("branch", branch, "remote"))
                || Strings.isNullOrBlank(config.getString("branch", branch, "merge"))) {
            config.setString("branch", branch, "remote", remoteName);
            config.setString("branch", branch, "merge", "refs/heads/" + branch);
            try {
                config.save();//  w w w. j a  v  a  2  s  .c o m
            } catch (IOException e) {
                getLog().error("Failed to save the git configuration into " + new File(buildDir, ".git")
                        + " with branch " + branch + " on remote repo: " + gitUrl + " due: " + e.getMessage()
                        + ". This exception is ignored.", e);
            }
        }
    }
}

From source file:io.fabric8.maven.CreateBranchMojo.java

License:Apache License

/**
 * Returns true if the remote git url is defined or the local git repo has a remote url defined
 *//*from   w ww .j  a  va2s.  c o m*/
protected boolean hasRemoteRepo() {
    if (Strings.isNotBlank(gitUrl)) {
        return true;
    }
    Repository repository = git.getRepository();
    StoredConfig config = repository.getConfig();
    String url = config.getString("remote", remoteName, "url");
    if (Strings.isNotBlank(url)) {
        return true;
    }
    return false;
}

From source file:io.fabric8.maven.CreateBranchMojo.java

License:Apache License

protected void doPull() throws MojoExecutionException {
    //CredentialsProvider cp = getCredentials();
    CredentialsProvider cp = null;/*from   ww  w  .  j av  a2 s . c  o  m*/
    try {
        Repository repository = git.getRepository();
        StoredConfig config = repository.getConfig();
        String url = config.getString("remote", "origin", "url");
        if (Strings.isNullOrBlank(url)) {
            getLog().info("No remote repository defined for the git repository at "
                    + getGitBuildPathDescription() + " so not doing a pull");
            return;
        }
        String branch = repository.getBranch();
        String mergeUrl = config.getString("branch", branch, "merge");
        if (Strings.isNullOrBlank(mergeUrl)) {
            getLog().info("No merge spec for branch." + branch + ".merge in the git repository at "
                    + getGitBuildPathDescription() + " so not doing a pull");
            return;
        }
        getLog().info("Performing a pull in git repository " + getGitBuildPathDescription() + " on remote URL: "
                + url);

        git.pull().setCredentialsProvider(cp).setRebase(true).call();
    } catch (Throwable e) {
        String credText = "";
        if (cp instanceof UsernamePasswordCredentialsProvider) {
        }
        String message = "Failed to pull from the remote git repo with credentials " + cp + " due: "
                + e.getMessage() + ". This exception is ignored.";
        getLog().error(message, e);
        throw new MojoExecutionException(message, e);
    }
}

From source file:io.fabric8.project.support.GitUtils.java

License:Apache License

public static String getRemoteURL(Repository repository, String remoteName) {
    if (repository != null) {
        StoredConfig config = repository.getConfig();
        if (config != null) {
            return config.getString("remote", remoteName, "url");
        }/*from   w ww  .j a  v a 2 s .  com*/
    }
    return null;
}