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:com.microsoft.tfs.client.common.ui.teambuild.egit.repositories.GitRepositoriesMap.java

License:Open Source License

private Map<String, String> getMappedBranches(final TfsGitRepositoryJson serverRepository,
        final Repository localRepository) {
    Map<String, String> mappedBranches = null;
    String upstreamURL = serverRepository.getRemoteUrl();
    try {//from   w  w w  .j av a 2  s.  c om
        upstreamURL = URIUtil.encodePath(serverRepository.getRemoteUrl());
    } catch (final URIException e) {
        log.error("Error encoding repository URL " + upstreamURL, e); //$NON-NLS-1$
    }

    final StoredConfig repositoryConfig = localRepository.getConfig();
    final Set<String> remotes = repositoryConfig.getSubsections(REMOTES_SECTION_NAME);

    for (final String remoteName : remotes) {
        final String remoteURL = repositoryConfig.getString(REMOTES_SECTION_NAME, remoteName, URL_VALUE_NAME);

        if (remoteURL != null && remoteURL.equalsIgnoreCase(upstreamURL)) {
            if (mappedBranches == null) {
                mappedBranches = new HashMap<String, String>();
            }

            final Set<String> branches = repositoryConfig.getSubsections(BRANCHES_SECTION_NAME);

            for (final String branch : branches) {
                final String fullBranchName = Constants.R_HEADS + branch;

                final String[] remoteNames = repositoryConfig.getStringList(BRANCHES_SECTION_NAME, branch,
                        REMOTE_VALUE_NAME);
                final String[] mappedBrancheNames = repositoryConfig.getStringList(BRANCHES_SECTION_NAME,
                        branch, MERGE_VALUE_NAME);

                for (int k = 0; k < remoteNames.length; k++) {
                    if (remoteNames[k].equals(remoteName)) {
                        final String remoteBranchName = mappedBrancheNames[k];

                        if (!mappedBranches.containsKey(remoteBranchName)) {
                            mappedBranches.put(remoteBranchName, fullBranchName);
                        }

                        break;
                    }
                }
            }

            break;
        }
    }

    return mappedBranches;
}

From source file:com.microsoft.tfs.client.eclipse.ui.egit.teamexplorer.TeamExplorerGitRepositoriesSection.java

License:Open Source License

private void loadRegisteredRepositories() {
    repositoryMap = new TreeMap<String, Repository>();
    final List<String> repositoryFolders = Activator.getDefault().getRepositoryUtil()
            .getConfiguredRepositories();

    for (final String repositoryFolder : repositoryFolders) {
        final File folder = new File(repositoryFolder);
        if (!folder.exists() || !folder.isDirectory()) {
            continue;
        }// www . ja va  2 s . c  o m

        if (!folder.getName().equals(Constants.DOT_GIT) || !FileKey.isGitRepository(folder, FS.DETECTED)) {
            continue;
        }

        final RepositoryBuilder rb = new RepositoryBuilder().setGitDir(folder).setMustExist(true);

        try {
            final Repository repo = rb.build();
            final StoredConfig repositoryConfig = repo.getConfig();
            final Set<String> remotes = repositoryConfig.getSubsections(REMOTES_SECTION_NAME);

            for (final String remoteName : remotes) {
                final String remoteURL = repositoryConfig.getString(REMOTES_SECTION_NAME, remoteName,
                        URL_VALUE_NAME);
                repositoryMap.put(remoteURL, repo);
            }
        } catch (final Exception e) {
            log.error("Error loading local Git repository " + repositoryFolder, e); //$NON-NLS-1$
            continue;
        }
    }
}

From source file:com.osbitools.ws.shared.prj.web.AbstractWsPrjInit.java

License:LGPL

@Override
public void contextInitialized(ServletContextEvent evt) {
    super.contextInitialized(evt);
    ServletContext ctx = evt.getServletContext();

    // First - Load Custom Error List 
    try {//from   w w w  .  j  a va2 s .c  om
        Class.forName("com.osbitools.ws.shared.prj.CustErrorList");
    } catch (ClassNotFoundException e) {
        // Ignore Error 
    }

    // Initialize Entity Utils
    IEntityUtils eut = getEntityUtils();
    ctx.setAttribute("entity_utils", eut);

    // Initiate LangSetFileUtils
    ctx.setAttribute("ll_set_utils", new LangSetUtils());

    // Check if git repository exists and create one
    // Using ds subdirectory as git root repository 
    File drepo = new File(
            getConfigDir(ctx) + File.separator + eut.getPrjRootDirName() + File.separator + ".git");
    Git git;
    try {

        if (!drepo.exists()) {
            if (!drepo.mkdirs())
                throw new RuntimeErrorException(
                        new Error("Unable create directory '" + drepo.getAbsolutePath() + "'"));

            try {
                git = createGitRepo(drepo);
            } catch (Exception e) {
                throw new RuntimeErrorException(new Error(
                        "Unable create new repo on path: " + drepo.getAbsolutePath() + ". " + e.getMessage()));
            }

            getLogger(ctx).info("Created new git repository '" + drepo.getAbsolutePath() + "'");
        } else if (!drepo.isDirectory()) {
            throw new RuntimeErrorException(
                    new Error(drepo.getAbsolutePath() + " is regular file and not a directory"));
        } else {
            git = Git.open(drepo);
            getLogger(ctx).debug("Open existing repository " + drepo.getAbsolutePath());
        }
    } catch (IOException e) {
        // Something unexpected and needs to be analyzed
        e.printStackTrace();

        throw new RuntimeErrorException(new Error(e));
    }

    // Save git handler
    ctx.setAttribute("git", git);

    // Check if remote destination set/changed
    StoredConfig config = git.getRepository().getConfig();
    String rname = (String) ctx.getAttribute(PrjMgrConstants.PREMOTE_GIT_NAME);
    String rurl = (String) ctx.getAttribute("git_remote_url");

    if (!Utils.isEmpty(rname) && !Utils.isEmpty(rurl)) {
        String url = config.getString("remote", rname, "url");
        if (!rurl.equals(url)) {
            config.setString("remote", rname, "url", rurl);
            try {
                config.save();
            } catch (IOException e) {
                getLogger(ctx).error("Error saving git remote url. " + e.getMessage());
            }
        }
    }

    // Temp directory for files upload
    String tname = System.getProperty("java.io.tmpdir");
    getLogger(ctx).info("Using temporarily directory '" + tname + "' for file uploads");
    File tdir = new File(tname);

    if (!tdir.exists())
        throw new RuntimeErrorException(
                new Error("Temporarily directory for file upload '" + tname + "' is not found"));
    if (!tdir.isDirectory())
        throw new RuntimeErrorException(
                new Error("Temporarily directory for file upload '" + tname + "' is not a directory"));

    DiskFileItemFactory dfi = new DiskFileItemFactory();
    dfi.setSizeThreshold(
            ((Integer) ctx.getAttribute(PrjMgrConstants.SMAX_FILE_UPLOAD_SIZE_NAME)) * 1024 * 1024);
    dfi.setRepository(tdir);
    evt.getServletContext().setAttribute("dfi", dfi);

    // Save entity utils in context
    evt.getServletContext().setAttribute("entity_utils", getEntityUtils());
}

From source file:com.pieceof8.gradle.snapshot.GitScmProvider.java

License:Apache License

/** {@inheritDoc} */
@Override/*from w ww  . j av  a2s. c om*/
@SneakyThrows(IOException.class)
public Commit getCommit() {
    if (repoDir == null) {
        throw new IllegalArgumentException("'repoDir' must not be null");
    }
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    @Cleanup
    Repository repo = builder.setGitDir(repoDir).readEnvironment().findGitDir().build();
    StoredConfig conf = repo.getConfig();

    int abbrev = Commit.ABBREV_LENGTH;
    if (conf != null) {
        abbrev = conf.getInt("core", "abbrev", abbrev);
    }

    val sdf = new SimpleDateFormat(extension.getDateFormat());

    val HEAD = repo.getRef(Constants.HEAD);
    if (HEAD == null) {
        val msg = "Could not get HEAD Ref, the repository may be corrupt.";
        throw new RuntimeException(msg);
    }

    RevWalk revWalk = new RevWalk(repo);
    if (HEAD.getObjectId() == null) {
        val msg = "Could not find any commits from HEAD ref.";
        throw new RuntimeException(msg);
    }
    RevCommit commit = revWalk.parseCommit(HEAD.getObjectId());
    revWalk.markStart(commit);

    try {
        // git commit time in sec and java datetime is in ms
        val commitTime = new Date(commit.getCommitTime() * 1000L);
        val ident = commit.getAuthorIdent();

        return new Commit(sdf.format(new Date()), // build time
                conf.getString("user", null, "name"), conf.getString("user", null, "email"), repo.getBranch(),
                commit.getName(), sdf.format(commitTime), ident.getName(), ident.getEmailAddress(),
                commit.getFullMessage().trim());
    } finally {
        revWalk.dispose();
    }
}

From source file:com.puppetlabs.geppetto.forge.jenkins.RepositoryInfo.java

License:Open Source License

/**
 * Obtains the remote URL that is referenced by the given <code>branchName</code>
 *
 * @return The URL or <code>null</code> if it hasn't been configured
 *         for the given branch.// www  .  j ava  2 s .c o m
 */
public static String getRemoteURL(Repository repository) throws IOException {
    StoredConfig repoConfig = repository.getConfig();
    String configuredRemote = repoConfig.getString(ConfigConstants.CONFIG_BRANCH_SECTION,
            repository.getBranch(), ConfigConstants.CONFIG_KEY_REMOTE);
    return configuredRemote == null ? null
            : repoConfig.getString(ConfigConstants.CONFIG_REMOTE_SECTION, configuredRemote,
                    ConfigConstants.CONFIG_KEY_URL);
}

From source file:com.surevine.gateway.scm.git.jgit.JGitGitFacade.java

License:Open Source License

@Override
public Map<String, String> getRemotes(final LocalRepoBean repoBean) throws GitException {
    Map<String, String> remotes = new HashMap<String, String>();
    try {/*from   w w  w  .  jav  a  2  s  .c o m*/
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setGitDir(repoBean.getGitConfigDirectory().toFile()).findGitDir()
                .build();
        Git git = new org.eclipse.jgit.api.Git(repository);
        StoredConfig config = git.getRepository().getConfig();
        Set<String> remoteNames = config.getSubsections("remote");
        for (String remoteName : remoteNames) {
            remotes.put(remoteName, config.getString("remote", remoteName, "url"));
        }
    } catch (IOException e) {
        LOGGER.error(e);
        throw new GitException(e);
    }
    return remotes;
}

From source file:de.fau.osr.core.vcs.impl.GitVcsClient.java

License:Open Source License

/**
 * This method returns the current repository name.This method is used in setting the file name for file export options.
 * @return// ww  w . j  a  v a2s  .c om
 */
@Override
public String getRepositoryName() {
    StoredConfig c = repo.getConfig();
    try {
        String url = c.getString("remote", "origin", "url");
        if (url != null && !url.isEmpty()) {
            return url.substring(url.lastIndexOf('/') + 1);
        }
    } catch (Exception e) {
        e.printStackTrace();

    }
    return ".git";
}

From source file:edu.wustl.lookingglass.community.CommunityRepository.java

License:Open Source License

private void addRemote(String newName, URL newURL) throws IOException, URISyntaxException {
    assert this.remoteName != null;
    assert this.remoteURL != null;

    boolean remoteExists = false;
    StoredConfig config = this.git.getRepository().getConfig();
    Set<String> remotes = config.getSubsections("remote");
    for (String oldName : remotes) {
        String oldURL = config.getString("remote", oldName, "url");
        if (newName.equals(oldName)) {
            remoteExists = true;/*from  ww  w.  j  a v a  2s.  c o m*/
            if (newURL.toExternalForm().equals(oldURL)) {
                break;
            } else {
                Logger.warning("inconsistent remote url " + oldName + " : " + oldURL);
                config.setString("remote", oldName, "url", newURL.toExternalForm());
                config.save();
                break;
            }
        }
    }

    if (!remoteExists) {
        RemoteConfig remoteConfig = new RemoteConfig(config, this.remoteName);
        remoteConfig.addURI(new URIish(this.remoteURL));
        remoteConfig.addFetchRefSpec(new RefSpec("+refs/heads/*:refs/remotes/" + this.remoteName + "/*"));
        remoteConfig.update(config);
        config.save();
    }
}

From source file:eu.cloud4soa.cli.roo.addon.commands.GitManager.java

License:Apache License

public void setConfig() throws URISyntaxException, IOException, GitAPIException {
    StoredConfig config = gitRepository.getConfig();

    if (config.getString("remote", repoName, "url") == null
            || config.getString("remote", repoName, "url") != gitProxyUrl) {
        config.unset("remote", repoName, "url");
        RemoteConfig remoteConfig = new RemoteConfig(config, repoName);
        //cloud@94.75.243.141/proxyname.git
        //proxy<userid><applicationid>.git?
        //        String gitUrl = gitUser+"@"+gitProxyUrl+"/proxy"+this.userId+this.applicationId+".git";
        URIish uri = new URIish(gitProxyUrl);
        remoteConfig.addURI(uri);/*from  w w w .  jav  a  2 s .  c  o m*/
        config.unset("remote", repoName, "fetch");
        RefSpec spec = new RefSpec("+refs/heads/*:refs/remotes/" + repoName + "/*");
        remoteConfig.addFetchRefSpec(spec);
        remoteConfig.update(config);
    }

    if (config.getString("branch", "master", "remote") == null
            || config.getString("branch", "master", "remote") != repoName) {
        config.unset("branch", "master", "remote");
        config.setString("branch", "master", "remote", repoName);
    }
    if (config.getString("branch", "master", "merge") == null
            || config.getString("branch", "master", "merge") != "refs/heads/master") {
        config.unset("branch", "master", "merge");
        config.setString("branch", "master", "merge", "refs/heads/master");
    }
    config.save();
}

From source file:git_manager.tool.GitOperations.java

License:Open Source License

public void getConfigParameters() {
    StoredConfig config = git.getRepository().getConfig();
    String name = config.getString("user", null, "name");
    String email = config.getString("user", null, "email");
    if (name != null && email != null) {
        Object[] options = { "Yes", "No" };
        // TODO: Probably get this on the EDT instead
        int n = JOptionPane.showOptionDialog(new JFrame(),
                "The following global " + "user details have been detected:\n    Name: " + name
                        + "\n    Email: " + email + "\n\nContinue with these details?",
                "Who's there?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options,
                options[1]);/*from  w  w w  . j a  v  a2  s. c  o  m*/
        if (n == JOptionPane.YES_OPTION) {
            return;
        }
    }

    // TODO: Definitely make this nicer- better parsing and error handling, etc.
    // TODO: On the EDT with this too!
    // Adapted from http://www.edu4java.com/en/swing/swing3.html
    name = "";
    email = "";
    while (name.isEmpty() || email.isEmpty()) {
        JPanel configPanel = new JPanel();
        configPanel.setLayout(null);
        configPanel.setPreferredSize(new Dimension(300, 80));

        JLabel nameLabel = new JLabel("Name");
        nameLabel.setBounds(10, 10, 80, 25);
        configPanel.add(nameLabel);

        JTextField nameText = new JTextField(20);
        nameText.setBounds(100, 10, 160, 25);
        configPanel.add(nameText);
        nameText.setText(name);

        JLabel emailLabel = new JLabel("Email");
        emailLabel.setBounds(10, 40, 80, 25);
        configPanel.add(emailLabel);

        JTextField emailText = new JTextField(20);
        emailText.setBounds(100, 40, 160, 25);
        configPanel.add(emailText);
        emailText.setText(email);

        JOptionPane.showMessageDialog(new JFrame(), configPanel, "User details", JOptionPane.PLAIN_MESSAGE,
                null);

        name = nameText.getText();
        email = emailText.getText();

        if (name.isEmpty() || email.isEmpty()) {
            JOptionPane.showMessageDialog(new JFrame(),
                    "Neither the name nor the email address can be left blank", "Nopes",
                    JOptionPane.ERROR_MESSAGE, null);
        }
    }

    config.setString("user", null, "name", name);
    config.setString("user", null, "email", email);
    try {
        config.save();
    } catch (IOException e) {
        e.printStackTrace();
    }
}