Example usage for org.eclipse.jgit.lib Repository getConfig

List of usage examples for org.eclipse.jgit.lib Repository getConfig

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Repository getConfig.

Prototype

@NonNull
public abstract StoredConfig getConfig();

Source Link

Document

Get the configuration of this repository.

Usage

From source file:jbyoshi.gitupdate.Utils.java

License:Apache License

public static String getPushRemote(Repository repo, String branch) throws IOException {
    String pushDefault = repo.getConfig().getString("branch", branch, "pushremote");
    if (pushDefault == null) {
        pushDefault = repo.getConfig().getString("remote", branch, "pushdefault");
    }//from www  . j  av  a  2s  .  c  o m
    return pushDefault;
}

From source file:jenkins.plugins.git.AbstractGitSCMSource.java

License:Open Source License

@NonNull
@Override/*ww  w.java  2s  .  co m*/
protected void retrieve(@NonNull final SCMHeadObserver observer, @NonNull TaskListener listener)
        throws IOException, InterruptedException {
    String cacheEntry = getCacheEntry();
    Lock cacheLock = getCacheLock(cacheEntry);
    cacheLock.lock();
    try {
        File cacheDir = getCacheDir(cacheEntry);
        Git git = Git.with(listener, new EnvVars(EnvVars.masterEnvVars)).in(cacheDir);
        GitClient client = git.getClient();
        client.addDefaultCredentials(getCredentials());
        if (!client.hasGitRepo()) {
            listener.getLogger().println("Creating git repository in " + cacheDir);
            client.init();
        }
        String remoteName = getRemoteName();
        listener.getLogger().println("Setting " + remoteName + " to " + getRemote());
        client.setRemoteUrl(remoteName, getRemote());
        listener.getLogger().println("Fetching " + remoteName + "...");
        List<RefSpec> refSpecs = getRefSpecs();
        client.fetch(remoteName, refSpecs.toArray(new RefSpec[refSpecs.size()]));
        listener.getLogger().println("Pruning stale remotes...");
        final Repository repository = client.getRepository();
        try {
            client.prune(new RemoteConfig(repository.getConfig(), remoteName));
        } catch (UnsupportedOperationException e) {
            e.printStackTrace(listener.error("Could not prune stale remotes"));
        } catch (URISyntaxException e) {
            e.printStackTrace(listener.error("Could not prune stale remotes"));
        }
        listener.getLogger().println("Getting remote branches...");
        SCMSourceCriteria branchCriteria = getCriteria();
        RevWalk walk = new RevWalk(repository);
        try {
            walk.setRetainBody(false);
            for (Branch b : client.getRemoteBranches()) {
                if (!b.getName().startsWith(remoteName + "/")) {
                    continue;
                }
                final String branchName = StringUtils.removeStart(b.getName(), remoteName + "/");
                listener.getLogger().println("Checking branch " + branchName);
                if (isExcluded(branchName)) {
                    continue;
                }
                if (branchCriteria != null) {
                    RevCommit commit = walk.parseCommit(b.getSHA1());
                    final long lastModified = TimeUnit.SECONDS.toMillis(commit.getCommitTime());
                    final RevTree tree = commit.getTree();
                    SCMSourceCriteria.Probe probe = new SCMSourceCriteria.Probe() {
                        @Override
                        public String name() {
                            return branchName;
                        }

                        @Override
                        public long lastModified() {
                            return lastModified;
                        }

                        @Override
                        public boolean exists(@NonNull String path) throws IOException {
                            TreeWalk tw = TreeWalk.forPath(repository, path, tree);
                            try {
                                return tw != null;
                            } finally {
                                if (tw != null) {
                                    tw.release();
                                }
                            }
                        }
                    };
                    if (branchCriteria.isHead(probe, listener)) {
                        listener.getLogger().println("Met criteria");
                    } else {
                        listener.getLogger().println("Does not meet criteria");
                        continue;
                    }
                }
                SCMHead head = new SCMHead(branchName);
                SCMRevision hash = new SCMRevisionImpl(head, b.getSHA1String());
                observer.observe(head, hash);
                if (!observer.isObserving()) {
                    return;
                }
            }
        } finally {
            walk.dispose();
        }

        listener.getLogger().println("Done.");
    } finally {
        cacheLock.unlock();
    }
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.agent.UpdaterImpl.java

License:Apache License

private void addSubmoduleUsernames(@NotNull File repositoryDir, @NotNull Config gitModules)
        throws IOException, ConfigInvalidException, VcsException {
    if (!myPluginConfig.isUseMainRepoUserForSubmodules())
        return;//from  w ww  .ja  va2  s  .c  o  m

    Loggers.VCS.info("Update submodules credentials");

    AuthSettings auth = myRoot.getAuthSettings();
    final String userName = auth.getUserName();
    if (userName == null) {
        Loggers.VCS.info("Username is not specified in the main VCS root settings, skip updating credentials");
        return;
    }

    Repository r = new RepositoryBuilder().setBare().setGitDir(getGitDir(repositoryDir)).build();
    StoredConfig gitConfig = r.getConfig();

    Set<String> submodules = gitModules.getSubsections("submodule");
    if (submodules.isEmpty()) {
        Loggers.VCS.info("No submodule sections found in "
                + new File(repositoryDir, ".gitmodules").getCanonicalPath() + ", skip updating credentials");
        return;
    }
    File modulesDir = new File(r.getDirectory(), Constants.MODULES);
    for (String submoduleName : submodules) {
        String url = gitModules.getString("submodule", submoduleName, "url");
        Loggers.VCS.info("Update credentials for submodule with url " + url);
        if (url == null || !isRequireAuth(url)) {
            Loggers.VCS.info("Url " + url + " does not require authentication, skip updating credentials");
            continue;
        }
        try {
            URIish uri = new URIish(url);
            String updatedUrl = uri.setUser(userName).toASCIIString();
            gitConfig.setString("submodule", submoduleName, "url", updatedUrl);
            String submodulePath = gitModules.getString("submodule", submoduleName, "path");
            if (submodulePath != null && myPluginConfig.isUpdateSubmoduleOriginUrl()) {
                File submoduleDir = new File(modulesDir, submodulePath);
                if (submoduleDir.isDirectory() && new File(submoduleDir, Constants.CONFIG).isFile())
                    updateOriginUrl(submoduleDir, updatedUrl);
            }
            Loggers.VCS.debug("Submodule url " + url + " changed to " + updatedUrl);
        } catch (URISyntaxException e) {
            Loggers.VCS.warn("Error while parsing an url " + url + ", skip updating submodule credentials", e);
        } catch (Exception e) {
            Loggers.VCS.warn("Error while updating the '" + submoduleName + "' submodule url", e);
        }
    }
    gitConfig.save();
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.agent.UpdaterImpl.java

License:Apache License

private void updateOriginUrl(@NotNull File repoDir, @NotNull String url) throws IOException {
    Repository r = new RepositoryBuilder().setBare().setGitDir(repoDir).build();
    StoredConfig config = r.getConfig();
    config.setString("remote", "origin", "url", url);
    config.save();/*from   w w w.  ja  v  a2s  .  com*/
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.agent.UpdaterImpl.java

License:Apache License

protected void removeUrlSections() throws VcsException {
    Repository r = null;
    try {/* w w  w . jav a  2  s.  c o  m*/
        r = new RepositoryBuilder().setWorkTree(myTargetDirectory).build();
        StoredConfig config = r.getConfig();
        Set<String> urlSubsections = config.getSubsections("url");
        for (String subsection : urlSubsections) {
            config.unsetSection("url", subsection);
        }
        config.save();
    } catch (IOException e) {
        String msg = "Error while remove url.* sections";
        LOG.error(msg, e);
        throw new VcsException(msg, e);
    } finally {
        if (r != null)
            r.close();
    }
}

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  ww  .j  a  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 {/*  w ww. j  ava2  s  .c  o  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.OperationContext.java

License:Apache License

@NotNull
public StoredConfig getConfig(@NotNull Repository r) {
    String repositoryPath = r.getDirectory().getAbsolutePath();
    StoredConfig result = myConfigsCache.get(repositoryPath);
    if (result == null) {
        result = r.getConfig();
        myConfigsCache.put(repositoryPath, result);
    }/* w  w w  .  j a  va2 s.c  o m*/
    return result;
}

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

License:Apache License

@NotNull
public Repository openRepository(@NotNull final File dir, @NotNull final URIish fetchUrl) throws VcsException {
    final URIish canonicalURI = getCanonicalURI(fetchUrl);
    if (isDefaultMirrorDir(dir))
        updateLastUsedTime(dir);/*from w w  w  .j  a v  a  2 s  .c  o m*/
    Repository result = myRepositoryCache.get(RepositoryCache.FileKey.exact(dir, FS.DETECTED));
    if (result == null)
        return createRepository(dir, canonicalURI);
    String existingRemote = result.getConfig().getString("teamcity", null, "remote");
    if (existingRemote == null) {
        myRepositoryCache.release(result);
        invalidate(dir);
        return GitServerUtil.getRepository(dir, fetchUrl);
    }
    if (!canonicalURI.toString().equals(existingRemote)) {
        myRepositoryCache.release(result);
        throw getWrongUrlError(dir, existingRemote, fetchUrl);
    }
    return result;
}

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

License:Apache License

@NotNull
public static String resolveSubmoduleUrl(@NotNull final Repository repository,
        @NotNull final String relativeUrl) throws URISyntaxException {
    return resolveSubmoduleUrl(repository.getConfig(), relativeUrl);
}