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.gmail.cjbooms.thesis.pythonappengine.server.git.GitCommandsServiceImpl.java

License:Open Source License

/**
 * Pull changes from Remote Repository/*from   w  ww. ja  v  a 2 s.  co m*/
 *
 * @param pathToLocalRepository Root Location Of Repository or Project
 * @param remoteRepoURL The URL of the Remote Repository to push to
 * @param userName The remote login user name
 * @param password The remote login password
 * @throws IOException, GitAPIException, URISyntaxException
 */
public void pullChangesFromRemoteRepository(String pathToLocalRepository, String remoteRepoURL, String userName,
        String password) throws IOException {

    File repositoryDirectory = new File(pathToLocalRepository);
    Git localGitRepositoryRef = Git.open(repositoryDirectory);
    Repository localRepository = localGitRepositoryRef.getRepository();

    URIish remoteURI = null;
    try {
        remoteURI = new URIish(remoteRepoURL);
    } catch (URISyntaxException e) {
        throw new RuntimeException(e.getMessage());
    }
    Transport t = Transport.open(localRepository, remoteURI);
    ((TransportHttp) t).setUseSmartHttp(true);
    t.setCredentialsProvider(new UsernamePasswordCredentialsProvider(userName, password));
    RefSpec refSpec = new RefSpec("+refs/heads/*:refs/heads/*");

    t.fetch(NullProgressMonitor.INSTANCE, Collections.singleton(refSpec));

}

From source file:com.google.gct.idea.appengine.synchronization.SampleSyncTask.java

License:Apache License

private Git getLocalRepo() {
    File localRepo = new File(LOCAL_REPO_PATH);

    if (localRepo.exists()) {
        try {/*from  w  w w  .j  a v  a2  s  .  c o m*/
            return Git.open(localRepo);
        } catch (IOException e) {
            LOG.error("Error getting the local sample repository", e);
        }
    }
    return null;
}

From source file:com.google.gct.idea.appengine.synchronization.SampleSyncTaskTest.java

License:Apache License

@Ignore
@Test/* ww  w  .  j  av a2 s.  c  om*/
public void testSync_noLocalRepo() throws IOException, GitAPIException {
    // Sync files from mock Git Hub repo to mock local Android sample template repo
    SampleSyncTask sampleSyncTask = new SampleSyncTask(mockAndroidRepoPath, mockGitHubRepoPath);
    sampleSyncTask.run();

    File mockAndroidRepoDir = new File(mockAndroidRepoPath);
    Assert.assertTrue(mockAndroidRepoDir.exists());

    Git mockAndroidRepo = Git.open(mockAndroidRepoDir);

    Assert.assertEquals("refs/heads/master", mockAndroidRepo.getRepository().getFullBranch());
    Assert.assertEquals(1,
            mockAndroidRepo.branchList().setListMode(ListBranchCommand.ListMode.REMOTE).call().size());

    File mockGitHubRepoDir = new File(mockGitHubRepoPath);
    Assert.assertTrue(mockGitHubRepoDir.exists());

    File[] mockAndroidRepoFiles = mockAndroidRepoDir.listFiles();
    File[] mockGitHubRepoFiles = mockGitHubRepoDir.listFiles();

    Assert.assertEquals(mockGitHubRepoFiles.length, mockAndroidRepoFiles.length);

    int num = 0;
    for (File aFile : mockGitHubRepoFiles) {
        aFile.getName().equals(mockAndroidRepoFiles[0].getName());
        num++;
    }
}

From source file:com.google.gct.idea.appengine.synchronization.SampleSyncTaskTest.java

License:Apache License

@Ignore
@Test//from   ww  w .  ja v a  2  s. c o m
public void testSync_singleCommit() throws GitAPIException, IOException, URISyntaxException {
    // Sync files from mock Git Hub repo to mock local Android sample template repo
    SampleSyncTask sampleSyncTask = new SampleSyncTask(mockAndroidRepoPath, mockGitHubRepoPath);
    sampleSyncTask.run();

    // Add a file to mock github repo
    RevCommit commit = addFileToMockGitHubRepo("a.txt", "Adding a.txt");

    // Sync files from mock Git Hub repo to mock local Android sample template repo
    sampleSyncTask.run();

    // Check that the last commit in the mock Android repo is the commit made to add a new file
    Git mockAndroidRepo = Git.open(new File(mockAndroidRepoPath));
    Iterable<RevCommit> logs = mockAndroidRepo.log().call();
    Assert.assertNotNull(logs);

    // Check that commits exist
    boolean hasCommits = false;

    for (RevCommit aLog : logs) {
        hasCommits = true;
        Assert.assertEquals(commit.getCommitTime(), aLog.getCommitTime());
        Assert.assertEquals(commit.getFullMessage(), aLog.getFullMessage());
        break;
    }

    Assert.assertTrue(hasCommits);
}

From source file:com.google.gct.idea.appengine.synchronization.SampleSyncTaskTest.java

License:Apache License

@Ignore
@Test//www .  j ava  2  s . com
public void testSync_multipleCommits() throws GitAPIException, IOException {
    // Sync files from mock Git Hub repo to mock local Android sample template repo
    SampleSyncTask sampleSyncTask = new SampleSyncTask(mockAndroidRepoPath, mockGitHubRepoPath);
    sampleSyncTask.run();

    // Add 2 files to mock github repo
    RevCommit commit1 = addFileToMockGitHubRepo("a.txt", "Adding a.txt");
    Assert.assertNotNull(commit1);
    RevCommit commit2 = addFileToMockGitHubRepo("b.txt", "Adding b.txt");
    Assert.assertNotNull(commit2);

    // Delete a file from github repo
    RevCommit commit3 = removeFileFromMockGitHubRepo("a.txt", "Removing a.txt");
    Assert.assertNotNull(commit3);

    // Sync files from mock Git Hub repo to mock local Android sample template repo
    sampleSyncTask.run();

    // Check that last 3 commits in mock Android repo
    Git mockAndroidRepo = Git.open(new File(mockAndroidRepoPath));
    Iterable<RevCommit> logs = mockAndroidRepo.log().call();
    Assert.assertNotNull(logs);
    ArrayList<RevCommit> logsList = Lists.newArrayList(logs);

    Assert.assertTrue(logsList.size() >= 3);
    Assert.assertEquals(commit3.getCommitTime(), logsList.get(0).getCommitTime());
    Assert.assertEquals(commit3.getFullMessage(), logsList.get(0).getFullMessage());
    Assert.assertEquals(commit2.getCommitTime(), logsList.get(1).getCommitTime());
    Assert.assertEquals(commit2.getFullMessage(), logsList.get(1).getFullMessage());
    Assert.assertEquals(commit1.getCommitTime(), logsList.get(2).getCommitTime());
    Assert.assertEquals(commit1.getFullMessage(), logsList.get(2).getFullMessage());
}

From source file:com.googlecode.ounit.GitQuestion.java

License:Open Source License

@Override
public String findHeadRevision() {
    if (cloneDir == null)
        findRepo();/*from  w ww  .  j  av  a  2 s . co m*/

    try {
        Repository repo = Git.open(cloneDir).getRepository();
        Ref ref = repo.getRef(version);
        if (ref == null)
            ref = repo.getRef(Constants.MASTER);

        return ref.getObjectId().name();
    } catch (IOException e) {
        throw new RuntimeException("Unable to find HEAD revision", e);
    }
}

From source file:com.googlecode.ounit.GitQuestion.java

License:Open Source License

private void pull() {
    Long pullTime = pullTimes.get(id);
    long now = System.currentTimeMillis();

    if (pullTime != null && now - pullTime.longValue() < SCM_TTL * 1000) {
        getLog().debug("Skipping update, already pulled {} ms ago", now - pullTime.longValue());
        return;/*from   w  ww.j  a  v  a 2s  .  com*/
    }

    try {
        getLog().debug("Pulling in {}", cloneDir);
        Git.open(cloneDir).fetch().setTimeout(SCM_TIMEOUT).call();
        pullTimes.put(id, System.currentTimeMillis());
    } catch (Exception e) {
        // Failing a pull is not to be considered fatal ...
        getLog().error("Error while updating question " + id + "-" + version, e);
    }
}

From source file:com.hazelcast.simulator.utils.jars.GitSupport.java

License:Open Source License

private Git cloneIfNecessary(File src) throws GitAPIException, IOException {
    Git git;/*from  w ww  .j a va 2  s. co  m*/
    if (!isValidLocalRepository(src)) {
        LOGGER.info("Cloning Hazelcast Git repository to " + src.getAbsolutePath()
                + ". This might take a while...");
        git = Git.cloneRepository().setURI(HAZELCAST_MAIN_REPO_URL).setDirectory(src).call();
    } else {
        git = Git.open(src);
    }
    return git;
}

From source file:com.hazelcast.simulator.utils.jars.GitSupport.java

License:Open Source License

private boolean isValidLocalRepository(File repository) {
    boolean result = false;
    Git git = null;/*from   w  w  w . j  a  va 2 s .c  o  m*/
    try {
        git = Git.open(repository);
        result = true;
    } catch (RepositoryNotFoundException e) {
        result = false;
    } catch (IOException e) {
        result = false;
    } finally {
        if (git != null) {
            git.close();
        }
    }
    return result;
}

From source file:com.hpe.application.automation.tools.octane.model.processors.scm.GitSCMProcessor.java

License:Open Source License

@Override
public CommonOriginRevision getCommonOriginRevision(final Run run) {
    //for phase 1 this is hard coded since its not possible to calculate it, and configuration from outside will complicate the feature
    //so for this phase we keep it hardcoded.
    CommonOriginRevision commonOriginRevision = new CommonOriginRevision();

    try {/*from  w  w w.j  a  v a 2  s .c om*/
        final AbstractBuild abstractBuild = (AbstractBuild) run;
        FilePath workspace = ((AbstractBuild) run).getWorkspace();
        if (workspace != null) {
            commonOriginRevision = workspace.act(new FilePath.FileCallable<CommonOriginRevision>() {
                @Override
                public CommonOriginRevision invoke(File file, VirtualChannel channel)
                        throws IOException, InterruptedException {
                    CommonOriginRevision result = new CommonOriginRevision();
                    File repoDir = new File(getRemoteString(abstractBuild) + File.separator + ".git");
                    Git git = Git.open(repoDir);
                    Repository repo = git.getRepository();
                    final RevWalk walk = new RevWalk(repo);

                    ObjectId resolveForCurrentBranch = repo.resolve(Constants.HEAD);
                    RevCommit currentBranchCommit = walk.parseCommit(resolveForCurrentBranch);
                    ObjectId resolveForMaster = repo.resolve(MASTER);
                    RevCommit masterCommit = walk.parseCommit(resolveForMaster);

                    walk.reset();
                    walk.setRevFilter(RevFilter.MERGE_BASE);
                    walk.markStart(currentBranchCommit);
                    walk.markStart(masterCommit);
                    final RevCommit base = walk.next();
                    if (base == null)
                        return result;
                    final RevCommit base2 = walk.next();
                    if (base2 != null) {
                        throw new NoMergeBaseException(
                                NoMergeBaseException.MergeBaseFailureReason.MULTIPLE_MERGE_BASES_NOT_SUPPORTED,
                                MessageFormat.format(JGitText.get().multipleMergeBasesFor,
                                        currentBranchCommit.name(), masterCommit.name(), base.name(),
                                        base2.name()));
                    }
                    result.revision = base.getId().getName();
                    result.branch = getBranchName(run);
                    return result;
                }

                @Override
                public void checkRoles(RoleChecker roleChecker) throws SecurityException {
                    if (roleChecker != null) {
                        logger.info("Note : roleChecker is not empty, but no action was taken");
                    }
                }
            });
        }
        logger.info("most recent common revision resolved to " + commonOriginRevision.revision + " (branch: "
                + commonOriginRevision.branch + ")");
    } catch (Exception e) {
        logger.error("failed to resolve most recent common revision", e);
        return commonOriginRevision;
    }
    return commonOriginRevision;
}