Example usage for org.eclipse.jgit.lib Repository close

List of usage examples for org.eclipse.jgit.lib Repository close

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Repository close.

Prototype

@Override
public void close() 

Source Link

Document

Decrement the use count, and maybe close resources.

Usage

From source file:playRepository.GitRepository.java

License:Apache License

public static boolean canDeleteFromBranch(PullRequest pullRequest) {
    List<Ref> refs;//from  www  . j  av  a  2s . c  o  m
    Repository fromRepo = null; // repository that sent the pull request
    String currentBranch;
    try {
        fromRepo = buildGitRepository(pullRequest.fromProject);
        currentBranch = fromRepo.getFullBranch();
        refs = new Git(fromRepo).branchList().call();

        for (Ref branchRef : refs) {
            String branchName = branchRef.getName();
            if (branchName.equals(pullRequest.fromBranch) && !branchName.equals(currentBranch)) {
                RevWalk revWalk = new RevWalk(fromRepo);
                RevCommit commit = revWalk.parseCommit(fromRepo.resolve(branchName));
                String commitName = commit.name(); // fromBranch's head commit name
                revWalk.release();

                // check whether the target repository has the commit witch is the fromBranch's head commit.
                Repository toRepo = buildGitRepository(pullRequest.toProject);
                ObjectId toBranch = toRepo.resolve(commitName);
                if (toBranch != null) {
                    return true;
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (fromRepo != null) {
            fromRepo.close();
        }
    }

    return false;
}

From source file:playRepository.GitRepository.java

License:Apache License

public static String deleteFromBranch(PullRequest pullRequest) {
    if (!canDeleteFromBranch(pullRequest)) {
        return null;
    }//from   w w  w.j a v  a 2s .  c  o m

    RevWalk revWalk = null;
    String lastCommitId;
    Repository repo = null;
    try {
        repo = buildGitRepository(pullRequest.fromProject);
        ObjectId branch = repo.resolve(pullRequest.fromBranch);
        revWalk = new RevWalk(repo);
        RevCommit commit = revWalk.parseCommit(branch);
        lastCommitId = commit.getName();
        deleteBranch(repo, pullRequest.fromBranch);
        return lastCommitId;
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (revWalk != null) {
            revWalk.release();
        }
        if (repo != null) {
            repo.close();
        }
    }
}

From source file:playRepository.GitRepository.java

License:Apache License

public static void restoreBranch(PullRequest pullRequest) {
    if (!canRestoreBranch(pullRequest)) {
        return;//www  .j a  va 2 s  . co m
    }

    Repository repo = null;
    try {
        repo = buildGitRepository(pullRequest.fromProject);
        new Git(repo).branchCreate().setName(pullRequest.fromBranch.replaceAll("refs/heads/", ""))
                .setStartPoint(pullRequest.lastCommitId).call();
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (repo != null) {
            repo.close();
        }
    }
}

From source file:playRepository.GitRepository.java

License:Apache License

public static boolean canRestoreBranch(PullRequest pullRequest) {
    Repository repo = null;
    try {/*from  ww  w  .  j  av  a2  s.c  om*/
        repo = buildGitRepository(pullRequest.fromProject);
        ObjectId resolve = repo.resolve(pullRequest.fromBranch);
        if (resolve == null && pullRequest.lastCommitId != null) {
            return true;
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (repo != null) {
            repo.close();
        }
    }

    return false;
}

From source file:playRepository.GitRepositoryTest.java

License:Apache License

@Test
public void getMetaDataFromPath() throws Exception {
    // Given//from  w ww  .  j a  va2 s .co  m
    final String userName = "yobi";
    final String projectName = "mytest";
    final String branchName = "branch";
    final String lightWeightTagName = "tag1";
    final String annotatedTagName = "tag2";
    String wcPath = GitRepository.getRepoPrefix() + userName + "/" + projectName;

    Repository repository = GitRepository.buildGitRepository(userName, projectName + "/");
    repository.create();
    Git git = new Git(repository);
    FileUtils.touch(new File(wcPath + "/hello"));
    FileUtils.touch(new File(wcPath + "/dir/world"));
    git.add().addFilepattern("hello").call();
    git.add().addFilepattern("dir").call();
    git.commit().setAuthor("yobi", "yobi@yobi.io").setMessage("test").call();
    git.branchCreate().setName(branchName).call();
    git.tag().setName(lightWeightTagName).setAnnotated(false).call();
    git.tag().setName(annotatedTagName).setAnnotated(true).setMessage("annotated tag").call();
    repository.close();

    running(support.Helpers.makeTestApplication(), new Runnable() {
        @Override
        public void run() {
            try {
                // When
                GitRepository gitRepository = new GitRepository(userName, projectName + "/");
                ObjectNode notExistBranch = gitRepository.getMetaDataFromPath("not_exist_branch", "");
                ObjectNode root = gitRepository.getMetaDataFromPath("");
                ObjectNode dir = gitRepository.getMetaDataFromPath("dir");
                ObjectNode file = gitRepository.getMetaDataFromPath("hello");
                ObjectNode branch = gitRepository.getMetaDataFromPath(branchName, "");
                ObjectNode lightWeightTag = gitRepository.getMetaDataFromPath(lightWeightTagName, "");
                ObjectNode annotatedTag = gitRepository.getMetaDataFromPath(annotatedTagName, "");

                // Then
                assertThat(notExistBranch).isNull();
                assertThat(root.get("type").textValue()).isEqualTo("folder");
                assertThat(root.get("data").get("hello").get("type").textValue()).isEqualTo("file");
                assertThat(root.get("data").get("dir").get("type").textValue()).isEqualTo("folder");
                assertThat(dir.get("type").textValue()).isEqualTo("folder");
                assertThat(dir.get("data").get("world").get("type").textValue()).isEqualTo("file");
                assertThat(file.get("type").textValue()).isEqualTo("file");
                assertThat(branch.toString()).isEqualTo(root.toString());
                assertThat(lightWeightTag.toString()).isEqualTo(root.toString());
                assertThat(annotatedTag.toString()).isEqualTo(root.toString());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    });
}

From source file:playRepository.GitRepositoryTest.java

License:Apache License

@Test
public void isFile() throws Exception {
    // Given//  w  w  w .  j a  v a 2 s .  co m
    String userName = "yobi";
    String projectName = "mytest";
    String wcPath = GitRepository.getRepoPrefix() + userName + "/" + projectName;
    String repoPath = wcPath + "/.git";
    String dirName = "dir";
    String fileName = "file";

    Repository repository = new RepositoryBuilder().setGitDir(new File(repoPath)).build();
    repository.create(false);
    Git git = new Git(repository);
    FileUtils.forceMkdir(new File(wcPath + "/" + dirName));
    FileUtils.touch(new File(wcPath + "/" + fileName));
    git.add().addFilepattern(dirName).call();
    git.add().addFilepattern(fileName).call();
    git.commit().setMessage("test").call();
    repository.close();

    // When
    GitRepository gitRepository = new GitRepository(userName, projectName + "/");

    // Then
    assertThat(gitRepository.isFile(dirName)).isEqualTo(false);
    assertThat(gitRepository.isFile(fileName)).isEqualTo(true);
    assertThat(gitRepository.isFile("not_exist_file")).isEqualTo(false);
    assertThat(gitRepository.isFile(fileName, "not_exist_branch")).isEqualTo(false);
}

From source file:playRepository.GitRepositoryTest.java

License:Apache License

@Test
public void testGetAllBranches() throws IOException, GitAPIException {
    FakeApplication app = support.Helpers.makeTestApplication();
    Helpers.start(app);//from w w w.j a va2  s  .c o  m

    // Given
    String userName = "wansoon";
    String projectName = "test";
    Project project = createProject(userName, projectName);
    project.save();

    String email = "test@email.com";
    String wcPath = GitRepository.getRepoPrefix() + userName + "/" + "clone-" + projectName + ".git";
    String repoPath = wcPath + "/.git";
    String dirName = "dir";
    String fileName = "file";

    GitRepository gitRepository = new GitRepository(userName, projectName);
    gitRepository.create();

    Repository repository = new RepositoryBuilder().setGitDir(new File(repoPath)).build();
    repository.create(false);

    Git git = new Git(repository);
    FileUtils.forceMkdir(new File(wcPath + "/" + dirName));
    FileUtils.touch(new File(wcPath + "/" + fileName));
    git.add().addFilepattern(dirName).call();
    git.add().addFilepattern(fileName).call();
    git.commit().setMessage("test").setAuthor(userName, email).call();

    String branchName = "testBranch";
    git.branchCreate().setName(branchName).setForce(true).call();

    git.push().setRemote(GitRepository.getGitDirectoryURL(project))
            .setRefSpecs(new RefSpec(branchName + ":" + branchName)).setForce(true).call();

    repository.close();

    // When
    List<GitBranch> gitBranches = gitRepository.getBranches();
    gitRepository.close();

    // Then
    assertThat(gitBranches.size()).isEqualTo(1);
    assertThat(gitBranches.get(0).getShortName()).isEqualTo(branchName);

    Helpers.stop(app);
}

From source file:playRepository.GitRepositoryTest.java

License:Apache License

@Test
public void getRelatedAuthors() throws IOException, GitAPIException, LimitExceededException {
    FakeApplication app = support.Helpers.makeTestApplication();
    Helpers.start(app);/* w w  w. j av  a2  s  . co  m*/

    Repository repository = support.Git.createRepository("yobi", "test", true);

    // Given
    User yobi = User.findByLoginId("yobi");
    User laziel = User.findByLoginId("laziel");
    User doortts = User.findByLoginId("doortts");
    User nori = User.findByLoginId("nori");

    Git git = new Git(repository);
    RevCommit from = addCommit(git, "README.md", "hello", "1st commit", yobi);
    addCommit(git, "test.txt", "text file", "2nd commit", laziel);
    addCommit(git, "test.txt", "edited text file", "3rd commit", doortts);
    RevCommit to = addCommit(git, "README.md", "hello, world!", "4th commit", nori);

    // When
    Set<User> authors = GitRepository.getRelatedAuthors(repository, from.getName(), to.getName());

    // Then
    assertThat(authors).containsOnly(yobi);

    repository.close();
    Helpers.stop(app);
}

From source file:sh.isaac.provider.sync.git.SyncServiceGIT.java

License:Apache License

/**
 * Link and fetch from remote./* w ww.  j  a v  a 2  s . co m*/
 *
 * @param remoteAddress the remote address
 * @param username the username
 * @param password the password
 * @throws IllegalArgumentException the illegal argument exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws AuthenticationException the authentication exception
 * @see sh.isaac.api.sync.SyncFiles#linkAndFetchFromRemote(java.io.File, java.lang.String, java.lang.String, java.lang.String)
 */
@Override
public void linkAndFetchFromRemote(String remoteAddress, String username, char[] password)
        throws IllegalArgumentException, IOException, AuthenticationException {
    LOG.info("linkAndFetchFromRemote called - folder: {}, remoteAddress: {}, username: {}", this.localFolder,
            remoteAddress, username);

    Repository r = null;
    Git git = null;

    try {
        final File gitFolder = new File(this.localFolder, ".git");

        r = new FileRepository(gitFolder);

        if (!gitFolder.isDirectory()) {
            LOG.debug("Root folder does not contain a .git subfolder.  Creating new git repository.");
            r.create();
        }

        relinkRemote(remoteAddress, username, password);
        git = new Git(r);

        final CredentialsProvider cp = new UsernamePasswordCredentialsProvider(username,
                ((password == null) ? new char[] {} : password));

        LOG.debug("Fetching");

        final FetchResult fr = git.fetch().setCheckFetchedObjects(true).setCredentialsProvider(cp).call();

        LOG.debug("Fetch messages: {}", fr.getMessages());

        boolean remoteHasMaster = false;
        final Collection<Ref> refs = git.lsRemote().setCredentialsProvider(cp).call();

        for (final Ref ref : refs) {
            if ("refs/heads/master".equals(ref.getName())) {
                remoteHasMaster = true;
                LOG.debug("Remote already has 'heads/master'");
                break;
            }
        }

        if (remoteHasMaster) {
            // we need to fetch and (maybe) merge - get onto origin/master.
            LOG.debug("Fetching from remote");

            final String fetchResult = git.fetch().setCredentialsProvider(cp).call().getMessages();

            LOG.debug("Fetch Result: {}", fetchResult);
            LOG.debug("Resetting to origin/master");
            git.reset().setMode(ResetType.MIXED).setRef("origin/master").call();

            // Get the files from master that we didn't have in our working folder
            LOG.debug("Checking out missing files from origin/master");

            for (final String missing : git.status().call().getMissing()) {
                LOG.debug("Checkout {}", missing);
                git.checkout().addPath(missing).call();
            }

            for (final String newFile : makeInitialFilesAsNecessary(this.localFolder)) {
                LOG.debug("Adding and committing {}", newFile);
                git.add().addFilepattern(newFile).call();
                git.commit().setMessage("Adding " + newFile).setAuthor(username, "42").call();

                for (final PushResult pr : git.push().setCredentialsProvider(cp).call()) {
                    LOG.debug("Push Message: {}", pr.getMessages());
                }
            }
        } else {
            // just push
            // make sure we have something to push
            for (final String newFile : makeInitialFilesAsNecessary(this.localFolder)) {
                LOG.debug("Adding and committing {}", newFile);
                git.add().addFilepattern(newFile).call();
            }

            git.commit().setMessage("Adding initial files").setAuthor(username, "42").call();
            LOG.debug("Pushing repository");

            for (final PushResult pr : git.push().setCredentialsProvider(cp).call()) {
                LOG.debug("Push Result: {}", pr.getMessages());
            }
        }

        LOG.info("linkAndFetchFromRemote Complete.  Current status: " + statusToString(git.status().call()));
    } catch (final TransportException te) {
        if (te.getMessage().contains("Auth fail") || te.getMessage().contains("not authorized")) {
            LOG.info("Auth fail", te);
            throw new AuthenticationException("Auth fail");
        } else {
            LOG.error("Unexpected", te);
            throw new IOException("Internal error", te);
        }
    } catch (final GitAPIException e) {
        LOG.error("Unexpected", e);
        throw new IOException("Internal error", e);
    } finally {
        if (git != null) {
            git.close();
        }

        if (r != null) {
            r.close();
        }
    }
}

From source file:uk.ac.cam.cl.dtg.segue.database.GitDb.java

License:Apache License

/**
 * getFileByCommitSHA//from   w  ww .  j a  v a 2s . c o m
 * 
 * This method will access the git repository given a particular SHA and will attempt to locate a unique file and
 * return a bytearrayoutputstream of the files contents.
 * 
 * @param sha
 *            to search in.
 * @param fullFilePath
 *            file path to search for e.g. /src/filename.json
 * @return the ByteArrayOutputStream - which you can extract the file contents via the toString method.
 * @throws IOException
 *             - if we cannot access the repo location.
 * @throws UnsupportedOperationException
 *             - This method is intended to only locate one file at a time. If your search matches multiple files
 *             then this exception will be thrown.
 */
public ByteArrayOutputStream getFileByCommitSHA(final String sha, final String fullFilePath)
        throws IOException, UnsupportedOperationException {
    if (null == sha || null == fullFilePath) {
        return null;
    }

    ObjectId objectId = this.findGitObject(sha, fullFilePath);

    if (null == objectId) {
        return null;
    }

    Repository repository = gitHandle.getRepository();
    ObjectLoader loader = repository.open(objectId);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    loader.copyTo(out);

    repository.close();
    return out;
}