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

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

Introduction

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

Prototype

public CloneCommand setBare(boolean bare) throws IllegalStateException 

Source Link

Document

Set whether the cloned repository shall be bare

Usage

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.
 * //from  www  . j av  a2 s.  c o  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.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   ww w .  jav  a2 s.com*/
 *
 * @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);//w ww .  j  a va  2  s  .  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 {//from  w w w .  ja va 2 s.  co  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 ava  2 s.c o m
    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);
}

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

License:Apache License

@Test
public void testAnonymousPush() throws Exception {
    GitBlitSuite.close(ticgitFolder);//from   w w  w . jav a2 s  .  c o  m
    if (ticgitFolder.exists()) {
        FileUtils.delete(ticgitFolder, FileUtils.RECURSIVE | FileUtils.RETRY);
    }

    RepositoryModel model = repositories().getRepositoryModel("ticgit.git");
    model.accessRestriction = AccessRestrictionType.NONE;
    repositories().updateRepositoryModel(model.name, model, false);

    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);

    Git git = Git.open(ticgitFolder);
    File file = new File(ticgitFolder, "TODO");
    OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(file, true), Constants.CHARSET);
    BufferedWriter w = new BufferedWriter(os);
    w.write("// hellol " + new Date().toString() + "\n");
    w.close();
    git.add().addFilepattern(file.getName()).call();
    git.commit().setMessage("test commit").call();
    Iterable<PushResult> results = git.push().setPushAll().call();
    GitBlitSuite.close(git);
    for (PushResult result : results) {
        for (RemoteRefUpdate update : result.getRemoteUpdates()) {
            assertEquals(Status.OK, update.getStatus());
        }
    }
}

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

License:Apache License

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

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

    Git git = Git.open(jgitFolder);
    File file = new File(jgitFolder, "TODO");
    OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(file, true), Constants.CHARSET);
    BufferedWriter w = new BufferedWriter(os);
    w.write("// " + new Date().toString() + "\n");
    w.close();
    git.add().addFilepattern(file.getName()).call();
    git.commit().setMessage("test commit").call();
    Iterable<PushResult> results = git.push().setPushAll()
            .setCredentialsProvider(new UsernamePasswordCredentialsProvider(account, password)).call();
    GitBlitSuite.close(git);
    for (PushResult result : results) {
        for (RemoteRefUpdate update : result.getRemoteUpdates()) {
            assertEquals(Status.OK, update.getStatus());
        }
    }
}

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

License:Apache License

@Test
public void testPushToFrozenRepo() throws Exception {
    GitBlitSuite.close(jgitFolder);// w ww.  java 2 s . co m
    if (jgitFolder.exists()) {
        FileUtils.delete(jgitFolder, FileUtils.RECURSIVE | FileUtils.RETRY);
    }

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

    // freeze repo
    RepositoryModel model = repositories().getRepositoryModel("test/jgit.git");
    model.isFrozen = true;
    repositories().updateRepositoryModel(model.name, model, false);

    Git git = Git.open(jgitFolder);
    File file = new File(jgitFolder, "TODO");
    OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(file, true), Constants.CHARSET);
    BufferedWriter w = new BufferedWriter(os);
    w.write("// " + new Date().toString() + "\n");
    w.close();
    git.add().addFilepattern(file.getName()).call();
    git.commit().setMessage("test commit").call();

    Iterable<PushResult> results = git.push().setPushAll()
            .setCredentialsProvider(new UsernamePasswordCredentialsProvider(account, password)).call();
    for (PushResult result : results) {
        for (RemoteRefUpdate update : result.getRemoteUpdates()) {
            assertEquals(Status.REJECTED_OTHER_REASON, update.getStatus());
        }
    }

    // unfreeze repo
    model.isFrozen = false;
    repositories().updateRepositoryModel(model.name, model, false);

    results = git.push().setPushAll()
            .setCredentialsProvider(new UsernamePasswordCredentialsProvider(account, password)).call();
    GitBlitSuite.close(git);
    for (PushResult result : results) {
        for (RemoteRefUpdate update : result.getRemoteUpdates()) {
            assertEquals(Status.OK, update.getStatus());
        }
    }
}

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

License:Apache License

@Test
public void testPushToNonBareRepository() throws Exception {
    CloneCommand clone = Git.cloneRepository();
    clone.setURI(MessageFormat.format("{0}/working/jgit", url));
    clone.setDirectory(jgit2Folder);/*from   w w w . j av  a 2s . co  m*/
    clone.setBare(false);
    clone.setCloneAllBranches(true);
    clone.setCredentialsProvider(new UsernamePasswordCredentialsProvider(account, password));
    GitBlitSuite.close(clone.call());
    assertTrue(true);

    Git git = Git.open(jgit2Folder);
    File file = new File(jgit2Folder, "NONBARE");
    OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(file, true), Constants.CHARSET);
    BufferedWriter w = new BufferedWriter(os);
    w.write("// " + new Date().toString() + "\n");
    w.close();
    git.add().addFilepattern(file.getName()).call();
    git.commit().setMessage("test commit followed by push to non-bare repository").call();
    Iterable<PushResult> results = git.push().setPushAll()
            .setCredentialsProvider(new UsernamePasswordCredentialsProvider(account, password)).call();
    GitBlitSuite.close(git);
    for (PushResult result : results) {
        for (RemoteRefUpdate update : result.getRemoteUpdates()) {
            assertEquals(Status.REJECTED_OTHER_REASON, update.getStatus());
        }
    }
}

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

License:Apache License

private void testCommitterVerification(UserModel user, String displayName, String emailAddress,
        boolean expectedSuccess) throws Exception {

    delete(user);/*from   w w w.  jav  a 2  s .  c om*/

    CredentialsProvider cp = new UsernamePasswordCredentialsProvider(user.username, user.password);

    // fork from original to a temporary bare repo
    File verification = new File(GitBlitSuite.REPOSITORIES, "refchecks/verify-committer.git");
    if (verification.exists()) {
        FileUtils.delete(verification, FileUtils.RECURSIVE);
    }
    CloneCommand clone = Git.cloneRepository();
    clone.setURI(MessageFormat.format("{0}/ticgit.git", url));
    clone.setDirectory(verification);
    clone.setBare(true);
    clone.setCloneAllBranches(true);
    clone.setCredentialsProvider(cp);
    GitBlitSuite.close(clone.call());

    // require push permissions and committer verification
    RepositoryModel model = repositories().getRepositoryModel("refchecks/verify-committer.git");
    model.authorizationControl = AuthorizationControl.NAMED;
    model.accessRestriction = AccessRestrictionType.PUSH;
    model.verifyCommitter = true;

    // grant user push permission
    user.setRepositoryPermission(model.name, AccessPermission.PUSH);

    gitblit().addUser(user);
    repositories().updateRepositoryModel(model.name, model, false);

    // clone temp bare repo to working copy
    File local = new File(GitBlitSuite.REPOSITORIES, "refchecks/verify-wc");
    if (local.exists()) {
        FileUtils.delete(local, FileUtils.RECURSIVE);
    }
    clone = Git.cloneRepository();
    clone.setURI(MessageFormat.format("{0}/{1}", url, model.name));
    clone.setDirectory(local);
    clone.setBare(false);
    clone.setCloneAllBranches(true);
    clone.setCredentialsProvider(cp);
    GitBlitSuite.close(clone.call());

    Git git = Git.open(local);

    // force an identity which may or may not match the account's identity
    git.getRepository().getConfig().setString("user", null, "name", displayName);
    git.getRepository().getConfig().setString("user", null, "email", emailAddress);
    git.getRepository().getConfig().save();

    // commit a file and push it
    File file = new File(local, "PUSHCHK");
    OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(file, true), Constants.CHARSET);
    BufferedWriter w = new BufferedWriter(os);
    w.write("// " + new Date().toString() + "\n");
    w.close();
    git.add().addFilepattern(file.getName()).call();
    git.commit().setMessage("push test").call();
    Iterable<PushResult> results = git.push().setCredentialsProvider(cp).setRemote("origin").call();

    for (PushResult result : results) {
        RemoteRefUpdate ref = result.getRemoteUpdate("refs/heads/master");
        Status status = ref.getStatus();
        if (expectedSuccess) {
            assertTrue("Verification failed! User was NOT able to push commit! " + status.name(),
                    Status.OK.equals(status));
        } else {
            assertTrue("Verification failed! User was able to push commit! " + status.name(),
                    Status.REJECTED_OTHER_REASON.equals(status));
        }
    }

    GitBlitSuite.close(git);
    // close serving repository
    GitBlitSuite.close(verification);
}