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:org.eclipse.egit.ui.internal.variables.GitTemplateVariableResolver.java

License:Open Source License

/**
 * Resolves the git_config variable for a project
 *
 * @param variable/* ww  w  .  jav a  2 s. co m*/
 *            the current template variable.
 * @param project
 *            the current project.
 */
protected static void resolveVariable(TemplateVariable variable, IProject project) {
    final List<String> params = variable.getVariableType().getParams();
    if (params.isEmpty()) {
        variable.setValue(""); //$NON-NLS-1$
        return;
    }

    final String gitKey = params.get(0);
    if (gitKey == null || gitKey.length() == 0) {
        variable.setValue(""); //$NON-NLS-1$
        return;
    }

    // Get git's config
    RepositoryMapping mapping = RepositoryMapping.getMapping(project);
    Repository repository = null;

    if (mapping != null) {
        repository = mapping.getRepository();
    }
    if (repository == null) {
        variable.setValue(""); //$NON-NLS-1$
        return;
    }

    StoredConfig config = repository.getConfig();

    // Get the value of the key
    final String[] splits = gitKey.split("\\."); //$NON-NLS-1$
    String section = null;
    String subSection = null;
    String name = null;

    if (splits.length == 3) {
        section = splits[0];
        subSection = splits[1];
        name = splits[2];
    } else if (splits.length == 2) {
        section = splits[0];
        name = splits[1];
    } else {
        variable.setValue(""); //$NON-NLS-1$
        return;
    }

    String gitValue = config.getString(section, subSection, name);
    if (gitValue != null) {
        variable.setValue(gitValue);
    }
}

From source file:org.eclipse.oomph.gitbash.decorators.BranchDecorator.java

License:Open Source License

private String getDecoration(org.eclipse.egit.ui.internal.repository.tree.RefNode node) {
    String branchName = Repository.shortenRefName(node.getObject().getName());
    Repository repository = node.getRepository();
    StoredConfig config = repository.getConfig();

    String branch = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
            ConfigConstants.CONFIG_KEY_MERGE);

    if (branch != null) {
        String remote = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
                ConfigConstants.CONFIG_KEY_REMOTE);

        boolean rebaseFlag = config.getBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
                ConfigConstants.CONFIG_KEY_REBASE, false);

        if (branch.startsWith(DEFAULT_PATH)) {
            branch = branch.substring(DEFAULT_PATH.length());
        }//from   w  w w  .  j a v a2s.c o m

        String prefix = ".".equals(remote) ? "" : remote + "/";
        String result = (rebaseFlag ? "REBASE" : "MERGE") + ": " + prefix + branch;

        try {
            BranchTrackingStatus trackingStatus = BranchTrackingStatus.of(repository, branchName);
            if (trackingStatus != null
                    && (trackingStatus.getAheadCount() != 0 || trackingStatus.getBehindCount() != 0)) {
                result += " " + formatBranchTrackingStatus(trackingStatus);
            }
        } catch (Throwable t) {
            //$FALL-THROUGH$
        }

        return result;
    }

    return null;
}

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

License:Open Source License

@Test
public void testClonedRepoConfigUsingUserProfile() throws Exception {
    // set Git name and mail in the user profile
    WebRequest request = getPutUserRequest();
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // clone a  repo
    URI workspaceLocation = createWorkspace(getMethodName());
    JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(), null);
    IPath clonePath = new Path("file").append(project.getString(ProtocolConstants.KEY_ID)).makeAbsolute();

    String contentLocation = clone(clonePath).getString(ProtocolConstants.KEY_CONTENT_LOCATION);

    // check the repository configuration using JGit API
    Git git = new Git(getRepositoryForContentLocation(contentLocation));
    StoredConfig config = git.getRepository().getConfig();
    assertEquals(GIT_NAME,//from  w w w .  j  a v  a 2 s  .c  o m
            config.getString(ConfigConstants.CONFIG_USER_SECTION, null, ConfigConstants.CONFIG_KEY_NAME));
    assertEquals(GIT_MAIL,
            config.getString(ConfigConstants.CONFIG_USER_SECTION, null, ConfigConstants.CONFIG_KEY_EMAIL));

    // now check if commits have the right committer set

    request = getGetFilesRequest(project.getString(ProtocolConstants.KEY_CONTENT_LOCATION));
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    project = new JSONObject(response.getText());
    String childrenLocation = project.getString(ProtocolConstants.KEY_CHILDREN_LOCATION);
    assertNotNull(childrenLocation);

    // check if Git locations are in place
    JSONObject gitSection = project.optJSONObject(GitConstants.KEY_GIT);
    assertNotNull(gitSection);
    String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);
    String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);

    // modify
    String projectLocation = project.getString(ProtocolConstants.KEY_LOCATION);
    request = getPutFileRequest(projectLocation + "/test.txt", "change to commit");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // add
    request = GitAddTest.getPutGitIndexRequest(gitIndexUri + "test.txt");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // commit all
    request = GitCommitTest.getPostGitCommitRequest(gitHeadUri /* all */, GIT_COMMIT_MESSAGE, false);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // log
    // TODO: replace with RESTful API for git log when available
    Iterable<RevCommit> commits = git.log().call();
    PersonIdent testIdent = new PersonIdent(GIT_NAME, GIT_MAIL);
    PersonIdent[] expectedIdents = new PersonIdent[] { testIdent };
    int c = 0;
    for (RevCommit commit : commits) {
        if (commit.getFullMessage().equals(GIT_COMMIT_MESSAGE)) {
            assertEquals(expectedIdents[expectedIdents.length - 1 - c].getName(),
                    commit.getCommitterIdent().getName());
            assertEquals(expectedIdents[expectedIdents.length - 1 - c].getEmailAddress(),
                    commit.getCommitterIdent().getEmailAddress());
        }
        c++;
    }
    assertEquals(2, c);
}

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

License:Open Source License

@Test
public void testInitializedRepoConfigUsingUserProfile() throws Exception {
    // set Git name and mail in the user profile
    WebRequest request = getPutUserRequest();
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // init a repo
    URI workspaceLocation = createWorkspace(getMethodName());
    JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(), null);
    IPath initPath = new Path("file").append(project.getString(ProtocolConstants.KEY_ID)).makeAbsolute();

    String contentLocation = init(null, initPath, null).getString(ProtocolConstants.KEY_CONTENT_LOCATION);

    // check the repository configuration using JGit API
    Git git = new Git(getRepositoryForContentLocation(contentLocation));
    StoredConfig config = git.getRepository().getConfig();
    assertEquals(GIT_NAME,/*from  ww w.  j a  v a 2s . com*/
            config.getString(ConfigConstants.CONFIG_USER_SECTION, null, ConfigConstants.CONFIG_KEY_NAME));
    assertEquals(GIT_MAIL,
            config.getString(ConfigConstants.CONFIG_USER_SECTION, null, ConfigConstants.CONFIG_KEY_EMAIL));

    // now check if commits have the right committer set

    request = getGetFilesRequest(project.getString(ProtocolConstants.KEY_CONTENT_LOCATION));
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    project = new JSONObject(response.getText());
    String childrenLocation = project.getString(ProtocolConstants.KEY_CHILDREN_LOCATION);
    assertNotNull(childrenLocation);

    // check if Git locations are in place
    JSONObject gitSection = project.optJSONObject(GitConstants.KEY_GIT);
    assertNotNull(gitSection);
    String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);
    String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);

    // modify
    String projectLocation = project.getString(ProtocolConstants.KEY_LOCATION);
    request = getPutFileRequest(projectLocation + "/test.txt", "change to commit");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // add
    request = GitAddTest.getPutGitIndexRequest(gitIndexUri + "test.txt");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // commit all
    request = GitCommitTest.getPostGitCommitRequest(gitHeadUri /* all */, GIT_COMMIT_MESSAGE, false);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // log
    // TODO: replace with RESTful API for git log when available
    Iterable<RevCommit> commits = git.log().call();
    PersonIdent testIdent = new PersonIdent(GIT_NAME, GIT_MAIL);
    PersonIdent[] expectedIdents = new PersonIdent[] { testIdent };
    int c = 0;
    for (RevCommit commit : commits) {
        if (commit.getFullMessage().equals(GIT_COMMIT_MESSAGE)) {
            assertEquals(expectedIdents[expectedIdents.length - 1 - c].getName(),
                    commit.getCommitterIdent().getName());
            assertEquals(expectedIdents[expectedIdents.length - 1 - c].getEmailAddress(),
                    commit.getCommitterIdent().getEmailAddress());
        }
        c++;
    }
    assertEquals(2, c);
}

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

License:Open Source License

@Test
public void testSyncSubmodule()
        throws IOException, SAXException, JSONException, CoreException, ConfigInvalidException {
    createWorkspace(SimpleMetaStore.DEFAULT_WORKSPACE_NAME);
    String workspaceId = getWorkspaceId(workspaceLocation);

    JSONObject project = createProjectOrLink(workspaceLocation, getMethodName().concat("Project1"), null);
    JSONObject clone = clone(workspaceId, project);
    String contentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION);
    String submoduleLocation = clone.getString(GitConstants.KEY_SUBMODULE);
    String location = clone.getString(ProtocolConstants.KEY_LOCATION);

    Repository repository = getRepositoryForContentLocation(contentLocation);
    File file = new File(repository.getWorkTree(), DOT_GIT_MODULES);
    assertFalse(file.exists());/*ww w  .j a va2 s.  c  om*/

    URIish uri = new URIish(gitDir.toURI().toURL());
    WebRequest request = postSubmoduleRequest(submoduleLocation, "test", uri.toString(), location);
    WebResponse response = webConversation.getResponse(request);

    file = new File(repository.getWorkTree(), DOT_GIT_MODULES);
    assertTrue(file.exists());

    assertNotNull(repository);

    StoredConfig repoConfig = repository.getConfig();
    String originalUrl = repoConfig.getString("submodule", "test", "url");
    repoConfig.setString("submodule", "test", "url", "value");
    repoConfig.save();
    assertEquals(repoConfig.getString("submodule", "test", "url"), "value");

    WebRequest reqSync = putSubmoduleRequest(submoduleLocation, "sync");
    WebResponse resSync = webConversation.getResponse(reqSync);

    repoConfig = repository.getConfig();
    assertEquals(repoConfig.getString("submodule", "test", "url"), originalUrl);

}

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

License:Open Source License

@RemoteInvocation
public ConfigBranchPageDto getConfigBranchData(ServiceInvocationContext context, List<PathFragment> path) {
    try {//from   w  w  w.j  av  a 2s  .c o m
        RefNode node = (RefNode) GenericTreeStatefulService.getNodeByPathFor(path, null);
        Repository repository = node.getRepository();

        StoredConfig config = repository.getConfig();

        ConfigBranchPageDto dto = new ConfigBranchPageDto();

        Ref branch = (Ref) node.getRef();
        dto.setRef(new GitRef(branch.getName(), Repository.shortenRefName(branch.getName())));

        List<RemoteConfig> remotes = getAllRemotes(context, path);

        String branchName = branch.getName().substring(Constants.R_HEADS.length());
        String branchConfig = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
                ConfigConstants.CONFIG_KEY_MERGE);

        String remoteConfig = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
                ConfigConstants.CONFIG_KEY_REMOTE);
        if (remoteConfig == null) {
            remoteConfig = "";
        }
        if (remotes != null) {
            dto.setRemotes(remotes);

            for (RemoteConfig remote : remotes) {
                if (remote.getName().equals(remoteConfig)) {
                    List<Object> branches = getBranches(context, remote.getUri());
                    if (branches != null) {
                        @SuppressWarnings("unchecked")
                        List<GitRef> refs = (List<GitRef>) branches.get(0);
                        for (GitRef ref : refs) {
                            if (ref.getName().equals(branchConfig)) {
                                dto.setSelectedRef(ref);
                                break;
                            }
                        }
                        dto.setRefs(refs);
                    }
                    dto.setSelectedRemote(remote);
                    break;
                }
            }
        }

        boolean rebaseFlag = config.getBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
                ConfigConstants.CONFIG_KEY_REBASE, false);
        dto.setRebase(rebaseFlag);

        return dto;
    } catch (Exception e) {
        logger.debug(CommonPlugin.getInstance().getMessage("error"), path, e);
        context.getCommunicationChannel().appendOrSendCommand(
                new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"),
                        e.getMessage(), DisplaySimpleMessageClientCommand.ICON_ERROR));
        return null;
    }
}

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

License:Apache License

/**
 * Pushes any committed changes to the remote repo
 *//*from  w  w w .j a  v  a  2  s  . c om*/
protected Iterable<PushResult> doPush(Git git, GitContext gitContext, CredentialsProvider credentialsProvider)
        throws Exception {
    assertValid();
    Repository repository = git.getRepository();
    StoredConfig config = repository.getConfig();
    String url = config.getString("remote", remote, "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.EMPTY_LIST;
    }

    String branch = gitContext != null && gitContext.getPushBranch() != null ? gitContext.getPushBranch()
            : GitHelpers.currentBranch(git);
    if (!branch.equals(MASTER_BRANCH)) {
        return git.push().setCredentialsProvider(credentialsProvider)
                .setRefSpecs(new RefSpec(MASTER_BRANCH), new RefSpec(branch)).call();
    } else {
        return git.push().setCredentialsProvider(credentialsProvider).setRefSpecs(new RefSpec(branch)).call();
    }
}

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  ww w.j a  v  a2 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);
    }
}

From source file:org.fusesource.fabric.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();//  w  ww  . jav a 2  s  .co  m
            } catch (IOException e) {
                LOG.error("Failed to configure the branch configuration to " + getRootGitDirectory(git)
                        + " with branch " + branch + " on remote repo: " + remote + ". " + e, e);
            }
        }
    }
}

From source file:org.jboss.as.server.controller.git.GitRepository.java

License:Apache License

private String findRemoteName(String gitRepository) {
    if (isValidRemoteName(gitRepository)) {
        return gitRepository;
    }/*from w ww.j a va  2  s .  c  o  m*/
    StoredConfig config = repository.getConfig();
    for (String remoteName : repository.getRemoteNames()) {
        if (gitRepository.equals(config.getString("remote", remoteName, "url"))) {
            return remoteName;
        }
    }
    return null;
}