Example usage for org.eclipse.jgit.transport URIish setUser

List of usage examples for org.eclipse.jgit.transport URIish setUser

Introduction

In this page you can find the example usage for org.eclipse.jgit.transport URIish setUser.

Prototype

public URIish setUser(String n) 

Source Link

Document

Return a new URI matching this one, but with a different user.

Usage

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

License:Open Source License

private String getRepoUrl(Repository repository) {
    try {//w w  w. jav  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.internal.gps.model.GpsGitRepositoriesConfig.java

License:Open Source License

public void performConfiguration(Map<String, Object> options, SubMonitor monitor) throws CoreException {
    monitor.beginTask("", repo2branch.size() * 2);
    for (Entry<String, RepoSetup> entry : repo2branch.entrySet()) {
        if (monitor.isCanceled())
            return;

        RepoSetup repo = entry.getValue();

        String repositoryName = repo.name;
        String repositoryBranch = repo.branch;
        boolean localBranch = repositoryBranch.startsWith("refs/heads/"); //$NON-NLS-1$
        String branchName = null;
        if (localBranch) {
            branchName = repositoryBranch.substring(11);
        }/*ww  w . j a v  a  2  s  .  c  o  m*/
        switch (repo.state) {
        case LOCATED:
            org.eclipse.egit.ui.Activator.getDefault().getRepositoryUtil()
                    .addConfiguredRepository(new File(repo.location, ".git")); //$NON-NLS-1$
            break;
        case CLONE:
            monitor.setTaskName("Cloning repository " + repositoryName);
            monitor.subTask("");
            try {
                URIish uri = new URIish(repo.url);
                if (repo.userName != null) {
                    uri = uri.setUser(repo.userName);
                } else {
                    uri = uri.setUser(null);
                }
                CloneOperation co = new CloneOperation(uri, true, null, repo.location, repositoryBranch,
                        "origin", 5000); //$NON-NLS-1$
                co.setCredentialsProvider(new EGitCredentialsProvider());
                co.setCloneSubmodules(true);
                co.run(new SubProgressMonitor(monitor, 0, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK));

                org.eclipse.egit.ui.Activator.getDefault().getRepositoryUtil()
                        .addConfiguredRepository(co.getGitDir());

                break;
            } catch (Throwable e) {
                if (e instanceof InvocationTargetException) {
                    e = e.getCause();
                }
                throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID,
                        (e instanceof InterruptedException) ? "Operation cancelled" : e.getMessage(), e));
            }
        default:
        }

        monitor.setTaskName("Preparing repository " + repositoryName);

        Repository repository = RepositoryUtils.getRepositoryForName(repositoryName);
        if (repository == null) {
            throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID,
                    MessageFormat.format(
                            "Cannot continue. A required git repository named {0} is not configured.",
                            repositoryName)));
        }

        monitor.subTask(MessageFormat.format("Checking out branch \"{0}\" of git repository \"{1}\"",
                repositoryBranch, repositoryName));

        if (repositoryBranch != null && repositoryBranch.length() > 0) {
            //checkout the branch
            boolean newBranch = false;
            try {
                Ref ref = repository.getRef(repositoryBranch);
                if (localBranch && ref == null) {
                    String originBranch = "refs/remotes/origin/" + branchName; //$NON-NLS-1$
                    ref = repository.getRef(originBranch);
                    if (ref == null) {
                        try {
                            new Git(repository).fetch().setRemote("origin").call(); //$NON-NLS-1$
                        } catch (Exception e) {
                            throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID,
                                    MessageFormat.format(
                                            "Cannot fetch from remote 'origin' of repository \"{0}\":\n{1}",
                                            repositoryName, e.getMessage(), e)));
                        }
                    }
                    ref = repository.getRef(originBranch);
                    if (ref == null) {
                        throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID,
                                MessageFormat.format("Cannot find branch \"{1}\" in repository \"{0}\".",
                                        repositoryName, originBranch)));
                    }
                    //we need to create the local branch based on remote branch
                    new Git(repository).branchCreate().setName(branchName).setStartPoint(originBranch)
                            .setUpstreamMode(SetupUpstreamMode.TRACK).call();
                    newBranch = true;
                }
                if (monitor.isCanceled())
                    return;

                try {
                    new Git(repository).checkout().setName(repositoryBranch).call();
                } catch (Exception e) {
                    if (options.containsKey(PROP_FORCE_CHECKOUT)
                            && (Boolean) options.get(PROP_FORCE_CHECKOUT)) {
                        //try to reset
                        new Git(repository).reset().setMode(ResetType.HARD).call();

                        //and then checkout again
                        new Git(repository).checkout().setName(repositoryBranch).call();
                    } else {
                        throw e;
                    }
                }

                int fileCount = repository.getDirectory().getParentFile().list().length;
                if (fileCount == 1) {
                    //we need to hard reset the repository - there are no files in it
                    new Git(repository).reset().setMode(ResetType.HARD).call();
                }

            } catch (Exception e) {
                throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID,
                        MessageFormat.format("Cannot checkout branch \"{1}\" of repository \"{0}\":\n{2}",
                                repositoryName, repositoryBranch, e.getMessage(), e)));
            }
            if (monitor.isCanceled())
                return;

            if (localBranch) {
                monitor.subTask(MessageFormat.format("Configuring branch \"{0}\" of git repository \"{1}\"",
                        repositoryBranch, repositoryName));
                try {
                    StoredConfig config = repository.getConfig();

                    if (options.get(PROP_CONFIGURE_PUSH_TO_UPSTREAM) != null
                            && (Boolean) options.get(PROP_CONFIGURE_PUSH_TO_UPSTREAM)) {
                        //configure push to upstream
                        config.setString("remote", "origin", "push", //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
                                repositoryBranch + ":refs/for/" + branchName); //$NON-NLS-1$
                    }
                    if (newBranch || (options.get(PROP_RECONFIGURE_BRANCH) != null
                            && (Boolean) options.get(PROP_RECONFIGURE_BRANCH))) {
                        config.setString("branch", branchName, "remote", "origin"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                        config.setString("branch", branchName, "merge", repositoryBranch); //$NON-NLS-1$ //$NON-NLS-2$
                        config.setString("branch", branchName, "rebase", "true"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                    }
                    config.save();
                } catch (Exception e) {
                    throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID,
                            MessageFormat.format("Cannot configure branch \"{1}\" of repository \"{0}\":\n{2}",
                                    repositoryName, repositoryBranch, e.getMessage(), e)));
                }
            }
            if (monitor.isCanceled())
                return;

            if (options.containsKey(PROP_AUTO_PULL) && (Boolean) options.get(PROP_AUTO_PULL)) {
                monitor.subTask(MessageFormat.format("Pulling branch \"{0}\" from git repository \"{1}\"",
                        repositoryBranch, repositoryName));

                try {
                    new Git(repository).pull().call();
                } catch (Exception e) {
                    throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID,
                            MessageFormat.format("Cannot pull branch \"{1}\" of repository \"{0}\":\n{2}",
                                    repositoryName, repositoryBranch, e.getMessage(), e)));
                }
            }
        }

        monitor.worked(1);
    }

}

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;/* w ww  . j av  a2  s.co  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.AuthSettings.java

License:Apache License

public URIish createAuthURI(final URIish uri, boolean fixErrors) {
    URIish result = uri;
    if (requiresCredentials(result)) {
        if (!StringUtil.isEmptyOrSpaces(myUserName)) {
            result = result.setUser(myUserName);
        }//w  w  w .  j a va2 s .  c  om
        if (!StringUtil.isEmpty(myPassword)) {
            result = result.setPass(myPassword);
        }
    }
    if (fixErrors && isAnonymousProtocol(result)) {
        result = result.setUser(null);
        result = result.setPass(null);
    }
    return result;
}

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

License:Apache License

@NotNull
private URIish prepareURI(@NotNull URIish uri) {
    final String scheme = uri.getScheme();
    //Remove a username from the http URI. A Username can contain forbidden
    //characters, e.g. backslash (TW-21747). A username and a password will
    //be supplied by CredentialProvider
    if ("http".equals(scheme) || "https".equals(scheme))
        return uri.setUser(null);
    return uri;//from ww w . j a  va 2 s .  c o m
}

From source file:org.eclipse.egit.core.securestorage.EGitSecureStore.java

License:Open Source License

private String calcNodePath(URIish uri) {
    URIish storedURI = uri.setUser(null).setPass(null);
    String pathName = GIT_PATH_PREFIX + EncodingUtils.encodeSlashes(storedURI.toString());
    return pathName;
}

From source file:org.sonatype.m2e.egit.internal.EgitScmHandler.java

License:Open Source License

protected URIish getUri(MavenProjectScmInfo info) throws URISyntaxException {
    String url = info.getRepositoryUrl();
    url = normalizeUri(url);//from  w  w w . j a v a 2s. com

    URIish uri = new URIish(url);

    if (isProtocolAuthAware(uri.getScheme()) && info.getUsername() != null && info.getUsername().length() > 0) {
        if (uri.getUser() == null || info.getUsername().equals(uri.getUser())) {
            uri = uri.setUser(info.getUsername());
        }
    }

    return uri;
}