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

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

Introduction

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

Prototype

public List<URIish> getURIs() 

Source Link

Document

Get all configured URIs under this remote.

Usage

From source file:br.com.ingenieux.jenkins.plugins.codecommit.CodeCommitURLHelper.java

License:Apache License

private Iterable<RepositoryUsernameReference> fetchCodeCommitRepositoryNames(GitSCM scm)
        throws CredentialNotFoundException {
    AWSCredentialsProvider credentials = new DefaultAWSCredentialsProviderChain();

    if (isNotBlank(credentialId)) {
        credentials = CredentialsFactory.getCredentials(credentialId);

        if (null == credentials)
            throw new CredentialNotFoundException(
                    "CredentialId '" + credentialId + "' specified but not found.");
    }/*from  ww  w  . j av a2s  .c  om*/

    Set<RepositoryUsernameReference> results = new LinkedHashSet<RepositoryUsernameReference>();

    for (RemoteConfig cfg : scm.getRepositories()) {
        for (URIish u : cfg.getURIs()) {
            final String repositoryUrl = u.toPrivateASCIIString();
            final Matcher m = PATTERN_CODECOMMIT_REPO.matcher(repositoryUrl);

            if (m.matches()) {
                final String awsRegion = m.group(1);
                final String repositoryName = m.group(2);

                String usernamePassword = new CodeCommitRequestSigner(credentials, repositoryName, awsRegion,
                        new Date()).getPushUrl();

                int lastIndex = usernamePassword.lastIndexOf(':');

                String username = usernamePassword.substring(0, lastIndex);

                String password = usernamePassword.substring(1 + lastIndex);

                results.add(new RepositoryUsernameReference(repositoryUrl, repositoryName, username, password));
            }
        }
    }

    return results;
}

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

License:Open Source License

public static boolean isAlreadyCloned(final String url) {
    try {/* ww w .j  a v  a  2  s  .  c  o  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 {//from  ww  w  .j  a  v  a2  s  .c  o  m
        // 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.genuitec.eclipse.gerrit.tools.internal.fbranches.BranchingUtils.java

License:Open Source License

public static PushOperationSpecification setupPush(Repository repository, String refSpec)
        throws IOException, URISyntaxException {
    PushOperationSpecification spec = new PushOperationSpecification();
    Collection<RemoteRefUpdate> updates = Transport.findRemoteRefUpdatesFor(repository,
            Collections.singletonList(new RefSpec(refSpec)), null);

    RemoteConfig config = new RemoteConfig(repository.getConfig(), "origin");

    for (URIish uri : config.getPushURIs()) {
        spec.addURIRefUpdates(uri, updates);
        break;//from   w  w w  .  ja v  a  2 s  .c o m
    }
    if (spec.getURIsNumber() == 0) {
        for (URIish uri : config.getURIs()) {
            spec.addURIRefUpdates(uri, updates);
            break;
        }
    }
    if (spec.getURIsNumber() == 0) {
        throw new RuntimeException("Cannot find URI for push");
    }
    return spec;
}

From source file:com.genuitec.eclipse.gerrit.tools.internal.gps.model.GpsGitRepositoriesConfig.java

License:Open Source License

private String getRepoUrl(Repository repository) {
    try {/*w ww  .  j a v a 2  s. c o  m*/
        RemoteConfig config = new RemoteConfig(repository.getConfig(), "origin"); //$NON-NLS-1$
        for (URIish uri : config.getURIs()) {
            if (uri.getUser() != null) {
                return uri.setUser("user-name").toASCIIString(); //$NON-NLS-1$
            }
            return uri.toASCIIString();
        }
    } catch (Exception e) {
        GerritToolsPlugin.getDefault().log(e);
    }
    return null;
}

From source file:com.genuitec.eclipse.gerrit.tools.utils.GerritUtils.java

License:Open Source License

public static String getGerritProjectName(Repository repository) {
    try {/*  ww  w .j av a 2 s  . c  o m*/
        RemoteConfig config = new RemoteConfig(repository.getConfig(), "origin"); //$NON-NLS-1$

        List<URIish> urls = new ArrayList<URIish>(config.getPushURIs());
        urls.addAll(config.getURIs());

        for (URIish uri : urls) {
            if (uri.getPort() == 29418) { //Gerrit refspec
                String path = uri.getPath();
                while (path.startsWith("/")) { //$NON-NLS-1$
                    path = path.substring(1);
                }
                return path;
            }
            break;
        }
    } catch (Exception e) {
        GerritToolsPlugin.getDefault().log(e);
    }
    return null;
}

From source file:com.genuitec.eclipse.gerrit.tools.utils.GerritUtils.java

License:Open Source License

public static String getGerritURL(Repository repository) {
    String best = null;//from  ww  w.  j  a v  a  2  s . co  m
    try {
        RemoteConfig config = new RemoteConfig(repository.getConfig(), "origin"); //$NON-NLS-1$

        List<URIish> urls = new ArrayList<URIish>(config.getPushURIs());
        urls.addAll(config.getURIs());

        for (URIish uri : urls) {
            best = "https://" + uri.getHost(); //$NON-NLS-1$
            if (uri.getPort() == 29418) { //Gerrit refspec
                return best;
            }
            break;
        }
    } catch (Exception e) {
        GerritToolsPlugin.getDefault().log(e);
    }
    return best;
}

From source file:com.google.gdt.eclipse.gph.egit.wizard.CloneRepositoryWizardPage.java

License:Open Source License

private File getLocalDirForRepo(String repoURL) {
    RepositoryUtil repoUtil = Activator.getDefault().getRepositoryUtil();

    for (String configuredRepo : repoUtil.getConfiguredRepositories()) {
        try {/*ww w. j av a2 s  .c om*/
            File repoFile = new File(configuredRepo);

            Repository repository = Activator.getDefault().getRepositoryCache().lookupRepository(repoFile);

            try {
                RemoteConfig originConfig = new RemoteConfig(repository.getConfig(), "origin");

                for (URIish uri : originConfig.getURIs()) {
                    String uriStr = uri.toString();

                    if (repoURL.equals(uriStr)) {
                        return repoFile.getParentFile();
                    }
                }
            } catch (URISyntaxException exception) {

            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

    return null;
}

From source file:com.google.gerrit.server.git.PushReplication.java

License:Apache License

private List<ReplicationConfig> allConfigs(final SitePaths site) throws ConfigInvalidException, IOException {
    final FileBasedConfig cfg = new FileBasedConfig(site.replication_config, FS.DETECTED);

    if (!cfg.getFile().exists()) {
        log.warn("No " + cfg.getFile() + "; not replicating");
        return Collections.emptyList();
    }//from w w w  . j a  va2s. c  om
    if (cfg.getFile().length() == 0) {
        log.info("Empty " + cfg.getFile() + "; not replicating");
        return Collections.emptyList();
    }

    try {
        cfg.load();
    } catch (ConfigInvalidException e) {
        throw new ConfigInvalidException("Config file " + cfg.getFile() + " is invalid: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new IOException("Cannot read " + cfg.getFile() + ": " + e.getMessage(), e);
    }

    final List<ReplicationConfig> r = new ArrayList<ReplicationConfig>();
    for (final RemoteConfig c : allRemotes(cfg)) {
        if (c.getURIs().isEmpty()) {
            continue;
        }

        for (final URIish u : c.getURIs()) {
            if (u.getPath() == null || !u.getPath().contains("${name}")) {
                throw new ConfigInvalidException("remote." + c.getName() + ".url" + " \"" + u
                        + "\" lacks ${name} placeholder in " + cfg.getFile());
            }
        }

        // In case if refspec destination for push is not set then we assume it is
        // equal to source
        for (RefSpec ref : c.getPushRefSpecs()) {
            if (ref.getDestination() == null) {
                ref.setDestination(ref.getSource());
            }
        }

        if (c.getPushRefSpecs().isEmpty()) {
            RefSpec spec = new RefSpec();
            spec = spec.setSourceDestination("refs/*", "refs/*");
            spec = spec.setForceUpdate(true);
            c.addPushRefSpec(spec);
        }

        r.add(new ReplicationConfig(injector, workQueue, c, cfg, database, replicationUserFactory));
    }
    return Collections.unmodifiableList(r);
}

From source file:com.google.jenkins.plugins.gitnotes.GitNotesJobLogger.java

License:Open Source License

/**
 * Helper function to write the given message to git-notes.
 *//*from  w ww . j  a v  a 2s .c  o m*/
private void writeGitNoteMessage(AbstractBuild<?, ?> build, final BuildListener listener,
        GitNotesCiMessage message, GitSCM gitScm) {
    try {
        final GitClient gitClient = gitScm.createClient(listener, build.getEnvironment(listener), build,
                build.getWorkspace());

        RemoteConfig remoteConfig = gitScm.getRepositoryByName(GIT_REPO_ORIGIN);

        if (remoteConfig == null) {
            listener.getLogger().println("Failed to find Git repository.");
            return;
        }

        URIish remoteURI = remoteConfig.getURIs().get(0);
        try {
            ArrayList<RefSpec> refs = new ArrayList<RefSpec>();
            refs.add(new RefSpec(String.format("+%s:%s", GIT_NOTES_REFS, GIT_NOTES_REFS)));
            FetchCommand fetch = gitClient.fetch_().from(remoteURI, refs);
            fetch.execute();
        } catch (GitException e) {
            // This could be a normal case, when the remote doesn't have the
            // expected git-notes reference yet. The git library doesn't return
            // a dedicated exception type for "reference not found", so we
            // would just ignore all GitExceptions here.
            listener.getLogger().printf(
                    "Caught GitException: %s. Most likely remote doesn't have " + "git notes reference %s",
                    e.getMessage(), GIT_NOTES_REFS);
        }
        if (!gitClient.refExists(GIT_NOTES_REFS)) {
            try {
                gitClient.ref(GIT_NOTES_REFS);
                PushCommand push = gitClient.push().to(remoteURI).ref(GIT_NOTES_REFS);
                push.execute();
            } catch (GitException e) {
                // if the push failed, we should remove locally created GIT_NOTES_REFS
                listener.getLogger().printf("Failed to push %s, removing locally created notes refs",
                        GIT_NOTES_REFS);
                gitClient.deleteRef(GIT_NOTES_REFS);
                throw e;
            }
        }
        gitClient.appendNote(message.toString(), GIT_NOTES_REFS);

        PushCommand push = gitClient.push().to(remoteURI).ref(GIT_NOTES_REFS);
        push.execute();
    } catch (GitException e) {
        e.printStackTrace(listener.error("Caught git-notes exception. " + e.getMessage()));
    } catch (IOException e) {
        e.printStackTrace(listener.error(e.getMessage()));
    } catch (InterruptedException e) {
        e.printStackTrace(listener.error(e.getMessage()));
    }
}