Example usage for org.eclipse.jgit.api CloneCommand setDirectory

List of usage examples for org.eclipse.jgit.api CloneCommand setDirectory

Introduction

In this page you can find the example usage for org.eclipse.jgit.api CloneCommand setDirectory.

Prototype

public CloneCommand setDirectory(File directory) 

Source Link

Document

The optional directory associated with the clone operation.

Usage

From source file:bluej.groupwork.git.GitCloneCommand.java

License:Open Source License

@Override
public TeamworkCommandResult getResult() {

    try {//from w  w  w.jav a  2s .co  m
        String reposUrl = getRepository().getReposUrl();
        CloneCommand cloneCommand = Git.cloneRepository();
        disableFingerprintCheck(cloneCommand);
        cloneCommand.setDirectory(clonePath);
        cloneCommand.setURI(reposUrl);
        StoredConfig repoConfig = cloneCommand.call().getRepository().getConfig(); //save the repo
        repoConfig.setString("user", null, "name", getRepository().getYourName()); //register the user name
        repoConfig.setString("user", null, "email", getRepository().getYourEmail()); //register the user email
        repoConfig.save();

        if (!isCancelled()) {
            return new TeamworkCommandResult();
        }

        return new TeamworkCommandAborted();
    } catch (GitAPIException | IOException ex) {
        return new TeamworkCommandError(ex.getMessage(), ex.getLocalizedMessage());
    }
}

From source file:com.bb.extensions.plugin.unittests.internal.git.GitWrapper.java

License:Open Source License

/**
 * Clones the git repository located at the given url to the given path.
 * // ww  w .j  ava2 s  . co m
 * @param path
 * 
 * @param url
 * @return The GitWrapper to interact with the clone git repository.
 * @throws IllegalArgumentException
 */
public static GitWrapper cloneRepository(String path, String url) throws IllegalArgumentException {
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    File gitDir = new File(path);
    if (gitDir.exists() == false) {
        gitDir.mkdir();
    } else if (gitDir.list().length > 0) {
        if (isGitRepository(gitDir)) {
            return openRepository(path);
        } else {
            throw new IllegalArgumentException("Cannot clone to a non-empty directory");
        }
    }
    Repository repository;
    try {
        repository = builder.setGitDir(gitDir).readEnvironment().findGitDir().build();
        GitWrapper gitWrapper = new GitWrapper();
        gitWrapper.git = new Git(repository);
        CloneCommand clone = Git.cloneRepository();
        clone.setBare(false);
        clone.setCloneAllBranches(true);
        clone.setDirectory(gitDir).setURI(url);
        // we have to close the newly returned Git object as call() creates
        // a new one every time
        clone.call().getRepository().close();
        return gitWrapper;
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InvalidRemoteException e) {
        e.printStackTrace();
    } catch (TransportException e) {
        e.printStackTrace();
    } catch (GitAPIException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.ejwa.gitdepmavenplugin.DownloaderMojo.java

License:Open Source License

private Git clone(Pom pom, GitDependency dependency) throws MojoExecutionException {
    final CloneCommand c = new CloneCommand();
    final String location = dependency.getLocation();

    c.setURI(location);//from   ww  w.ja  va2s .c om
    c.setCloneAllBranches(true);
    c.setProgressMonitor(new TextProgressMonitor());

    final GitDependencyHandler dependencyHandler = new GitDependencyHandler(dependency);
    final String version = dependencyHandler.getDependencyVersion(pom);
    final String tempDirectory = Directory.getTempDirectoryString(location, version);

    c.setDirectory(new File(tempDirectory));
    return c.call();
}

From source file:com.ejwa.mavengitdepplugin.DownloaderMojo.java

License:Open Source License

private Git clone(POM pom, GitDependency dependency) {
    final CloneCommand c = new CloneCommand();

    c.setURI(dependency.getLocation());/* ww w .  j  a  v a  2s .  com*/
    c.setCloneAllBranches(true);
    c.setProgressMonitor(new TextProgressMonitor());

    final GitDependencyHandler dependencyHandler = new GitDependencyHandler(dependency);
    final String version = dependencyHandler.getDependencyVersion(pom);
    final String tempDirectory = Directory.getTempDirectoryString(dependency.getLocation(), version);
    c.setDirectory(new File(tempDirectory));

    return c.call();
}

From source file:com.fanniemae.ezpie.common.GitOperations.java

License:Open Source License

public String cloneHTTP(String repo_url, String destination, String userID, String password, String branch)
        throws InvalidRemoteException, TransportException, GitAPIException, URISyntaxException {

    _repositoryHost = getHost(repo_url);
    setupProxy();// w  w  w .j  a v  a  2 s  .com

    File localDir = new File(destination);
    CloneCommand cloneCommand = Git.cloneRepository();
    cloneCommand.setURI(repo_url);
    cloneCommand.setDirectory(localDir);

    if (StringUtilities.isNotNullOrEmpty(branch))
        cloneCommand.setBranch(branch);

    if (StringUtilities.isNotNullOrEmpty(userID))
        cloneCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(userID, password));

    try (Writer writer = new StringWriter()) {
        TextProgressMonitor tpm = new TextProgressMonitor(writer);
        cloneCommand.setProgressMonitor(tpm);
        try (Git result = cloneCommand.call()) {
        }
        clearProxyAuthenticatorCache();
        writer.flush();
        return writer.toString();
    } catch (IOException e) {
        throw new PieException("Error while trying to clone the git repository. " + e.getMessage(), e);
    }
}

From source file:com.fanniemae.ezpie.common.GitOperations.java

License:Open Source License

public String cloneSSH(String repo_url, String destination, String privateKey, String password, String branch) {
    if (_useProxy) {
        throw new PieException(
                "Network proxies do not support SSH, please use an http url to clone this repository.");
    }//from  ww w.ja v  a 2 s .  com

    final SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
        @Override
        protected void configure(Host host, Session session) {
            // This still checks existing host keys and will disable "unsafe"
            // authentication mechanisms if the host key doesn't match.
            session.setConfig("StrictHostKeyChecking", "no");
        }

        @Override
        protected JSch createDefaultJSch(FS fs) throws JSchException {
            JSch defaultJSch = super.createDefaultJSch(fs);
            defaultJSch.addIdentity(privateKey, password);
            return defaultJSch;
        }
    };

    CloneCommand cloneCommand = Git.cloneRepository();
    cloneCommand.setURI(repo_url);
    File dir = new File(destination);
    cloneCommand.setDirectory(dir);

    if (StringUtilities.isNotNullOrEmpty(branch))
        cloneCommand.setBranch(branch);

    cloneCommand.setTransportConfigCallback(new TransportConfigCallback() {
        public void configure(Transport transport) {
            SshTransport sshTransport = (SshTransport) transport;
            sshTransport.setSshSessionFactory(sshSessionFactory);
        }
    });

    try (Writer writer = new StringWriter()) {
        TextProgressMonitor tpm = new TextProgressMonitor(writer);
        cloneCommand.setProgressMonitor(tpm);
        try (Git result = cloneCommand.call()) {
        }
        writer.flush();
        return writer.toString();
    } catch (IOException | GitAPIException e) {
        throw new PieException("Error while trying to clone the git repository. " + e.getMessage(), e);
    }
}

From source file:com.gitblit.manager.GitblitManager.java

License:Apache License

/**
 * Creates a personal fork of the specified repository. The clone is view
 * restricted by default and the owner of the source repository is given
 * access to the clone.//from   w w w  .  j a va  2  s  .  co m
 *
 * @param repository
 * @param user
 * @return the repository model of the fork, if successful
 * @throws GitBlitException
 */
@Override
public RepositoryModel fork(RepositoryModel repository, UserModel user) throws GitBlitException {
    String cloneName = MessageFormat.format("{0}/{1}.git", user.getPersonalPath(),
            StringUtils.stripDotGit(StringUtils.getLastPathElement(repository.name)));
    String fromUrl = MessageFormat.format("file://{0}/{1}",
            repositoryManager.getRepositoriesFolder().getAbsolutePath(), repository.name);

    // clone the repository
    try {
        Repository canonical = getRepository(repository.name);
        File folder = new File(repositoryManager.getRepositoriesFolder(), cloneName);
        CloneCommand clone = new CloneCommand();
        clone.setBare(true);

        // fetch branches with exclusions
        Collection<Ref> branches = canonical.getRefDatabase().getRefs(Constants.R_HEADS).values();
        List<String> branchesToClone = new ArrayList<String>();
        for (Ref branch : branches) {
            String name = branch.getName();
            if (name.startsWith(Constants.R_TICKET)) {
                // exclude ticket branches
                continue;
            }
            branchesToClone.add(name);
        }
        clone.setBranchesToClone(branchesToClone);
        clone.setURI(fromUrl);
        clone.setDirectory(folder);
        Git git = clone.call();

        // fetch tags
        FetchCommand fetch = git.fetch();
        fetch.setRefSpecs(new RefSpec("+refs/tags/*:refs/tags/*"));
        fetch.call();

        git.getRepository().close();
    } catch (Exception e) {
        throw new GitBlitException(e);
    }

    // create a Gitblit repository model for the clone
    RepositoryModel cloneModel = repository.cloneAs(cloneName);
    // owner has REWIND/RW+ permissions
    cloneModel.addOwner(user.username);

    // ensure initial access restriction of the fork
    // is not lower than the source repository  (issue-495/ticket-167)
    if (repository.accessRestriction.exceeds(cloneModel.accessRestriction)) {
        cloneModel.accessRestriction = repository.accessRestriction;
    }

    repositoryManager.updateRepositoryModel(cloneName, cloneModel, false);

    // add the owner of the source repository to the clone's access list
    if (!ArrayUtils.isEmpty(repository.owners)) {
        for (String owner : repository.owners) {
            UserModel originOwner = userManager.getUserModel(owner);
            if (originOwner != null && !originOwner.canClone(cloneModel)) {
                // origin owner can't yet clone fork, grant explicit clone access
                originOwner.setRepositoryPermission(cloneName, AccessPermission.CLONE);
                reviseUser(originOwner.username, originOwner);
            }
        }
    }

    // grant origin's user list clone permission to fork
    List<String> users = repositoryManager.getRepositoryUsers(repository);
    List<UserModel> cloneUsers = new ArrayList<UserModel>();
    for (String name : users) {
        if (!name.equalsIgnoreCase(user.username)) {
            UserModel cloneUser = userManager.getUserModel(name);
            if (cloneUser.canClone(repository) && !cloneUser.canClone(cloneModel)) {
                // origin user can't yet clone fork, grant explicit clone access
                cloneUser.setRepositoryPermission(cloneName, AccessPermission.CLONE);
            }
            cloneUsers.add(cloneUser);
        }
    }
    userManager.updateUserModels(cloneUsers);

    // grant origin's team list clone permission to fork
    List<String> teams = repositoryManager.getRepositoryTeams(repository);
    List<TeamModel> cloneTeams = new ArrayList<TeamModel>();
    for (String name : teams) {
        TeamModel cloneTeam = userManager.getTeamModel(name);
        if (cloneTeam.canClone(repository) && !cloneTeam.canClone(cloneModel)) {
            // origin team can't yet clone fork, grant explicit clone access
            cloneTeam.setRepositoryPermission(cloneName, AccessPermission.CLONE);
        }
        cloneTeams.add(cloneTeam);
    }
    userManager.updateTeamModels(cloneTeams);

    // add this clone to the cached model
    repositoryManager.addToCachedRepositoryList(cloneModel);

    if (pluginManager != null) {
        for (RepositoryLifeCycleListener listener : pluginManager
                .getExtensions(RepositoryLifeCycleListener.class)) {
            try {
                listener.onFork(repository, cloneModel);
            } catch (Throwable t) {
                logger.error(String.format("failed to call plugin onFork %s", repository.name), t);
            }
        }
    }
    return cloneModel;
}

From source file:com.gitblit.servlet.GitServletTest.java

License:Apache License

@Test
public void testClone() throws Exception {
    GitBlitSuite.close(ticgitFolder);/*from w  w w.j a  v  a 2s. c  o m*/
    if (ticgitFolder.exists()) {
        FileUtils.delete(ticgitFolder, FileUtils.RECURSIVE | FileUtils.RETRY);
    }

    CloneCommand clone = Git.cloneRepository();
    clone.setURI(MessageFormat.format("{0}/ticgit.git", url));
    clone.setDirectory(ticgitFolder);
    clone.setBare(false);
    clone.setCloneAllBranches(true);
    clone.setCredentialsProvider(new UsernamePasswordCredentialsProvider(account, password));
    GitBlitSuite.close(clone.call());
    assertTrue(true);
}

From source file:com.gitblit.servlet.GitServletTest.java

License:Apache License

@Test
public void testBogusLoginClone() throws Exception {
    // restrict repository access
    RepositoryModel model = repositories().getRepositoryModel("ticgit.git");
    model.accessRestriction = AccessRestrictionType.CLONE;
    repositories().updateRepositoryModel(model.name, model, false);

    // delete any existing working folder
    boolean cloned = false;
    try {//  ww  w.  j  a  v  a2  s  . c  o m
        CloneCommand clone = Git.cloneRepository();
        clone.setURI(MessageFormat.format("{0}/ticgit.git", url));
        clone.setDirectory(ticgit2Folder);
        clone.setBare(false);
        clone.setCloneAllBranches(true);
        clone.setCredentialsProvider(new UsernamePasswordCredentialsProvider("bogus", "bogus"));
        GitBlitSuite.close(clone.call());
        cloned = true;
    } catch (Exception e) {
        // swallow the exception which we expect
    }

    // restore anonymous repository access
    model.accessRestriction = AccessRestrictionType.NONE;
    repositories().updateRepositoryModel(model.name, model, false);

    assertFalse("Bogus login cloned a repository?!", cloned);
}

From source file:com.gitblit.servlet.GitServletTest.java

License:Apache License

@Test
public void testUnauthorizedLoginClone() throws Exception {
    // restrict repository access
    RepositoryModel model = repositories().getRepositoryModel("ticgit.git");
    model.accessRestriction = AccessRestrictionType.CLONE;
    model.authorizationControl = AuthorizationControl.NAMED;
    UserModel user = new UserModel("james");
    user.password = "james";
    gitblit().addUser(user);//  w  w w .j  a v  a  2  s .com
    repositories().updateRepositoryModel(model.name, model, false);

    FileUtils.delete(ticgit2Folder, FileUtils.RECURSIVE);

    // delete any existing working folder
    boolean cloned = false;
    try {
        CloneCommand clone = Git.cloneRepository();
        clone.setURI(MessageFormat.format("{0}/ticgit.git", url));
        clone.setDirectory(ticgit2Folder);
        clone.setBare(false);
        clone.setCloneAllBranches(true);
        clone.setCredentialsProvider(new UsernamePasswordCredentialsProvider(user.username, user.password));
        GitBlitSuite.close(clone.call());
        cloned = true;
    } catch (Exception e) {
        // swallow the exception which we expect
    }

    assertFalse("Unauthorized login cloned a repository?!", cloned);

    FileUtils.delete(ticgit2Folder, FileUtils.RECURSIVE);

    // switch to authenticated
    model.authorizationControl = AuthorizationControl.AUTHENTICATED;
    repositories().updateRepositoryModel(model.name, model, false);

    // try clone again
    cloned = false;
    CloneCommand clone = Git.cloneRepository();
    clone.setURI(MessageFormat.format("{0}/ticgit.git", url));
    clone.setDirectory(ticgit2Folder);
    clone.setBare(false);
    clone.setCloneAllBranches(true);
    clone.setCredentialsProvider(new UsernamePasswordCredentialsProvider(user.username, user.password));
    GitBlitSuite.close(clone.call());
    cloned = true;

    assertTrue("Authenticated login could not clone!", cloned);

    FileUtils.delete(ticgit2Folder, FileUtils.RECURSIVE);

    // restore anonymous repository access
    model.accessRestriction = AccessRestrictionType.NONE;
    model.authorizationControl = AuthorizationControl.NAMED;
    repositories().updateRepositoryModel(model.name, model, false);

    delete(user);
}