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:io.fabric8.maven.CreateBranchMojo.java

License:Apache License

protected void doPull() throws MojoExecutionException {
    //CredentialsProvider cp = getCredentials();
    CredentialsProvider cp = null;//from   ww w . jav a2  s  .c om
    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.openshift.agent.CartridgeGitRepository.java

License:Apache License

/**
 * Clones or pulls the remote repository and returns the directory with the checkout
 *///from   www  .  j  a v a 2  s  .c  om
public void cloneOrPull(final String repo, final CredentialsProvider credentials) throws Exception {
    if (!localRepo.exists() && !localRepo.mkdirs()) {
        throw new IOException("Failed to create local repository");
    }
    File gitDir = new File(localRepo, ".git");
    if (!gitDir.exists()) {
        LOG.info("Cloning remote repo " + repo);
        CloneCommand command = Git.cloneRepository().setCredentialsProvider(credentials).setURI(repo)
                .setDirectory(localRepo).setRemote(remoteName);
        git = command.call();
    } else {
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setGitDir(gitDir).readEnvironment() // scan environment GIT_* variables
                .findGitDir() // scan up the file system tree
                .build();

        git = new Git(repository);

        // update the remote repo just in case
        StoredConfig config = repository.getConfig();
        config.setString("remote", remoteName, "url", repo);
        config.setString("remote", remoteName, "fetch", "+refs/heads/*:refs/remotes/" + remoteName + "/*");

        String branch = "master";
        config.setString("branch", branch, "remote", remoteName);
        config.setString("branch", branch, "merge", "refs/heads/" + branch);

        try {
            config.save();
        } catch (IOException e) {
            LOG.error("Failed to save the git configuration to " + localRepo + " with remote repo: " + repo
                    + ". " + e, e);
        }

        // now pull
        LOG.info("Pulling from remote repo " + repo);
        git.pull().setCredentialsProvider(credentials).setRebase(true).call();
    }
}

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   ww  w.j ava2 s . co m*/
    }
    return null;
}

From source file:io.hawkcd.materials.materialservices.GitService.java

License:Apache License

@Override
public boolean repositoryExists(GitMaterial gitMaterial) {
    try {/*  ww w.  j  a v  a2 s  .c  o  m*/
        Repository repository = Git.open(new File(gitMaterial.getDestination())).getRepository();
        org.eclipse.jgit.lib.Config config = repository.getConfig();
        String repositoryUrl = config.getString("remote", "origin", "url");
        if (!repositoryUrl.equals(gitMaterial.getRepositoryUrl())) {
            return false;
        }
    } catch (IOException e) {
        return false;
    }

    return true;
}

From source file:io.jenkins.blueocean.blueocean_git_pipeline.GitCacheCloneReadSaveRequest.java

License:Open Source License

private @Nonnull Git getActiveRepository(Repository repository) throws IOException {
    try {/*w ww.  j a v  a 2s  . com*/
        // Clone the bare repository
        File cloneDir = File.createTempFile("clone", "");

        if (cloneDir.exists()) {
            if (cloneDir.isDirectory()) {
                FileUtils.deleteDirectory(cloneDir);
            } else {
                if (!cloneDir.delete()) {
                    throw new ServiceException.UnexpectedErrorException("Unable to delete repository clone");
                }
            }
        }
        if (!cloneDir.mkdirs()) {
            throw new ServiceException.UnexpectedErrorException("Unable to create repository clone directory");
        }

        String url = repository.getConfig().getString("remote", "origin", "url");
        Git gitClient = Git.cloneRepository().setCloneAllBranches(false)
                .setProgressMonitor(new CloneProgressMonitor(url))
                .setURI(repository.getDirectory().getCanonicalPath()).setDirectory(cloneDir).call();

        RemoteRemoveCommand remove = gitClient.remoteRemove();
        remove.setName("origin");
        remove.call();

        RemoteAddCommand add = gitClient.remoteAdd();
        add.setName("origin");
        add.setUri(new URIish(gitSource.getRemote()));
        add.call();

        if (GitUtils.isSshUrl(gitSource.getRemote())) {
            // Get committer info and credentials
            User user = User.current();
            if (user == null) {
                throw new ServiceException.UnauthorizedException("Not authenticated");
            }
            BasicSSHUserPrivateKey privateKey = UserSSHKeyManager.getOrCreate(user);

            // Make sure up-to-date and credentials work
            GitUtils.fetch(repository, privateKey);
        } else {
            FetchCommand fetch = gitClient.fetch();
            fetch.call();
        }

        if (!StringUtils.isEmpty(sourceBranch) && !sourceBranch.equals(branch)) {
            CheckoutCommand checkout = gitClient.checkout();
            checkout.setStartPoint("origin/" + sourceBranch);
            checkout.setName(sourceBranch);
            checkout.setCreateBranch(true); // to create a new local branch
            checkout.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.NOTRACK);
            checkout.call();

            checkout = gitClient.checkout();
            checkout.setName(branch);
            checkout.setCreateBranch(true); // this *should* be a new branch
            checkout.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.NOTRACK);
            checkout.call();
        } else {
            CheckoutCommand checkout = gitClient.checkout();
            checkout.setStartPoint("origin/" + branch);
            checkout.setName(branch);
            checkout.setCreateBranch(true); // to create a new local branch
            checkout.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.NOTRACK);
            checkout.call();
        }

        return gitClient;
    } catch (GitAPIException | URISyntaxException ex) {
        throw new ServiceException.UnexpectedErrorException("Unable to get working repository directory", ex);
    }
}

From source file:it.com.atlassian.labs.speakeasy.util.jgit.FixedTransportHttp.java

License:Eclipse Distribution License

FixedTransportHttp(final Repository local, final URIish uri) throws NotSupportedException {
    super(local, uri);
    try {//from w w w . j  ava  2 s  .c  o  m
        String uriString = uri.toString();
        if (!uriString.endsWith("/")) //$NON-NLS-1$
            uriString += "/"; //$NON-NLS-1$
        baseUrl = new URL(uriString);
        objectsUrl = new URL(baseUrl, "objects/"); //$NON-NLS-1$
    } catch (MalformedURLException e) {
        throw new NotSupportedException(MessageFormat.format(JGitText.get().invalidURL, uri), e);
    }
    http = local.getConfig().get(HTTP_KEY);
    proxySelector = ProxySelector.getDefault();
}

From source file:jbyoshi.gitupdate.processor.FastForward.java

License:Apache License

@Override
public void process(Repository repo, Git git, String branch, Ref ref, Report report)
        throws GitAPIException, IOException {
    String pushDefault = Utils.getPushRemote(repo, branch);
    if (pushDefault != null) {
        tryFastForward(repo, ref, repo.getRef(Constants.R_REMOTES + pushDefault + "/" + branch), report);
    }//  ww w. j ava  2 s.  c o m
    tryFastForward(repo, ref, repo.getRef(new BranchConfig(repo.getConfig(), branch).getTrackingBranch()),
            report);
    if (pushDefault == null) {
        tryFastForward(repo, ref, repo.getRef(Constants.R_REMOTES + "upstream/" + branch), report);
    }
}

From source file:jbyoshi.gitupdate.processor.Fetch.java

License:Apache License

@Override
public void process(Repository repo, Git git, String remote, String fullRemote, Report report)
        throws GitAPIException, IOException {
    FetchResult result = git.fetch().setRemoveDeletedRefs(true).setCredentialsProvider(Prompts.INSTANCE)
            .setRemote(remote).call();/*from   ww w .jav a 2  s  . c om*/
    for (TrackingRefUpdate update : result.getTrackingRefUpdates()) {
        if (update.getRemoteName().equals(Constants.R_HEADS + Constants.HEAD)) {
            continue;
        }
        StringBuilder text = new StringBuilder(Utils.getShortBranch(update.getRemoteName())).append(": ");
        String oldId = update.getOldObjectId().name();
        if (update.getOldObjectId().equals(ObjectId.zeroId())) {
            oldId = "new branch";
        }
        String newId = update.getNewObjectId().name();
        if (update.getNewObjectId().equals(ObjectId.zeroId())) {
            newId = "deleted";
            for (String branch : Utils.getLocalBranches(repo).keySet()) {
                if (update.getLocalName()
                        .equals(new BranchConfig(repo.getConfig(), branch).getRemoteTrackingBranch())) {
                    repo.getConfig().unset("branches", branch, "remote");
                    repo.getConfig().save();
                }
            }
        }
        text.append(oldId).append(" -> ").append(newId);
        report.newChild(text.toString()).modified();
    }
}

From source file:jbyoshi.gitupdate.processor.Push.java

License:Apache License

@Override
public void registerTasks(Repository repo, Git git, Task root) throws Exception {
    Task me = root.newChild(getClass().getSimpleName());
    // Group the branches by their remotes.
    Multimap<String, String> branchList = HashMultimap.create();
    for (String branch : Utils.getLocalBranches(repo).keySet()) {
        String remote = Utils.getPushRemote(repo, branch);
        if (remote == null) {
            remote = new BranchConfig(repo.getConfig(), branch).getRemote();
        }//from w  w  w  .j a  v a2 s. co m
        if (remote != null) {
            branchList.put(remote, branch);
        }
    }
    for (Map.Entry<String, Collection<String>> remote : branchList.asMap().entrySet()) {
        me.newChild(remote.getKey(), report -> {
            try {
                process(repo, git, remote.getKey(), remote.getValue(), report);
            } catch (Exception e) {
                report.newErrorChild(e);
            }
        });
    }
}

From source file:jbyoshi.gitupdate.processor.Push.java

License:Apache License

private static void process(Repository repo, Git git, String remote, Collection<String> branches, Report report)
        throws Exception {
    // Figure out if anything needs to be pushed.
    Map<String, ObjectId> oldIds = new HashMap<>();
    boolean canPush = false;
    for (String branch : branches) {
        BranchConfig config = new BranchConfig(repo.getConfig(), branch);
        ObjectId target = repo.getRef(branch).getObjectId();

        Ref remoteRef = repo.getRef(config.getRemoteTrackingBranch());
        if (remoteRef == null || !target.equals(remoteRef.getObjectId())) {
            canPush = true;/*from  w  ww .  j  a  v a2 s.c  om*/
        }
        oldIds.put(branch, remoteRef == null ? ObjectId.zeroId() : remoteRef.getObjectId());
    }

    if (!canPush) {
        return;
    }

    PushCommand push = git.push().setCredentialsProvider(Prompts.INSTANCE).setTimeout(5).setRemote(remote);
    for (String branch : branches) {
        push.add(Constants.R_HEADS + branch);
    }
    for (PushResult result : push.call()) {
        for (RemoteRefUpdate update : result.getRemoteUpdates()) {
            if (update.getStatus() == RemoteRefUpdate.Status.OK) {
                String branchName = Utils.getShortBranch(update.getSrcRef());
                ObjectId oldId = oldIds.get(branchName);
                String old = oldId.equals(ObjectId.zeroId()) ? "new branch" : oldId.name();
                report.newChild(branchName + ": " + old + " -> " + update.getNewObjectId().name()).modified();
            }
        }
    }
}