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:io.hawkcd.materials.materialservices.GitService.java

License:Apache License

@Override
public boolean repositoryExists(GitMaterial gitMaterial) {
    try {/*from  w  ww .  j a  v a 2 s.  c o m*/
        Repository repository = Git.open(new File(gitMaterial.getDestination())).getRepository();
        org.eclipse.jgit.lib.Config config = repository.getConfig();
        String repositoryUrl = config.getString("remote", "origin", "url");
        if (!repositoryUrl.equals(gitMaterial.getRepositoryUrl())) {
            return false;
        }
    } catch (IOException e) {
        return false;
    }

    return true;
}

From source file:io.hawkcd.materials.materialservices.GitService.java

License:Apache License

@Override
public GitMaterial fetchLatestCommit(GitMaterial gitMaterial) {
    try {/*  w  ww.j a  va2s .  c o m*/
        Git git = Git.open(new File(gitMaterial.getDestination() + File.separator + ".git"));
        CredentialsProvider credentials = this.handleCredentials(gitMaterial);
        git.fetch().setCredentialsProvider(credentials).setCheckFetchedObjects(true)
                .setRefSpecs(new RefSpec(
                        "refs/heads/" + gitMaterial.getBranch() + ":refs/heads/" + gitMaterial.getBranch()))
                .call();
        ObjectId objectId = git.getRepository().getRef(gitMaterial.getBranch()).getObjectId();
        RevWalk revWalk = new RevWalk(git.getRepository());
        RevCommit commit = revWalk.parseCommit(objectId);

        gitMaterial.setCommitId(commit.getId().getName());
        gitMaterial.setAuthorName(commit.getAuthorIdent().getName());
        gitMaterial.setAuthorEmail(commit.getAuthorIdent().getEmailAddress());
        gitMaterial.setComments(commit.getFullMessage());
        gitMaterial.setErrorMessage("");
        git.close();

        return gitMaterial;
    } catch (IOException | GitAPIException e) {
        gitMaterial.setErrorMessage(e.getMessage());
        return gitMaterial;
    }
}

From source file:io.liveoak.git.HTTPGitResourceTest.java

License:Open Source License

@Test
public void rootResource() throws Exception {
    // Test #1 -  Git Repo present after install
    File appDir = new File(testApplication.directory().getParentFile(), "newApp");
    File appGitDir = new File(appDir, ".git");

    // Verify app and git dir do not exist
    assertThat(appDir.exists()).isFalse();
    assertThat(appGitDir.exists()).isFalse();

    // Create new app
    assertThat(execPost(ADMIN_ROOT, "{ \"id\": \"newApp\" }")).hasStatus(201);
    awaitStability();//ww w.  ja  va  2  s  .c o  m

    // Verify app and git dirs exist
    assertThat(appDir.exists()).isTrue();
    assertThat(appGitDir.exists()).isTrue();
    assertThat(new File(appGitDir, ".git").exists()).isFalse();

    // Verify REST endpoints
    assertThat(execGet(GIT_ADMIN_ROOT)).hasStatus(200);
    assertThat(execGet(GIT_PUBLIC_ROOT)).hasStatus(404).hasNoSuchResource();

    // Test #2 - Post a commit, with auto add files to index
    // Create a file in the application directory
    File testFile = new File(appDir, "test.txt");
    assertThat(testFile.createNewFile()).isTrue();
    Files.write(testFile.toPath(), "content".getBytes());

    Git gitRepo = Git.open(appDir);

    // Execute a commit
    assertThat(
            execPost("/admin/applications/newApp/resources/git/commits", "{ \"msg\": \"my commit message\" }"))
                    .hasStatus(201);

    assertThat(gitRepo.status().call().hasUncommittedChanges()).isFalse();
    Iterator<RevCommit> iterator = gitRepo.log().all().call().iterator();
    int commitSize = 0;
    RevCommit latestCommit = null;
    while (iterator.hasNext()) {
        RevCommit commit = iterator.next();
        if (commitSize == 0) {
            latestCommit = commit;
        }
        commitSize++;
    }

    assertThat(commitSize).isEqualTo(2);
    assertThat(latestCommit.getFullMessage()).isEqualTo("my commit message");

    TreeWalk treeWalk = new TreeWalk(gitRepo.getRepository());
    treeWalk.addTree(latestCommit.getTree());
    treeWalk.setFilter(PathFilter.create("test.txt"));
    assertThat(treeWalk.next()).isTrue();
    String fileContent = new String(treeWalk.getObjectReader().open(treeWalk.getObjectId(0)).getBytes());
    treeWalk.release();
    assertThat(fileContent).isEqualTo("content");

    // Test #3 - Post a commit, with auto add files to index off
    File anotherFile = new File(appDir, "another.txt");
    assertThat(anotherFile.createNewFile()).isTrue();
    Files.write(anotherFile.toPath(), "another content".getBytes());
    Files.write(testFile.toPath(), "updated content".getBytes());

    // Execute a commit
    assertThat(execPost("/admin/applications/newApp/resources/git/commits",
            "{ \"msg\": \"another commit\", \"include-untracked\": \"false\" }")).hasStatus(201);

    assertThat(gitRepo.status().call().isClean()).isFalse();
    iterator = gitRepo.log().all().call().iterator();
    commitSize = 0;
    while (iterator.hasNext()) {
        RevCommit commit = iterator.next();
        if (commitSize == 0) {
            latestCommit = commit;
        }
        commitSize++;
    }

    assertThat(commitSize).isEqualTo(3);
    assertThat(latestCommit.getFullMessage()).isEqualTo("another commit");

    treeWalk = new TreeWalk(gitRepo.getRepository());
    treeWalk.addTree(latestCommit.getTree());
    treeWalk.setFilter(PathFilter.create("another.txt"));
    assertThat(treeWalk.next()).isFalse();
    treeWalk.release();

    treeWalk = new TreeWalk(gitRepo.getRepository());
    treeWalk.addTree(latestCommit.getTree());
    treeWalk.setFilter(PathFilter.create("test.txt"));
    assertThat(treeWalk.next()).isTrue();

    fileContent = new String(treeWalk.getObjectReader().open(treeWalk.getObjectId(0)).getBytes());
    treeWalk.release();
    assertThat(fileContent).isEqualTo("updated content");

    // Test #4 - Verify PUT on commit is not supported
    assertThat(execPut("/admin/applications/newApp/resources/git/commits/" + latestCommit.getName(),
            "{ \"bad\": \"request\" }")).hasStatus(500).isInternalError();
}

From source file:io.verticle.apex.commons.oss.repository.GitRepositoryService.java

License:Apache License

private Git openGitRepository() throws IOException {
    Git git = Git.open(localRepositoryPath.toFile());
    return git;
}

From source file:io.vertx.config.git.GitConfigStore.java

License:Apache License

private Git initializeGit() throws IOException, GitAPIException {
    if (path.isDirectory()) {
        Git git = Git.open(path);
        String current = git.getRepository().getBranch();
        if (branch.equalsIgnoreCase(current)) {
            PullResult pull = git.pull().setRemote(remote).setCredentialsProvider(credentialProvider)
                    .setTransportConfigCallback(transportConfigCallback).call();
            if (!pull.isSuccessful()) {
                LOGGER.warn("Unable to pull the branch + '" + branch + "' from the remote repository '" + remote
                        + "'");
            }/*from w ww.j  a  va  2 s . co  m*/
            return git;
        } else {
            git.checkout().setName(branch).setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
                    .setStartPoint(remote + "/" + branch).call();
            return git;
        }
    } else {
        return Git.cloneRepository().setURI(url).setBranch(branch).setRemote(remote).setDirectory(path)
                .setCredentialsProvider(credentialProvider).setTransportConfigCallback(transportConfigCallback)
                .call();
    }
}

From source file:net.morimekta.idltool.IdlToolTest.java

License:Apache License

@Test
public void testListNoRepository() throws GitAPIException, URISyntaxException, IOException {
    Git.init().setDirectory(tmp.getRoot()).call();
    Git git = Git.open(tmp.getRoot());
    RemoteAddCommand remoteAddCommand = git.remoteAdd();
    remoteAddCommand.setName("origin");
    remoteAddCommand.setUri(new URIish("git@github.com/morimekta/idltool.git"));
    remoteAddCommand.call();//from w w w  . ja  va 2 s .c o m

    idl.execute("list");

    assertThat(exitCode, is(1));
    assertThat(console.output(), is(""));
    assertThat(console.error(),
            is("I/O Error: No .idlrc file at: " + tmp.getRoot().toString() + " (recursive)\n"));
}

From source file:net.morimekta.idltool.IdlUtils.java

License:Apache License

public static Git getCacheRepository(File cacheDir, String repository) throws IOException, GitAPIException {
    File repoCache = getCacheDirectory(cacheDir, repository);

    Runtime runtime = Runtime.getRuntime();
    if (!repoCache.exists()) {
        Process p = runtime//from  www. j  av a2 s.  c o m
                .exec(new String[] { "git", "clone", repository, repoCache.getAbsoluteFile().toString() });
        try {
            int response = p.waitFor();
            if (response != 0) {
                throw new IOException(IOUtils.readString(p.getErrorStream()));
            }
        } catch (InterruptedException e) {
            throw new IOException(e.getMessage(), e);
        }
    } else {
        Process p = runtime.exec(new String[] { "git", "fetch", "origin", "-p" }, null, repoCache);
        try {
            int response = p.waitFor();
            if (response != 0) {
                throw new IOException(IOUtils.readString(p.getErrorStream()));
            }
        } catch (InterruptedException e) {
            throw new IOException(e.getMessage(), e);
        }

        p = runtime.exec(new String[] { "git", "add", "-A" }, null, repoCache);
        try {
            int response = p.waitFor();
            if (response != 0) {
                throw new IOException(IOUtils.readString(p.getErrorStream()));
            }
        } catch (InterruptedException e) {
            throw new IOException(e.getMessage(), e);
        }

        p = runtime.exec(new String[] { "git", "reset", "origin/master", "--hard" }, null, repoCache);
        try {
            int response = p.waitFor();
            if (response != 0) {
                throw new IOException(IOUtils.readString(p.getErrorStream()));
            }
        } catch (InterruptedException e) {
            throw new IOException(e.getMessage(), e);
        }
    }
    return Git.open(repoCache);
}

From source file:net.openbyte.gui.GitCommitFrame.java

License:MIT License

private void button2ActionPerformed(ActionEvent e) {
    if (textField1.getText().equals("")) {
        JOptionPane.showMessageDialog(this, "Invalid commit message.", "Error", JOptionPane.ERROR_MESSAGE);
        return;//w  w w .  j  av  a  2  s  . co m
    }
    try {
        Git.open(this.workDirectory).add().addFilepattern(".").call();
        Git.open(this.workDirectory).commit().setMessage(textField1.getText()).call();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:net.riezebos.thoth.content.impl.GitContentManager.java

License:Apache License

protected Git getRepository() throws ContextNotFoundException, IOException {
    String contextFolder = getContextFolder();
    File target = new File(contextFolder);
    return Git.open(target);
}

From source file:net.yacy.grid.tools.GitTool.java

License:Open Source License

public GitTool() {
    File gitWorkDir = new File(".");
    try {//  w  w w.j  a va  2  s .  c  o m
        Git git = Git.open(gitWorkDir);
        Iterable<RevCommit> commits = git.log().all().call();
        Repository repo = git.getRepository();
        branch = repo.getBranch();
        RevCommit latestCommit = commits.iterator().next();
        name = latestCommit.getName();
        message = latestCommit.getFullMessage();
    } catch (Throwable e) {
        name = "";
        message = "";
        branch = "";
    }
}