Example usage for org.eclipse.jgit.transport RemoteConfig getAllRemoteConfigs

List of usage examples for org.eclipse.jgit.transport RemoteConfig getAllRemoteConfigs

Introduction

In this page you can find the example usage for org.eclipse.jgit.transport RemoteConfig getAllRemoteConfigs.

Prototype

public static List<RemoteConfig> getAllRemoteConfigs(Config rc) throws URISyntaxException 

Source Link

Document

Parse all remote blocks in an existing configuration file, looking for remotes configuration.

Usage

From source file:com.cloudbees.eclipse.dev.scm.egit.ForgeEGitSync.java

License:Open Source License

public static boolean isAlreadyCloned(final String url) {
    try {/*from  w w  w .j  ava  2 s .  co  m*/

        if (url == null) {
            return false;
        }

        String bareUrl = ForgeUtil.stripGitPrefixes(url);
        if (bareUrl == null) {
            return false;
        }

        URIish proposalHTTPS = new URIish(ForgeUtil.PR_HTTPS + bareUrl);
        URIish proposalSSH = new URIish(ForgeUtil.PR_SSH + bareUrl);

        List<String> reps = Activator.getDefault().getRepositoryUtil().getConfiguredRepositories();
        for (String repo : reps) {
            try {

                FileRepository fr = new FileRepository(new File(repo));
                List<RemoteConfig> allRemotes = RemoteConfig.getAllRemoteConfigs(fr.getConfig());
                for (RemoteConfig remo : allRemotes) {
                    List<URIish> uris = remo.getURIs();
                    for (URIish uri : uris) {
                        //System.out.println("Checking URI: " + uri + " - " + proposal.equals(uri));
                        if (proposalHTTPS.equals(uri) || proposalSSH.equals(uri)) {
                            return true;
                        }
                    }
                }

            } catch (Exception e) {
                CloudBeesCorePlugin.getDefault().getLogger().error(e);
            }
        }
    } catch (Exception e) {
        CloudBeesCorePlugin.getDefault().getLogger().error(e);
    }

    return false;
}

From source file:com.cloudbees.eclipse.dev.scm.egit.ForgeEGitSync.java

License:Open Source License

private boolean openRemoteFile_(final String repo, final ChangeSetPathItem item,
        final IProgressMonitor monitor) {
    try {/*w w  w  .j a  v a 2s.  c om*/
        // TODO extract repo search into separate method
        RepositoryCache repositoryCache = org.eclipse.egit.core.Activator.getDefault().getRepositoryCache();
        Repository repository = null;
        URIish proposal = new URIish(repo);
        List<String> reps = Activator.getDefault().getRepositoryUtil().getConfiguredRepositories();
        all: for (String rep : reps) {
            try {

                Repository fr = repositoryCache.lookupRepository(new File(rep));
                List<RemoteConfig> allRemotes = RemoteConfig.getAllRemoteConfigs(fr.getConfig());
                for (RemoteConfig remo : allRemotes) {
                    List<URIish> uris = remo.getURIs();
                    for (URIish uri : uris) {
                        CloudBeesDevCorePlugin.getDefault().getLogger()
                                .info("Checking URI: " + uri + " - " + proposal.equals(uri));
                        if (proposal.equals(uri)) {
                            repository = fr;
                            break all;
                        }
                    }
                }
            } catch (Exception e) {
                CloudBeesDevCorePlugin.getDefault().getLogger().error(e);
            }
        }

        CloudBeesDevCorePlugin.getDefault().getLogger().info("Repo: " + repository);

        if (repository == null) {
            throw new CloudBeesException("Failed to find mapped repository for " + repo);
        }

        ObjectId commitId = ObjectId.fromString(item.parent.id);
        RevWalk rw = new RevWalk(repository);
        RevCommit rc = rw.parseCommit(commitId);
        final IFileRevision rev = CompareUtils.getFileRevision(item.path, rc, repository, null);

        final IEditorPart[] editor = new IEditorPart[1];

        PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
            @Override
            public void run() {
                IWorkbenchPage activePage = CloudBeesUIPlugin.getActiveWindow().getActivePage();
                try {
                    editor[0] = Utils.openEditor(activePage, rev, monitor);
                } catch (CoreException e) {
                    e.printStackTrace(); // TODO
                }
            }
        });

        return editor[0] != null;
    } catch (Exception e) {
        CloudBeesDevCorePlugin.getDefault().getLogger().error(e); // TODO handle better?
        return false;
    }
}

From source file:com.gitblit.service.MirrorService.java

License:Apache License

@Override
public void run() {
    if (!isReady()) {
        return;/*from w  ww  .  j a v a 2s  . c o m*/
    }

    running.set(true);

    for (String repositoryName : repositoryManager.getRepositoryList()) {
        if (forceClose.get()) {
            break;
        }
        if (repositoryManager.isCollectingGarbage(repositoryName)) {
            logger.debug("mirror is skipping {} garbagecollection", repositoryName);
            continue;
        }
        RepositoryModel model = null;
        Repository repository = null;
        try {
            model = repositoryManager.getRepositoryModel(repositoryName);
            if (!model.isMirror && !model.isBare) {
                // repository must be a valid bare git mirror
                logger.debug("mirror is skipping {} !mirror !bare", repositoryName);
                continue;
            }

            repository = repositoryManager.getRepository(repositoryName);
            if (repository == null) {
                logger.warn(
                        MessageFormat.format("MirrorExecutor is missing repository {0}?!?", repositoryName));
                continue;
            }

            // automatically repair (some) invalid fetch ref specs
            if (!repairAttempted.contains(repositoryName)) {
                repairAttempted.add(repositoryName);
                JGitUtils.repairFetchSpecs(repository);
            }

            // find the first mirror remote - there should only be one
            StoredConfig rc = repository.getConfig();
            RemoteConfig mirror = null;
            List<RemoteConfig> configs = RemoteConfig.getAllRemoteConfigs(rc);
            for (RemoteConfig config : configs) {
                if (config.isMirror()) {
                    mirror = config;
                    break;
                }
            }

            if (mirror == null) {
                // repository does not have a mirror remote
                logger.debug("mirror is skipping {} no mirror remote found", repositoryName);
                continue;
            }

            logger.debug("checking {} remote {} for ref updates", repositoryName, mirror.getName());
            final boolean testing = false;
            Git git = new Git(repository);
            FetchResult result = git.fetch().setRemote(mirror.getName()).setDryRun(testing).call();
            Collection<TrackingRefUpdate> refUpdates = result.getTrackingRefUpdates();
            if (refUpdates.size() > 0) {
                ReceiveCommand ticketBranchCmd = null;
                for (TrackingRefUpdate ru : refUpdates) {
                    StringBuilder sb = new StringBuilder();
                    sb.append("updated mirror ");
                    sb.append(repositoryName);
                    sb.append(" ");
                    sb.append(ru.getRemoteName());
                    sb.append(" -> ");
                    sb.append(ru.getLocalName());
                    if (ru.getResult() == Result.FORCED) {
                        sb.append(" (forced)");
                    }
                    sb.append(" ");
                    sb.append(ru.getOldObjectId() == null ? "" : ru.getOldObjectId().abbreviate(7).name());
                    sb.append("..");
                    sb.append(ru.getNewObjectId() == null ? "" : ru.getNewObjectId().abbreviate(7).name());
                    logger.info(sb.toString());

                    if (BranchTicketService.BRANCH.equals(ru.getLocalName())) {
                        ReceiveCommand.Type type = null;
                        switch (ru.getResult()) {
                        case NEW:
                            type = Type.CREATE;
                            break;
                        case FAST_FORWARD:
                            type = Type.UPDATE;
                            break;
                        case FORCED:
                            type = Type.UPDATE_NONFASTFORWARD;
                            break;
                        default:
                            type = null;
                            break;
                        }

                        if (type != null) {
                            ticketBranchCmd = new ReceiveCommand(ru.getOldObjectId(), ru.getNewObjectId(),
                                    ru.getLocalName(), type);
                        }
                    }
                }

                if (ticketBranchCmd != null) {
                    repository.fireEvent(new ReceiveCommandEvent(model, ticketBranchCmd));
                }
            }
        } catch (Exception e) {
            logger.error("Error updating mirror " + repositoryName, e);
        } finally {
            // cleanup
            if (repository != null) {
                repository.close();
            }
        }
    }

    running.set(false);
}

From source file:com.rimerosolutions.ant.git.tasks.FetchTask.java

License:Apache License

@Override
public void doExecute() {
    try {//from  ww w . j a  va2 s  .c  o m
        StoredConfig config = git.getRepository().getConfig();
        List<RemoteConfig> remoteConfigs = RemoteConfig.getAllRemoteConfigs(config);

        if (remoteConfigs.isEmpty()) {
            URIish uri = new URIish(getUri());

            RemoteConfig remoteConfig = new RemoteConfig(config, Constants.DEFAULT_REMOTE_NAME);
            remoteConfig.addURI(uri);
            remoteConfig.addFetchRefSpec(new RefSpec("+" + Constants.R_HEADS + "*:" + Constants.R_REMOTES
                    + Constants.DEFAULT_REMOTE_NAME + "/*"));

            config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, Constants.MASTER,
                    ConfigConstants.CONFIG_KEY_REMOTE, Constants.DEFAULT_REMOTE_NAME);
            config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, Constants.MASTER,
                    ConfigConstants.CONFIG_KEY_MERGE, Constants.R_HEADS + Constants.MASTER);

            remoteConfig.update(config);
            config.save();
        }

        List<RefSpec> specs = new ArrayList<RefSpec>(3);

        specs.add(new RefSpec(
                "+" + Constants.R_HEADS + "*:" + Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME + "/*"));
        specs.add(new RefSpec("+" + Constants.R_NOTES + "*:" + Constants.R_NOTES + "*"));
        specs.add(new RefSpec("+" + Constants.R_TAGS + "*:" + Constants.R_TAGS + "*"));

        FetchCommand fetchCommand = git.fetch().setDryRun(dryRun).setThin(thinPack).setRemote(getUri())
                .setRefSpecs(specs).setRemoveDeletedRefs(removeDeletedRefs);

        setupCredentials(fetchCommand);

        if (getProgressMonitor() != null) {
            fetchCommand.setProgressMonitor(getProgressMonitor());
        }

        FetchResult fetchResult = fetchCommand.call();

        GitTaskUtils.validateTrackingRefUpdates(FETCH_FAILED_MESSAGE, fetchResult.getTrackingRefUpdates());

        log(fetchResult.getMessages());

    } catch (URISyntaxException e) {
        throw new GitBuildException("Invalid URI syntax: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new GitBuildException("Could not save or get repository configuration: " + e.getMessage(), e);
    } catch (InvalidRemoteException e) {
        throw new GitBuildException("Invalid remote URI: " + e.getMessage(), e);
    } catch (TransportException e) {
        throw new GitBuildException("Communication error: " + e.getMessage(), e);
    } catch (GitAPIException e) {
        throw new GitBuildException("Unexpected exception: " + e.getMessage(), e);
    }
}

From source file:com.rimerosolutions.ant.git.tasks.PushTask.java

License:Apache License

@Override
protected void doExecute() {
    try {/*from   w w w .  ja  v  a 2  s  .co  m*/
        StoredConfig config = git.getRepository().getConfig();
        List<RemoteConfig> remoteConfigs = RemoteConfig.getAllRemoteConfigs(config);

        if (remoteConfigs.isEmpty()) {
            URIish uri = new URIish(getUri());

            RemoteConfig remoteConfig = new RemoteConfig(config, Constants.DEFAULT_REMOTE_NAME);

            remoteConfig.addURI(uri);
            remoteConfig.addFetchRefSpec(new RefSpec(DEFAULT_REFSPEC_STRING));
            remoteConfig.addPushRefSpec(new RefSpec(DEFAULT_REFSPEC_STRING));
            remoteConfig.update(config);

            config.save();
        }

        String currentBranch = git.getRepository().getBranch();
        List<RefSpec> specs = Arrays.asList(new RefSpec(currentBranch + ":" + currentBranch));

        if (deleteRemoteBranch != null) {
            specs = Arrays.asList(new RefSpec(":" + Constants.R_HEADS + deleteRemoteBranch));
        }

        PushCommand pushCommand = git.push().setPushAll().setRefSpecs(specs).setDryRun(false);

        if (getUri() != null) {
            pushCommand.setRemote(getUri());
        }

        setupCredentials(pushCommand);

        if (includeTags) {
            pushCommand.setPushTags();
        }

        if (getProgressMonitor() != null) {
            pushCommand.setProgressMonitor(getProgressMonitor());
        }

        Iterable<PushResult> pushResults = pushCommand.setForce(true).call();

        for (PushResult pushResult : pushResults) {
            log(pushResult.getMessages());
            GitTaskUtils.validateRemoteRefUpdates(PUSH_FAILED_MESSAGE, pushResult.getRemoteUpdates());
            GitTaskUtils.validateTrackingRefUpdates(PUSH_FAILED_MESSAGE, pushResult.getTrackingRefUpdates());
        }
    } catch (Exception e) {
        if (pushFailedProperty != null) {
            getProject().setProperty(pushFailedProperty, e.getMessage());
        }

        throw new GitBuildException(PUSH_FAILED_MESSAGE, e);
    }
}

From source file:edu.tum.cs.mylyn.provisioning.git.RepositoryWrapper.java

License:Open Source License

public List<RemoteConfig> getRemoteConfigs() {
    try {/*  w  w  w. ja  va  2 s  .  com*/
        return RemoteConfig.getAllRemoteConfigs(wrappedRepository.getConfig());
    } catch (URISyntaxException e) {
        return new ArrayList<RemoteConfig>();
    }
}

From source file:jenkins.plugins.versionedbuildstep.Git.java

License:Open Source License

/**
 * Code copied from the Git Plugin/*from   www  . j av a  2  s .c o  m*/
 * ({@link hudson.plugins.git.GitSCM#newRemoteConfig(String, String, org.eclipse.jgit.transport.RefSpec)}).
 * @param name the name of the remote
 * @param refUrl the url
 * @param refSpec the ref spec.
 * @return a RemoteConfig saleable for clone and fetch.
 */
private RemoteConfig newRemoteConfig(String name, String refUrl, RefSpec refSpec) {

    try {
        Config repoConfig = new Config();
        // Make up a repo config from the request parameters

        repoConfig.setString("remote", name, "url", refUrl);
        repoConfig.setString("remote", name, "fetch", refSpec.toString());

        return RemoteConfig.getAllRemoteConfigs(repoConfig).get(0);
    } catch (Exception ex) {
        throw new GitException("Error trying to create JGit configuration", ex);
    }
}

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

License:Open Source License

/**
 * Find the remote config for the given remote name
 *
 * @param config/* w w w  .java 2  s  . com*/
 *            the configuration containing the remote config
 * @param remoteName
 *            the name of the remote to find
 * @return the found remoteConfig or {@code null}
 * @throws URISyntaxException
 *             if the configuration contains an illegal URI
 */
public static RemoteConfig findRemoteConfig(Config config, String remoteName) throws URISyntaxException {
    RemoteConfig remoteConfig = null;
    List<RemoteConfig> allRemoteConfigs = RemoteConfig.getAllRemoteConfigs(config);
    for (RemoteConfig rc : allRemoteConfigs) {
        if (rc.getName().equals(remoteName)) {
            remoteConfig = rc;
            break;
        }
    }
    return remoteConfig;
}

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.//from  w w w.j a v  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.ui.internal.actions.SynchronizeWithAction.java

License:Open Source License

private List<RemoteConfig> getRemoteConfigs(Repository repo) throws InvocationTargetException {
    try {/*from w w w .  j  a  v  a2s.  c o m*/
        return RemoteConfig.getAllRemoteConfigs(repo.getConfig());
    } catch (URISyntaxException e) {
        throw new InvocationTargetException(e);
    }
}