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:jetbrains.buildServer.buildTriggers.vcs.git.GitServerUtil.java

License:Apache License

/**
 * Ensures that a bare repository exists at the specified path.
 * If it does not, the directory is attempted to be created.
 *
 * @param dir    the path to the directory to init
 * @param remote the remote URL/*from   w w  w . ja v a 2 s.  c o m*/
 * @return a connection to repository
 * @throws VcsException if the there is a problem with accessing VCS
 */
public static Repository getRepository(@NotNull final File dir, @NotNull final URIish remote)
        throws VcsException {
    if (dir.exists() && !dir.isDirectory()) {
        throw new VcsException("The specified path is not a directory: " + dir);
    }
    try {
        ensureRepositoryIsValid(dir);
        Repository r = new RepositoryBuilder().setBare().setGitDir(dir).build();
        if (!new File(dir, "config").exists()) {
            r.create(true);
            final StoredConfig config = r.getConfig();
            config.setString("teamcity", null, "remote", remote.toString());
            config.save();
        } else {
            final StoredConfig config = r.getConfig();
            final String existingRemote = config.getString("teamcity", null, "remote");
            if (existingRemote != null && !remote.toString().equals(existingRemote)) {
                throw getWrongUrlError(dir, existingRemote, remote);
            } else if (existingRemote == null) {
                config.setString("teamcity", null, "remote", remote.toString());
                config.save();
            }
        }
        return r;
    } catch (Exception ex) {
        if (ex instanceof NullPointerException)
            LOG.warn("The repository at directory '" + dir + "' cannot be opened or created", ex);
        throw new VcsException("The repository at directory '" + dir + "' cannot be opened or created, reason: "
                + ex.toString(), ex);
    }
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.MirrorManagerImpl.java

License:Apache License

@Nullable
private String getRemoteRepositoryUrl(@NotNull final File repositoryDir) {
    try {/*www . j av a 2  s. co m*/
        Repository r = new RepositoryBuilder().setBare().setGitDir(repositoryDir).build();
        StoredConfig config = r.getConfig();
        String teamcityRemote = config.getString("teamcity", null, "remote");
        if (teamcityRemote != null)
            return teamcityRemote;
        return config.getString("remote", "origin", "url");
    } catch (Exception e) {
        LOG.warn("Error while trying to get remote repository url at " + repositoryDir.getAbsolutePath(), e);
        return null;
    }
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.submodules.SubmoduleResolverImpl.java

License:Apache License

@NotNull
private static String resolveSubmoduleUrl(@NotNull StoredConfig mainRepoConfig, @NotNull String submoduleUrl)
        throws URISyntaxException {
    if (!isRelative(submoduleUrl))
        return submoduleUrl;

    String baseUrl = mainRepoConfig.getString("teamcity", null, "remote");
    URIish u = new URIish(baseUrl);
    String newPath = u.getPath();
    if (newPath.length() == 0) {
        newPath = submoduleUrl;//  w ww  . ja  va2  s  .  c  om
    } else {
        newPath = GitUtils.normalizePath(newPath + '/' + submoduleUrl);
    }
    return u.setPath(newPath).toPrivateString();
}

From source file:org.apache.stratos.cartridge.agent.artifact.deployment.synchronizer.git.impl.GitBasedArtifactRepository.java

License:Apache License

/**
 * Handles the Invalid configuration issues
 *
 * @param gitRepoCtx RepositoryContext instance of the tenant
 *///from  w  w w  .j a  v a  2s . c  o  m
private void handleInvalidConfigurationError(RepositoryContext gitRepoCtx) {

    StoredConfig storedConfig = gitRepoCtx.getLocalRepo().getConfig();
    boolean modifiedConfig = false;
    if (storedConfig != null) {

        if (storedConfig.getString("branch", "master", "remote") == null
                || storedConfig.getString("branch", "master", "remote").isEmpty()) {

            storedConfig.setString("branch", "master", "remote", "origin");
            modifiedConfig = true;
        }

        if (storedConfig.getString("branch", "master", "merge") == null
                || storedConfig.getString("branch", "master", "merge").isEmpty()) {

            storedConfig.setString("branch", "master", "merge", "refs/heads/master");
            modifiedConfig = true;
        }

        if (modifiedConfig) {
            try {
                storedConfig.save();
                // storedConfig.load();

            } catch (IOException e) {
                String message = "Error saving git configuration file in local repo at "
                        + gitRepoCtx.getGitLocalRepoPath();
                System.out.println(message);
                log.error(message, e);
            }
        }
    }
}

From source file:org.codice.git.GitHandler.java

License:Open Source License

@Override
public String getConfigString(String section, String subsection, String key) {
    final StoredConfig config = repo.getConfig();
    final String value = config.getString(section, subsection, key);

    LOGGER.log(Level.FINE, "Value for [{0}, {1}, {2}]: {3}\n",
            new Object[] { section, subsection, key, value });
    return value;
}

From source file:org.eclipse.che.git.impl.jgit.JGitConnection.java

License:Open Source License

@Override
public PullResponse pull(PullRequest request) throws GitException, UnauthorizedException {
    String remoteName = request.getRemote();
    String remoteUri;/*from  ww  w. j a  v  a2  s.co  m*/
    try {
        if (repository.getRepositoryState().equals(RepositoryState.MERGING)) {
            throw new GitException(ERROR_PULL_MERGING);
        }
        String fullBranch = repository.getFullBranch();
        if (!fullBranch.startsWith(Constants.R_HEADS)) {
            throw new DetachedHeadException(ERROR_PULL_HEAD_DETACHED);
        }

        String branch = fullBranch.substring(Constants.R_HEADS.length());

        StoredConfig config = repository.getConfig();
        if (remoteName == null) {
            remoteName = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branch,
                    ConfigConstants.CONFIG_KEY_REMOTE);
            if (remoteName == null) {
                remoteName = Constants.DEFAULT_REMOTE_NAME;
            }
        }
        remoteUri = config.getString(ConfigConstants.CONFIG_REMOTE_SECTION, remoteName,
                ConfigConstants.CONFIG_KEY_URL);

        String remoteBranch;
        RefSpec fetchRefSpecs = null;
        String refSpec = request.getRefSpec();
        if (refSpec != null) {
            fetchRefSpecs = (refSpec.indexOf(':') < 0) //
                    ? new RefSpec(Constants.R_HEADS + refSpec + ":" + fullBranch) //
                    : new RefSpec(refSpec);
            remoteBranch = fetchRefSpecs.getSource();
        } else {
            remoteBranch = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branch,
                    ConfigConstants.CONFIG_KEY_MERGE);
        }

        if (remoteBranch == null) {
            remoteBranch = fullBranch;
        }

        FetchCommand fetchCommand = getGit().fetch();
        fetchCommand.setRemote(remoteName);
        if (fetchRefSpecs != null) {
            fetchCommand.setRefSpecs(fetchRefSpecs);
        }
        int timeout = request.getTimeout();
        if (timeout > 0) {
            fetchCommand.setTimeout(timeout);
        }

        FetchResult fetchResult = (FetchResult) executeRemoteCommand(remoteUri, fetchCommand);

        Ref remoteBranchRef = fetchResult.getAdvertisedRef(remoteBranch);
        if (remoteBranchRef == null) {
            remoteBranchRef = fetchResult.getAdvertisedRef(Constants.R_HEADS + remoteBranch);
        }
        if (remoteBranchRef == null) {
            throw new GitException(String.format(ERROR_PULL_REF_MISSING, remoteBranch));
        }
        org.eclipse.jgit.api.MergeResult mergeResult = getGit().merge().include(remoteBranchRef).call();
        if (mergeResult.getMergeStatus()
                .equals(org.eclipse.jgit.api.MergeResult.MergeStatus.ALREADY_UP_TO_DATE)) {
            return newDto(PullResponse.class).withCommandOutput("Already up-to-date");
        }

        if (mergeResult.getConflicts() != null) {
            StringBuilder message = new StringBuilder(ERROR_PULL_MERGE_CONFLICT_IN_FILES);
            message.append(lineSeparator());
            Map<String, int[][]> allConflicts = mergeResult.getConflicts();
            for (String path : allConflicts.keySet()) {
                message.append(path).append(lineSeparator());
            }
            message.append(ERROR_PULL_AUTO_MERGE_FAILED);
            throw new GitException(message.toString());
        }
    } catch (CheckoutConflictException exception) {
        StringBuilder message = new StringBuilder(ERROR_CHECKOUT_CONFLICT);
        message.append(lineSeparator());
        for (String path : exception.getConflictingPaths()) {
            message.append(path).append(lineSeparator());
        }
        message.append(ERROR_PULL_COMMIT_BEFORE_MERGE);
        throw new GitException(message.toString(), exception);
    } catch (IOException | GitAPIException exception) {
        String errorMessage;
        if (exception.getMessage().equals("Invalid remote: " + remoteName)) {
            errorMessage = ERROR_NO_REMOTE_REPOSITORY;
        } else {
            errorMessage = exception.getMessage();
        }
        throw new GitException(errorMessage, exception);
    }
    return newDto(PullResponse.class).withCommandOutput("Successfully pulled from " + remoteUri);
}

From source file:org.eclipse.che.git.impl.jgit.JGitConnection.java

License:Open Source License

@Override
public void remoteDelete(String name) throws GitException {
    StoredConfig config = repository.getConfig();
    Set<String> remoteNames = config.getSubsections(ConfigConstants.CONFIG_KEY_REMOTE);
    if (!remoteNames.contains(name)) {
        throw new GitException("error: Could not remove config section 'remote." + name + "'");
    }//from w  w  w.j a v a  2s.  co  m

    config.unsetSection(ConfigConstants.CONFIG_REMOTE_SECTION, name);
    Set<String> branches = config.getSubsections(ConfigConstants.CONFIG_BRANCH_SECTION);

    for (String branch : branches) {
        String r = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branch,
                ConfigConstants.CONFIG_KEY_REMOTE);
        if (name.equals(r)) {
            config.unset(ConfigConstants.CONFIG_BRANCH_SECTION, branch, ConfigConstants.CONFIG_KEY_REMOTE);
            config.unset(ConfigConstants.CONFIG_BRANCH_SECTION, branch, ConfigConstants.CONFIG_KEY_MERGE);
            List<Branch> remoteBranches = branchList(newDto(BranchListRequest.class).withListMode("r"));
            for (Branch remoteBranch : remoteBranches) {
                if (remoteBranch.getDisplayName().startsWith(name)) {
                    branchDelete(
                            newDto(BranchDeleteRequest.class).withName(remoteBranch.getName()).withForce(true));
                }
            }
        }
    }

    try {
        config.save();
    } catch (IOException exception) {
        throw new GitException(exception.getMessage(), exception);
    }
}

From source file:org.eclipse.egit.core.GitProjectSetCapability.java

License:Open Source License

private String asReference(IProject project) throws TeamException {
    RepositoryMapping mapping = RepositoryMapping.getMapping(project);
    String branch;//from www.ja v a  2 s.c o m
    try {
        branch = mapping.getRepository().getBranch();
    } catch (IOException e) {
        throw new TeamException(
                NLS.bind(CoreText.GitProjectSetCapability_ExportCouldNotGetBranch, project.getName()));
    }
    StoredConfig config = mapping.getRepository().getConfig();
    String remote = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branch,
            ConfigConstants.CONFIG_KEY_REMOTE);
    String url = config.getString(ConfigConstants.CONFIG_REMOTE_SECTION, remote,
            ConfigConstants.CONFIG_KEY_URL);
    if (url == null)
        throw new TeamException(NLS.bind(CoreText.GitProjectSetCapability_ExportNoRemote, project.getName()));

    String projectPath = mapping.getRepoRelativePath(project);
    if (projectPath.equals("")) //$NON-NLS-1$
        projectPath = "."; //$NON-NLS-1$

    return asReference(url, branch, projectPath);
}

From source file:org.eclipse.egit.core.internal.gerrit.GerritUtil.java

License:Open Source License

/**
 * If the repository is not bare and looks like it might be a Gerrit
 * repository, try to configure it such that EGit's Gerrit support is
 * enabled./*w ww. jav a 2  s  . c o m*/
 *
 * @param repository
 *            to try to configure
 */
public static void tryToAutoConfigureForGerrit(@NonNull Repository repository) {
    if (repository.isBare()) {
        return;
    }
    StoredConfig config = repository.getConfig();
    boolean isGerrit = false;
    boolean changed = false;
    try {
        for (RemoteConfig remote : RemoteConfig.getAllRemoteConfigs(config)) {
            if (isGerritPush(remote)) {
                isGerrit = true;
                if (configureFetchNotes(remote)) {
                    changed = true;
                    remote.update(config);
                }
            }
        }
    } catch (URISyntaxException ignored) {
        // Ignore it here -- we're just trying to set up Gerrit support.
    }
    if (isGerrit) {
        if (config.getString(ConfigConstants.CONFIG_GERRIT_SECTION, null,
                ConfigConstants.CONFIG_KEY_CREATECHANGEID) != null) {
            // Already configured.
        } else {
            setCreateChangeId(config);
            changed = true;
        }
        if (changed) {
            try {
                config.save();
            } catch (IOException e) {
                Activator.logError(
                        MessageFormat.format(CoreText.GerritUtil_ConfigSaveError, repository.getDirectory()),
                        e);
            }
        }
    }
}

From source file:org.eclipse.egit.gitflow.GitFlowConfig.java

License:Open Source License

/**
 * @return Local user of this repository.
 *//*from w  w w. j  a  va 2  s . c om*/
public String getUser() {
    StoredConfig config = repository.getConfig();
    String userName = config.getString(USER_SECTION, null, "name"); //$NON-NLS-1$
    String email = config.getString(USER_SECTION, null, "email"); //$NON-NLS-1$
    return String.format("%s <%s>", userName, email); //$NON-NLS-1$
}