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

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

Introduction

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

Prototype

public Git(Repository repo) 

Source Link

Document

Construct a new org.eclipse.jgit.api.Git object which can interact with the specified git repository.

Usage

From source file:com.surevine.gateway.scm.git.jgit.JGitGitFacadeTest.java

License:Open Source License

@Test
public void testBundleMultipleBranches() throws Exception {
    LocalRepoBean repoWithBranches = TestUtility.createTestRepoMultipleBranches();
    Path bundlePath = underTest.bundle(repoWithBranches);
    assertTrue(Files.exists(bundlePath));
    assertTrue(Files.isRegularFile(bundlePath));

    LocalRepoBean fromBundle = new LocalRepoBean();
    fromBundle.setCloneSourceURI(bundlePath.toString());
    fromBundle.setProjectKey(repoWithBranches.getProjectKey());
    fromBundle.setSlug(repoWithBranches.getSlug() + "_from_bundle");
    fromBundle.setLocalBare(true);/*from  ww w .j  av a  2 s . c o m*/

    underTest.clone(fromBundle);

    FileRepositoryBuilder builder = new FileRepositoryBuilder();

    Repository originalRepo = builder.setGitDir(repoWithBranches.getGitConfigDirectory().toFile()).findGitDir()
            .build();
    Git original = new Git(originalRepo);
    List<Ref> originalBranches = original.branchList().call();

    Repository fromBundleRepo = builder.setGitDir(fromBundle.getGitConfigDirectory().toFile()).findGitDir()
            .build();
    Git fromBundleGit = new Git(fromBundleRepo);
    List<Ref> fromBundleBraches = fromBundleGit.branchList().call();

    int matches = 0;
    for (Ref branchRef : originalBranches) {
        for (Ref fromBundleRef : fromBundleBraches) {
            if (branchRef.getName().equals(fromBundleRef.getName())) {
                matches++;
                continue;
            }
        }
    }

    assertEquals(matches, originalBranches.size());

    TestUtility.destroyTestRepo(fromBundle);
    TestUtility.destroyTestRepo(repoWithBranches);
    Files.deleteIfExists(bundlePath);
}

From source file:com.surevine.gateway.scm.git.jgit.JGitGitFacadeTest.java

License:Open Source License

@Test
public void testFetch() throws Exception {
    LocalRepoBean sourceRepoBean = TestUtility.createTestRepo();
    String sourceDirectory = sourceRepoBean.getRepoDirectory().toString();

    LocalRepoBean targetRepoBean = new LocalRepoBean();
    targetRepoBean.setLocalBare(false);/*from   w  w w  .j a va2s .  c  om*/
    targetRepoBean.setProjectKey(sourceRepoBean.getProjectKey());
    targetRepoBean.setSlug(sourceRepoBean.getSlug() + "_clone");
    targetRepoBean.setCloneSourceURI(sourceDirectory);
    underTest.clone(targetRepoBean);
    underTest.addRemote(targetRepoBean, "source_repo", sourceDirectory);
    Map<String, String> remotes = underTest.getRemotes(targetRepoBean);

    assertTrue(remotes.containsKey("source_repo") && remotes.containsValue(sourceDirectory));
    assertFalse(underTest.fetch(targetRepoBean, "source_repo"));

    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository sourceRepository = builder.setGitDir(sourceRepoBean.getGitConfigDirectory().toFile())
            .findGitDir().build();

    String filename = "should_be_in_both.txt";
    Files.write(sourceRepoBean.getRepoDirectory().resolve(filename), Arrays.asList("Hello World"),
            StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
    Git git = new Git(sourceRepository);
    git.add().addFilepattern(filename).call();
    git.commit().setMessage("Added " + filename).call();

    assertTrue(underTest.fetch(targetRepoBean, "source_repo"));

    TestUtility.destroyTestRepo(sourceRepoBean);
    TestUtility.destroyTestRepo(targetRepoBean);
}

From source file:com.surevine.gateway.scm.git.jgit.TestUtility.java

License:Open Source License

public static LocalRepoBean createTestRepoMultipleBranches() throws Exception {
    final String projectKey = "test_" + UUID.randomUUID().toString();
    final String repoSlug = "testRepo";
    final String remoteURL = "ssh://fake_url";
    final Path repoPath = Paths.get(PropertyUtil.getGitDir(), "local_scm", projectKey, repoSlug);
    Files.createDirectories(repoPath);
    final Repository repo = new FileRepository(repoPath.resolve(".git").toFile());
    repo.create();//  w w  w  .j a va 2 s.co  m
    final StoredConfig config = repo.getConfig();
    config.setString("remote", "origin", "url", remoteURL);
    config.save();

    final LocalRepoBean repoBean = new LocalRepoBean();
    repoBean.setProjectKey(projectKey);
    repoBean.setSlug(repoSlug);
    repoBean.setLocalBare(false);

    final Git git = new Git(repo);

    // add some files to some branches
    for (int i = 0; i < 3; i++) {
        final String filename = "newfile" + i + ".txt";
        Files.write(repoPath.resolve(filename), Arrays.asList("Hello World"), StandardCharsets.UTF_8,
                StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        git.add().addFilepattern(filename).call();
        git.commit().setMessage("Added " + filename).call();
    }

    git.checkout().setName("branch1").setCreateBranch(true).call();
    for (int i = 0; i < 3; i++) {
        final String filename = "branch1" + i + ".txt";
        Files.write(repoPath.resolve(filename), Arrays.asList("Hello World"), StandardCharsets.UTF_8,
                StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        git.add().addFilepattern(filename).call();
        git.commit().setMessage("Added " + filename).call();
    }

    git.checkout().setName("master").call();
    git.checkout().setName("branch2").setCreateBranch(true).call();
    for (int i = 0; i < 3; i++) {
        final String filename = "branch2" + i + ".txt";
        Files.write(repoPath.resolve(filename), Arrays.asList("Hello World"), StandardCharsets.UTF_8,
                StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        git.add().addFilepattern(filename).call();
        git.commit().setMessage("Added " + filename).call();
    }

    repo.close();
    return repoBean;
}

From source file:com.surevine.gateway.scm.git.jgit.TestUtility.java

License:Open Source License

public static LocalRepoBean createTestRepo() throws Exception {
    final String projectKey = "test_" + UUID.randomUUID().toString();
    final String repoSlug = "testRepo";
    final String remoteURL = "ssh://fake_url";
    final Path repoPath = Paths.get(PropertyUtil.getGitDir(), "local_scm", projectKey, repoSlug);
    Files.createDirectories(repoPath);
    final Repository repo = new FileRepository(repoPath.resolve(".git").toFile());
    repo.create();/*from   w  w w.j a v  a2  s.c o  m*/
    final StoredConfig config = repo.getConfig();
    config.setString("remote", "origin", "url", remoteURL);
    config.save();

    final LocalRepoBean repoBean = new LocalRepoBean();
    repoBean.setProjectKey(projectKey);
    repoBean.setSlug(repoSlug);
    repoBean.setLocalBare(false);
    repoBean.setSourcePartner("partner");

    final Git git = new Git(repo);

    for (int i = 0; i < 3; i++) {
        final String filename = "newfile" + i + ".txt";
        Files.write(repoPath.resolve(filename), Arrays.asList("Hello World"), StandardCharsets.UTF_8,
                StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        git.add().addFilepattern(filename).call();
        git.commit().setMessage("Added " + filename).call();
    }

    git.checkout().setName("master").call();

    repo.close();
    return repoBean;
}

From source file:com.tasktop.c2c.server.scm.service.FetchWorkerThread.java

License:Open Source License

private void doMirrorFetch(String projectId, File mirroredRepo) {
    try {/*from  www. jav  a 2 s.  com*/
        // Set the home directory. This is used for configuration and ssh keys
        FS fs = FS.detect();
        fs.setUserHome(new File(repositoryProvider.getBaseDir(), projectId));
        FileRepositoryBuilder builder = new FileRepositoryBuilder().setGitDir(mirroredRepo).setFS(fs).setup();
        Git git = new Git(new FileRepository(builder));
        git.fetch().setRefSpecs(new RefSpec("refs/heads/*:refs/heads/*")).setThin(true).call();
    } catch (Exception e) {
        logger.warn("Caught exception durring fetch", e);
    }
}

From source file:com.tasktop.c2c.server.scm.service.GitBrowseUtil.java

License:Open Source License

public static Trees getTrees(Repository r, String revision, String path, boolean history, int recursion)
        throws IOException, GitAPIException, EntityNotFoundException {
    if (path.startsWith("/")) {
        path = path.substring(1);/*from w ww .  j a va2  s .  c  om*/
    }

    RevObject revId = resolveRevision(r, revision);

    MutableObjectId revTree = new MutableObjectId();
    TreeWalk treeWalk = getTreeOnPath(revTree, r, revId, path);

    if (treeWalk == null) {
        throw new EntityNotFoundException("Revision: " + revision + ", path: " + path + " not found.");
    }

    Trees trees = new Trees(revTree.name());

    Git git = history ? new Git(r) : null;

    while (treeWalk.next()) {
        ObjectLoader loader = r.open(treeWalk.getObjectId(0));
        Trees.Tree t = new Trees.Tree(treeWalk.getObjectId(0).getName(), // sha
                treeWalk.getPathString(), // path
                treeWalk.getNameString(), // name
                getType(loader.getType()), // type
                treeWalk.getRawMode(0), // mode
                loader.getSize() // size
        );
        trees.getTree().add(t);

        if (recursion == -2 && t.getType() == Item.Type.TREE) {
            t.setEmpty(getEmptyPath(r, treeWalk.getObjectId(0)));
        }

        if (history) {
            addHistory(git, t, revId, /* path + ( path.length() == 0 ? "" : "/") + */t.getPath());
        }

    }

    return trees;
}

From source file:com.tasktop.c2c.server.scm.service.GitBrowseUtil.java

License:Open Source License

public static Blame getBlame(Repository r, String revision, String path) throws IOException, GitAPIException {

    if (path.startsWith("/")) {
        path = path.substring(1);/*  w w  w  .  j  av a  2 s  .c o m*/
    }

    Git git = new Git(r);

    ObjectId revId = r.resolve(revision);

    BlameCommand bc = git.blame();
    bc.setStartCommit(revId);
    bc.setFilePath(path);
    BlameResult br = bc.call();

    Blame blame = new Blame();
    blame.path = path;
    blame.revision = revision;
    blame.commits = new ArrayList<Commit>();
    blame.lines = new ArrayList<Blame.Line>();

    Map<String, Integer> sha2idx = new HashMap<String, Integer>();

    RawText resultContents = br.getResultContents();

    for (int i = 0; i < br.getResultContents().size(); i++) {

        RevCommit sourceCommit = br.getSourceCommit(i); // XXX should it really be the source commit
        String sha = sourceCommit.getName();
        Integer cIdx = sha2idx.get(sha);
        if (cIdx == null) {
            cIdx = blame.commits.size();
            Commit commit = GitDomain.createCommit(sourceCommit);
            blame.commits.add(commit);
            sha2idx.put(sha, cIdx);
        }

        Blame.Line bl = new Blame.Line();
        bl.commit = cIdx;
        bl.text = resultContents.getString(i);
        blame.lines.add(bl);
    }

    return blame;
}

From source file:com.technophobia.substeps.mojo.runner.SubstepsRunnerMojoTest.java

License:Open Source License

@Test
public void testGitStuff() {

    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    try {/*from w ww.  j a va2s . c  o m*/
        Repository repository = builder.setGitDir(new File("/home/ian/projects/github/substeps-framework/.git"))
                .readEnvironment() // scan environment GIT_* variables
                .findGitDir() // scan up the file system tree
                .build();

        Git git = new Git(repository);

        String branchName = git.getRepository().getBranch();
        System.out.println("get branch: " + branchName);

        if (branchName != null) {
            System.setProperty("SUBSTEPS_CURRENT_BRANCHNAME", branchName);
        }

        Config cfg = Configuration.INSTANCE.getConfig();
        //

        System.out.println(cfg.getString("user.name"));

        System.out.println(cfg.getString("substeps.current.branchname"));

    } catch (Exception e) {
        System.out.println("Exception trying to get hold of the current branch: " + e.getMessage());
    }

}

From source file:com.tenxdev.ovcs.command.AbstractSyncCommand.java

License:Open Source License

/**
 * Commit all changes and push to remote repository
 *
 * @throws OvcsException/* w  ww  . j a  v  a  2 s  . c o m*/
 *             if changes could not be committed or pushed
 */
protected void commitAndPush() throws OvcsException {
    try {
        final FileRepository fileRepository = getRepoForCurrentDir();
        final Git git = new Git(fileRepository);
        final Status status = git.status().setProgressMonitor(new TextProgressMonitor()).call();
        if (!status.isClean()) {
            git.add().addFilepattern(".").call();
            git.commit().setMessage("initial synchronization").setAll(true).call();
            doPush(git);
        }
    } catch (final GitAPIException e) {
        throw new OvcsException("Unable to commit to git repo: " + e.getMessage(), e);
    }
}

From source file:com.tenxdev.ovcs.command.CommitCommand.java

License:Open Source License

@Override
/**/*from  ww w .jav a2  s . c  om*/
 * {@inheritDoc}
 */
public void execute(final String... args) throws OvcsException {
    if (args.length != 1) {
        throw new OvcsException(USAGE);
    }
    System.out.println("Fetching changes from database...");
    final FileRepository repository = getRepoForCurrentDir();
    try {
        try (Connection conn = getDbConnectionForRepo(repository)) {
            final Git git = new Git(repository);
            final List<ChangeEntry> changes = writeChanges(repository);
            if (changes.isEmpty()) {
                System.out.println("No changes have been made, ending session");
            } else {
                try {
                    for (final ChangeEntry changeEntry : changes) {
                        git.add()
                                .addFilepattern(changeEntry.getName().toUpperCase(Locale.getDefault()) + ".sql")
                                .call();
                    }
                    git.commit().setMessage(getCommitMessage()).setAll(true).call();
                } catch (final GitAPIException e) {
                    throw new OvcsException("Unable to commit: " + e.getMessage(), e);
                }
            }
            try (CallableStatement stmt = conn.prepareCall("begin ovcs.handler.end_session; end;")) {
                stmt.execute();
                conn.commit();
            } catch (final SQLException e) {
                throw new OvcsException(
                        "Unexpected error while committing database changes, you may have to call "
                                + "ovcs.handler.end_session from your schema and commit to bring the database into a consistent state.",
                        e);
            }
            if (!changes.isEmpty()) {
                try {
                    doPush(git);
                    System.out.println("All changes committed and sent to remote repository.");
                } catch (final GitAPIException e) {
                    throw new OvcsException(String.format(
                            "All changes have been committed, but were not sent to the remote repository%n"
                                    + "Please run the ovcs push command to retry sending to the remote repository%nError: %s",
                            e.getMessage()), e);
                }
            }
        } catch (final SQLException e) {
            throw new OvcsException("Unexpected error while closing database connection, you may have to call "
                    + "ovcs.handler.end_session from your schema and commit to bring the database into a consistent state.",
                    e);
        }
    } finally {
        repository.close();
    }

}