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

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

Introduction

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

Prototype

public static Git open(File dir) throws IOException 

Source Link

Document

Open repository

Usage

From source file:com.binarybirchtree.contributionart.RepositoryTest.java

License:Open Source License

@Test
public void validate_commits()
        throws IOException, Matrix.FileFormatException, Repository.GitException, GitAPIException {
    final int factor = 20;
    final String name = "name";
    final String email = "email";

    ////* w  w w.ja v  a  2  s.  c o m*/
    /// Encapsulates commit-validation logic.
    ///
    class CommitValidator {
        final ZonedDateTime timestamp;

        ///
        /// @param[in] commit Commit to validate.
        /// @param[in] timestamp Expected timestamp.
        /// @param[in] message Expected message.
        ///
        CommitValidator(RevCommit commit, ZonedDateTime timestamp, String message) {
            this.timestamp = timestamp;

            Assert.assertEquals(timestamp.toInstant(), Instant.ofEpochSecond(commit.getCommitTime()));
            Assert.assertEquals(message, commit.getFullMessage());

            new IdentityValidator(commit.getAuthorIdent());
            new IdentityValidator(commit.getCommitterIdent());
        }

        ///
        /// Contains shared validation logic used for both Author and Committer identities.
        ///
        class IdentityValidator {
            private PersonIdent identity;

            ///
            /// @param[in] identity Identity to validate.
            ///
            public IdentityValidator(PersonIdent identity) {
                this.identity = identity;

                validate_name();
                validate_email();
                validate_timestamp();
            }

            private void validate_name() {
                Assert.assertEquals(name, identity.getName());
            }

            private void validate_email() {
                Assert.assertEquals(email, identity.getEmailAddress());
            }

            private void validate_timestamp() {
                Assert.assertEquals(timestamp.toInstant(), identity.getWhen().toInstant());
            }
        }
    }

    Path repo = folder.newFolder().toPath();
    Matrix matrix = new Matrix(file);
    ZonedDateTime today = ZonedDateTime.now(ZoneOffset.UTC).truncatedTo(ChronoUnit.DAYS);

    // Generate commits in a temporary repository.
    try (Repository repository = new Repository(repo, name, email)) {
        repository.illustrate(matrix, factor);
    }

    // Verify that the state of the repository is as expected.
    try (Git git = Git.open(repo.toFile())) {
        // Start from the earliest date for which commits were generated.
        ZonedDateTime current = today.with(WeekFields.SUNDAY_START.dayOfWeek(), DayOfWeek.values().length)
                .minusDays(Matrix.AREA);

        // Prepare to iterate through the definition matrix alongside the commit log,
        // as the values in the definition matrix affect how many commits should have been generated.
        Iterator<Matrix.Value> values = matrix.iterator();
        Matrix.Value value;
        int cell_iterations = 0;
        int commit_count = 0;

        // Retrieve the list of commits, sorted from earliest to latest.
        List<RevCommit> commits = Lists.reverse(Lists.newArrayList(git.log().call()));
        Assert.assertFalse(commits.isEmpty());

        // Validate the README commit.
        String readme = "README.md";
        new CommitValidator(Iterables.getLast(commits), today, String.format("Added %s.", readme));
        commits.remove(commits.size() - 1);
        Assert.assertEquals(Repository.README, new String(Files.readAllBytes(repo.resolve(readme))));

        // Iterate through the commit log, starting from the earliest commit.
        for (RevCommit commit : commits) {
            if (cell_iterations == 0) {
                Assert.assertTrue(values.hasNext());
                value = values.next();
                cell_iterations = value.weight() * factor;
                current = current.plusDays(1);
            }

            new CommitValidator(commit, current, "");

            ++commit_count;
            --cell_iterations;
        }

        // Determine the expected commit count and compare it with the actual commit count.
        int expected_commit_count = StreamSupport.stream(matrix.spliterator(), false).map(Matrix.Value::weight)
                .reduce(0, (accumulator, element) -> accumulator + element * factor);

        while (values.hasNext()) {
            expected_commit_count -= values.next().weight() * factor;
        }

        Assert.assertEquals(expected_commit_count, commit_count);
    }
}

From source file:com.chungkwong.jgitgui.Main.java

License:Open Source License

private void gitOpen() {
    try {/*www .j av  a 2s .c  o m*/
        File dir = dirChooser.showDialog(null);
        if (dir != null)
            navigationRoot.getChildren().add(new GitTreeItem(Git.open(dir)));
    } catch (Exception ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        Util.informUser(ex);
    }
}

From source file:com.dell.doradus.core.DoradusServer.java

License:Apache License

/**
 * Get Doradus Version from git repo if it exists; otherwise get it from the local doradus.ver file
 * @return version// www.  j a  va 2 s .c  o m
 */
public static String getDoradusVersion() {
    String version = null;
    try {
        //first read from the local git repository
        Git git = Git.open(new File("../.git"));
        String url = git.getRepository().getConfig().getString("remote", "origin", "url");
        instance().m_logger.info("Remote.origin.url: {}", url);
        if (!Utils.isEmpty(url) && url.contains("dell-oss/Doradus.git")) {
            DescribeCommand cmd = git.describe();
            version = cmd.call();
            instance().m_logger.info("Doradus version found from git repo: {}", version);
            writeVersionToVerFile(version);
        }
    } catch (Throwable e) {
        instance().m_logger.info("failed to read version from git repo");
    }
    //if not found, reading from local file
    if (Utils.isEmpty(version)) {
        try {
            version = getVersionFromVerFile();
            instance().m_logger.info("Doradus version found from doradus.ver file {}", version);
        } catch (IOException e1) {
            version = null;
        }
    }
    return version;
}

From source file:com.ericsson.eiffel.remrem.semantics.clone.PrepareLocalEiffelSchemas.java

License:Apache License

/**
 * This method is used to clone repository from github using the URL and branch to local destination folder.
 * /* www  . jav a  2 s. c o m*/
 * @param repoURL
 *            repository url to clone.
 * @param branch
 *            specific branch name of the repository to clone
 * @param localEiffelRepoPath
 *            destination path to clone the repo.
 */
private void cloneEiffelRepo(final String repoURL, final String branch, final File localEiffelRepoPath) {
    Git localGitRepo = null;

    // checking for repository exists or not in the localEiffelRepoPath
    try {
        if (!localEiffelRepoPath.exists()) {
            // cloning github repository by using URL and branch name into local
            localGitRepo = Git.cloneRepository().setURI(repoURL).setBranch("master")
                    .setDirectory(localEiffelRepoPath).call();
        } else {
            // If required repository already exists
            localGitRepo = Git.open(localEiffelRepoPath);

            // Reset to normal if uncommitted changes are present
            localGitRepo.reset().call();

            //Checkout to master before pull the changes
            localGitRepo.checkout().setName(EiffelConstants.MASTER).call();

            // To get the latest changes from remote repository.
            localGitRepo.pull().call();
        }

        //checkout to input branch after changes pulled into local
        localGitRepo.checkout().setName(branch).call();

    } catch (Exception e) {
        LOGGER.info(
                "please check proxy settings if proxy enabled update proxy.properties file to clone behind proxy");
        e.printStackTrace();
    }
}

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

License:Apache License

@Test
public void testAnonymousPush() throws Exception {
    GitBlitSuite.close(ticgitFolder);/*  ww  w .  j a v  a 2s .co 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 www  .  j a v a 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);
    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);/*  www.j  av a  2 s. com*/
    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 ww.ja  v 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  .ja va 2s.  c o m

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

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

License:Apache License

private void testMergeCommitterVerification(boolean expectedSuccess) throws Exception {
    UserModel user = getUser();/*from   ww w . j av a  2  s  . co m*/

    delete(user);

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

    // checkout a mergetest branch
    git.checkout().setCreateBranch(true).setName("mergetest").call();

    // change identity
    git.getRepository().getConfig().setString("user", null, "name", "mergetest");
    git.getRepository().getConfig().setString("user", null, "email", "mergetest@merge.com");
    git.getRepository().getConfig().save();

    // commit a file
    File file = new File(local, "MERGECHK2");
    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();
    RevCommit mergeTip = git.commit().setMessage(file.getName() + " test").call();

    // return to master
    git.checkout().setName("master").call();

    // restore identity
    if (expectedSuccess) {
        git.getRepository().getConfig().setString("user", null, "name", user.username);
        git.getRepository().getConfig().setString("user", null, "email", user.emailAddress);
        git.getRepository().getConfig().save();
    }

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

    // merge the tip of the mergetest branch into master with --no-ff
    MergeResult mergeResult = git.merge().setFastForward(FastForwardMode.NO_FF).include(mergeTip.getId())
            .call();
    assertEquals(MergeResult.MergeStatus.MERGED, mergeResult.getMergeStatus());

    // push the merged master to the origin
    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);
}