Example usage for org.eclipse.jgit.api Git cloneRepository

List of usage examples for org.eclipse.jgit.api Git cloneRepository

Introduction

In this page you can find the example usage for org.eclipse.jgit.api Git cloneRepository.

Prototype

public static CloneCommand cloneRepository() 

Source Link

Document

Return a command object to execute a clone command

Usage

From source file:com.gitblit.tests.GitDaemonTest.java

License:Apache License

@Test
public void testAnonymousClone() throws Exception {
    GitBlitSuite.close(ticgitFolder);//from   ww w. j  av  a  2s .  com
    if (ticgitFolder.exists()) {
        FileUtils.delete(ticgitFolder, FileUtils.RECURSIVE | FileUtils.RETRY);
    }

    // set push restriction
    RepositoryModel model = repositories().getRepositoryModel("ticgit.git");
    model.accessRestriction = AccessRestrictionType.PUSH;
    model.authorizationControl = AuthorizationControl.NAMED;
    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);
    GitBlitSuite.close(clone.call());
    assertTrue(true);

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

From source file:com.gitblit.tests.GitDaemonTest.java

License:Apache License

@Test
public void testCloneRestrictedRepo() throws Exception {
    GitBlitSuite.close(ticgit2Folder);/*from w w  w. j  a va2 s . co  m*/
    if (ticgit2Folder.exists()) {
        FileUtils.delete(ticgit2Folder, FileUtils.RECURSIVE);
    }

    // restrict repository access
    RepositoryModel model = repositories().getRepositoryModel("ticgit.git");
    model.accessRestriction = AccessRestrictionType.CLONE;
    model.authorizationControl = AuthorizationControl.NAMED;
    repositories().updateRepositoryModel(model.name, model, false);

    // 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);
        GitBlitSuite.close(clone.call());
        cloned = true;
    } catch (Exception e) {
        // swallow the exception which we expect
    }

    assertFalse("Anonymous was able to clone the repository?!", cloned);

    FileUtils.delete(ticgit2Folder, FileUtils.RECURSIVE);

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

From source file:com.gitblit.tests.GitDaemonTest.java

License:Apache License

@Test
public void testAnonymousPush() throws Exception {
    GitBlitSuite.close(ticgitFolder);/*w  ww.  ja v  a 2  s.  c  om*/
    if (ticgitFolder.exists()) {
        FileUtils.delete(ticgitFolder, FileUtils.RECURSIVE | FileUtils.RETRY);
    }

    // restore anonymous repository access
    RepositoryModel model = repositories().getRepositoryModel("ticgit.git");
    model.accessRestriction = AccessRestrictionType.NONE;
    model.authorizationControl = AuthorizationControl.NAMED;
    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);
    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.tests.GitDaemonTest.java

License:Apache License

@Test
public void testPushRestrictedRepo() throws Exception {
    GitBlitSuite.close(ticgitFolder);//  w  w w  . ja va 2s  .co  m
    if (ticgitFolder.exists()) {
        FileUtils.delete(ticgitFolder, FileUtils.RECURSIVE | FileUtils.RETRY);
    }

    // restore anonymous repository access
    RepositoryModel model = repositories().getRepositoryModel("ticgit.git");
    model.accessRestriction = AccessRestrictionType.PUSH;
    model.authorizationControl = AuthorizationControl.NAMED;
    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);
    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.REJECTED_OTHER_REASON, update.getStatus());
        }
    }
}

From source file:com.gitblit.tests.GitDaemonTest.java

License:Apache License

@Test
public void testPushToFrozenRepo() throws Exception {
    GitBlitSuite.close(jgitFolder);/* ww w .  ja va 2 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);
    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().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().call();
    GitBlitSuite.close(git);
    for (PushResult result : results) {
        for (RemoteRefUpdate update : result.getRemoteUpdates()) {
            assertEquals(Status.OK, update.getStatus());
        }
    }
}

From source file:com.gitblit.tests.GitDaemonTest.java

License:Apache License

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

    CloneCommand clone = Git.cloneRepository();
    clone.setURI(MessageFormat.format("{0}/working/jgit", url));
    clone.setDirectory(jgit2Folder);
    clone.setBare(false);
    clone.setCloneAllBranches(true);
    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().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.tests.SshDaemonTest.java

License:Apache License

@Test
public void testCloneCommand() throws Exception {
    if (ticgitFolder.exists()) {
        GitBlitSuite.close(ticgitFolder);
        FileUtils.delete(ticgitFolder, FileUtils.RECURSIVE);
    }/*from  w  ww.j a  v a 2 s  . c  om*/

    // set clone restriction
    RepositoryModel model = repositories().getRepositoryModel("ticgit.git");
    model.accessRestriction = AccessRestrictionType.CLONE;
    model.authorizationControl = AuthorizationControl.NAMED;
    repositories().updateRepositoryModel(model.name, model, false);

    JschConfigTestSessionFactory sessionFactory = new JschConfigTestSessionFactory(roKeyPair);
    SshSessionFactory.setInstance(sessionFactory);

    CloneCommand clone = Git.cloneRepository();
    clone.setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password));
    clone.setURI(MessageFormat.format("{0}/ticgit.git", url));
    clone.setDirectory(ticgitFolder);
    clone.setBare(false);
    clone.setCloneAllBranches(true);
    Git git = clone.call();
    List<RevCommit> commits = JGitUtils.getRevLog(git.getRepository(), 10);
    GitBlitSuite.close(git);
    assertEquals(10, commits.size());

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

From source file:com.gitblit.tests.TicketReferenceTest.java

License:Apache License

@BeforeClass
public static void configure() throws Exception {
    File repositoryName = new File("TicketReferenceTest.git");
    ;/*from ww  w.  j  a v a 2  s  .  c o m*/

    GitBlitSuite.close(repositoryName);
    if (repositoryName.exists()) {
        FileUtils.delete(repositoryName, FileUtils.RECURSIVE | FileUtils.RETRY);
    }
    repo = new RepositoryModel("TicketReferenceTest.git", null, null, null);

    if (gitblit().hasRepository(repo.name)) {
        gitblit().deleteRepositoryModel(repo);
    }

    gitblit().updateRepositoryModel(repo.name, repo, true);

    user = new UserModel(account);
    user.displayName = account;
    user.emailAddress = account + "@example.com";
    user.password = password;

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

    if (gitblit().getUserModel(user.username) != null) {
        gitblit().deleteUser(user.username);
    }

    repo.authorizationControl = AuthorizationControl.NAMED;
    repo.accessRestriction = AccessRestrictionType.PUSH;
    gitblit().updateRepositoryModel(repo.name, repo, false);

    // grant user push permission
    user.setRepositoryPermission(repo.name, AccessPermission.REWIND);
    gitblit().updateUserModel(user);

    ticketService = gitblit().getTicketService();
    assertTrue(ticketService.deleteAll(repo));

    GitBlitSuite.close(workingCopy);
    if (workingCopy.exists()) {
        FileUtils.delete(workingCopy, FileUtils.RECURSIVE | FileUtils.RETRY);
    }

    CloneCommand clone = Git.cloneRepository();
    clone.setURI(MessageFormat.format("{0}/{1}", url, repo.name));
    clone.setDirectory(workingCopy);
    clone.setBare(false);
    clone.setBranch("master");
    clone.setCredentialsProvider(cp);
    GitBlitSuite.close(clone.call());

    git = Git.open(workingCopy);
    git.getRepository().getConfig().setString("user", null, "name", user.displayName);
    git.getRepository().getConfig().setString("user", null, "email", user.emailAddress);
    git.getRepository().getConfig().save();

    final RevCommit revCommit1 = makeCommit("initial commit");
    final String initialSha = revCommit1.name();
    Iterable<PushResult> results = git.push().setPushAll().setCredentialsProvider(cp).call();
    GitBlitSuite.close(git);
    for (PushResult result : results) {
        for (RemoteRefUpdate update : result.getRemoteUpdates()) {
            assertEquals(Status.OK, update.getStatus());
            assertEquals(initialSha, update.getNewObjectId().name());
        }
    }
}

From source file:com.github.kaitoy.goslings.server.dao.jgit.RepositoryResolver.java

License:Open Source License

private String processRemoteRepository(Token token) {
    String tokenString = token.tokenString;
    String uri = token.uri;//from   w  w w.j a v  a  2s. c om
    File repo = new File(REPOS_DIR, tokenString);
    Path lockFilePath = Paths.get(repo.getAbsolutePath() + ".lock");

    Object lock;
    synchronized (LOCKS) {
        lock = LOCKS.get(tokenString);
        if (lock == null) {
            lock = new Object();
            LOCKS.put(tokenString, lock);
        }
    }

    synchronized (lock) {
        try (FileChannel fc = FileChannel.open(lockFilePath, StandardOpenOption.CREATE,
                StandardOpenOption.WRITE); FileLock fileLock = fc.lock()) {
            if (repo.exists()) {
                // Another process or thread has already cloned the repo.
                READY_TOKENS.add(tokenString);
                return tokenString;
            }

            Git git = Git.cloneRepository().setURI(uri).setBare(true).setDirectory(repo).call();
            GITS.put(tokenString, git);
            READY_TOKENS.add(tokenString);
            return tokenString;
        } catch (GitAPIException e) {
            LOG.error("Failed to clone a repo {} due to: ", uri, e);
            throw new DaoException("The server failed to clone the repository. Please confirm the URL: " + uri,
                    e);
        } catch (IOException e) {
            LOG.error("Failed to lock a repo {} due to: ", uri, e);
            throw new DaoException("The server failed to clone the repository due to an I/O error. URI: " + uri,
                    e);
        }
    }
}

From source file:com.github.nk.klusterfuck.admin.services.GogsService.java

License:Apache License

public RepoInfo createRepo(UserNamespace userNamespace, String name, RepoInitializer initer) throws Exception {
    CreateRepositoryRequest cr = new CreateRepositoryRequest();
    cr.setName(name);//w w w.  j  av a2s.c om
    cr.setDescription("...");
    cr.setAutoInit(true);
    cr.setGitIgnores("Eclipse");
    cr.setReadme("Default");
    cr.setLicense("Apache License 2.0");
    cr.setPrivateRepository(true);

    String gogsUrl = "http://gogs." + userNamespace.getName() + "." + domain;
    String gogsUser = userNamespace.getGitUser();
    String gogsPassword = userNamespace.getGitPassword();
    Repository repository = SimpleGogsClient.createRepo(cr, gogsUrl, gogsUser, gogsPassword);
    RepoInfo info = new RepoInfo();
    // clone in temp dir and add fn things and push
    Path fnTmp = null;
    try {
        CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider(gogsUser,
                gogsPassword);
        fnTmp = Files.createTempDirectory("fn_tmp");
        repository.setCloneUrl(gogsUrl + "/" + gogsUser + "/" + name + ".git");
        String cloneUrl = repository.getCloneUrl();
        info.setGitUrl(cloneUrl);
        try (Git cloned = Git.cloneRepository().setURI(cloneUrl).setCredentialsProvider(credentialsProvider)
                .setDirectory(fnTmp.toFile().getCanonicalFile()).call()) {
            if (initer != null) {
                initer.init(fnTmp.toFile());
            }
            cloned.add().addFilepattern(".").call();

            RevCommit revCommit = cloned.commit().setMessage("setup function files...").call();
            info.setCommitId(revCommit.name());

            cloned.push().setCredentialsProvider(credentialsProvider).call();
        }
        return info;
    } catch (Exception e) {
        // delete gogs repo
        deleteRepo(userNamespace, name);
        throw new RepoCreationException("Could not create repo", e);
    } finally {
        if (fnTmp != null) {
            try {
                FileUtils.deleteDirectory(fnTmp.toFile());
            } catch (IOException e) {
                throw new RepoCreationException("Could not create repo", e);
            }
        }
    }
}