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

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

Introduction

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

Prototype

public Repository getRepository() 

Source Link

Document

Get repository

Usage

From source file:org.ossmeter.platform.vcs.git.GitManager.java

License:Open Source License

@Override
public String getFirstRevision(VcsRepository repository) throws Exception {
    Git git = getGit((GitRepository) repository);

    Repository repo = git.getRepository();
    RevWalk walk = new RevWalk(repo);

    Iterator<RevCommit> iterator = git.log().call().iterator();
    walk.parseCommit(iterator.next());//from   w  w w.  j  a v  a  2s  .  c om

    String revision = null;

    // The commits are ordered latest first, so we want the last one.
    while (iterator.hasNext()) {
        RevCommit commit = iterator.next();
        if (!iterator.hasNext()) {
            revision = commit.getId().getName();
        }
    }

    return revision;
}

From source file:org.ossmeter.platform.vcs.git.GitManager.java

License:Open Source License

@Override
public int compareVersions(VcsRepository repository, String versionOne, String versionTwo) throws Exception {
    Git git = getGit((GitRepository) repository);

    Repository repo = git.getRepository();
    RevWalk walk = new RevWalk(repo);

    Iterator<RevCommit> iterator = git.log().call().iterator();
    walk.parseCommit(iterator.next());//from   w  ww. j  a va 2s .co  m

    List<String> revisions = new ArrayList<String>();

    // The commits are ordered latest first, so we want the last one.
    while (iterator.hasNext()) {
        RevCommit commit = iterator.next();
        revisions.add(commit.getId().getName());
    }
    Integer oneIndex = revisions.indexOf(versionOne);
    Integer twoIndex = revisions.indexOf(versionTwo);

    //      System.out.println(oneIndex);
    //      System.out.println(twoIndex);
    //      System.out.println(revisions);

    // Because the revision list is reversed, we compare two to one instead of the other way around
    return twoIndex.compareTo(oneIndex);
}

From source file:org.ossmeter.platform.vcs.git.GitManager.java

License:Open Source License

@Override
public String[] getRevisionsForDate(VcsRepository repository, Date date) throws Exception {
    long epoch = date.toJavaDate().getTime();

    List<String> revisions = new ArrayList<String>();

    Git git = getGit((GitRepository) repository);

    Repository repo = git.getRepository();
    RevWalk walk = new RevWalk(repo);

    Iterator<RevCommit> iterator = git.log().call().iterator();
    walk.parseCommit(iterator.next());//from   w w w.j  av a2 s.c o  m

    boolean foundDate = false;
    while (iterator.hasNext()) {
        RevCommit commit = iterator.next();

        //         System.out.println(Long.valueOf(commit.getCommitTime())*1000 + " == " + epoch); 
        //         System.err.println("comparing " +new Date(Long.valueOf(commit.getCommitTime())*1000) + " with date " + date + " and epoch " + epoch);
        if (new Date(Long.valueOf(commit.getCommitTime()) * 1000).compareTo(date) == 0) {
            foundDate = true;
            revisions.add(0, commit.getId().getName());
            //FIXME: Added the zero index to in an attempt to bugfix
        } else if (foundDate) {
            break;
        }
    }

    return revisions.toArray(new String[revisions.size()]);
}

From source file:org.ossmeter.platform.vcs.git.GitManager.java

License:Open Source License

@Override
public Date getDateForRevision(VcsRepository repository, String revision) throws Exception {
    Git git = getGit((GitRepository) repository);

    Repository repo = git.getRepository();
    RevWalk walk = new RevWalk(repo);

    Iterator<RevCommit> iterator = git.log().call().iterator();
    walk.parseCommit(iterator.next());/*  w  w w .  j  a  va 2s  . c o m*/

    Date date = null;
    while (iterator.hasNext()) {
        RevCommit commit = iterator.next();
        if (commit.getId().getName().equals(revision)) {
            date = new Date(Long.valueOf(commit.getCommitTime()) * 1000);
        }
    }

    return date;
}

From source file:org.repodriller.scm.GitRepository.java

License:Apache License

private String discoverMainBranchName(Git git) throws IOException {
    return git.getRepository().getBranch();
}

From source file:org.repodriller.scm.GitRepository.java

License:Apache License

private List<ChangeSet> firstParentsOnly(Git git) {
    RevWalk revWalk = null;//from   w ww.  j a v a2s  .  c  o m
    try {
        List<ChangeSet> allCs = new ArrayList<>();

        revWalk = new RevWalk(git.getRepository());
        revWalk.setRevFilter(new FirstParentFilter());
        revWalk.sort(RevSort.TOPO);
        Ref headRef = git.getRepository().getRef(Constants.HEAD); /* TODO Deprecated. */
        RevCommit headCommit = revWalk.parseCommit(headRef.getObjectId());
        revWalk.markStart(headCommit);
        for (RevCommit revCommit : revWalk) {
            allCs.add(extractChangeSet(revCommit));
        }

        return allCs;

    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        revWalk.close();
    }
}

From source file:org.review_board.ereviewboard.ui.wizard.DiffCreator.java

License:Open Source License

public byte[] createDiff(Set<ChangedFile> selectedFiles, File rootLocation, Git gitClient)
        throws IOException, GitAPIException {

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    List<DiffEntry> changes = new ArrayList<DiffEntry>(selectedFiles.size());

    for (ChangedFile changedFile : selectedFiles) {
        changes.add(changedFile.getDiffEntry());
    }/*from   w ww.  jav  a2 s.c o  m*/

    final int INDEX_LENGTH = 40;
    DiffFormatter diffFormatter = new DiffFormatter(outputStream);
    diffFormatter.setRepository(gitClient.getRepository());
    diffFormatter.setDiffComparator(RawTextComparator.WS_IGNORE_ALL);
    diffFormatter.setAbbreviationLength(INDEX_LENGTH);
    diffFormatter.setDetectRenames(true);

    diffFormatter.format(changes);
    diffFormatter.flush();

    return outputStream.toByteArray();
}

From source file:org.spdx.tools.LicenseListPublisher.java

License:Apache License

/**
 * Publish a license list to the license data git repository
 * @param release license list release name (must be associatd with a tag in the license-list-xml repo)
 * @param gitUserName github username to be used - must have commit access to the license-xml-data repo
 * @param gitPassword github password/*from   w w w .j a  v  a2  s  . co  m*/
 * @throws LicensePublisherException 
 * @throws LicenseGeneratorException 
 */
private static void publishLicenseList(String release, String gitUserName, String gitPassword,
        boolean ignoreWarnings) throws LicensePublisherException, LicenseGeneratorException {
    CredentialsProvider githubCredentials = new UsernamePasswordCredentialsProvider(gitUserName, gitPassword);
    File licenseXmlDir = null;
    File licenseDataDir = null;
    Git licenseXmlGit = null;
    Git licenseDataGit = null;
    try {
        licenseXmlDir = Files.createTempDirectory("LicenseXML").toFile();
        System.out.println("Cloning the license XML repository - this could take a while...");
        licenseXmlGit = Git.cloneRepository().setCredentialsProvider(githubCredentials)
                .setDirectory(licenseXmlDir).setURI(LICENSE_XML_URI).call();
        Ref releaseTag = licenseXmlGit.getRepository().getTags().get(release);
        if (releaseTag == null) {
            throw new LicensePublisherException(
                    "Release " + release + " not found as a tag in the License List XML repository");
        }
        licenseXmlGit.checkout().setName(releaseTag.getName()).call();
        licenseDataDir = Files.createTempDirectory("LicenseData").toFile();
        System.out.println("Cloning the license data repository - this could take a while...");
        licenseDataGit = Git.cloneRepository().setCredentialsProvider(githubCredentials)
                .setDirectory(licenseDataDir).setURI(LICENSE_DATA_URI).call();
        Ref dataReleaseTag = licenseDataGit.getRepository().getTags().get(release);
        boolean dataReleaseTagExists = false;
        if (dataReleaseTag != null) {
            dataReleaseTagExists = true;
            licenseDataGit.checkout().setName(releaseTag.getName()).call();
        }
        cleanLicenseDataDir(licenseDataDir);
        String todayDate = new SimpleDateFormat("dd-MMM-yyyy").format(Calendar.getInstance().getTime());
        List<String> warnings = LicenseRDFAGenerator.generateLicenseData(
                new File(licenseXmlDir.getPath() + File.separator + "src"), licenseDataDir, release, todayDate);
        if (warnings.size() > 0 && !ignoreWarnings) {
            throw new LicensePublisherException(
                    "There are some skipped or invalid license input data.  Publishing aborted.  To ignore, add the --ignore option as the first parameter");
        }
        licenseDataGit.add().addFilepattern(".").call();
        licenseDataGit.commit().setAll(true)
                .setCommitter("SPDX License List Publisher", "spdx-tech@lists.spdx.org")
                .setMessage("License List Publisher for " + gitUserName + ".  License list version " + release)
                .call();
        if (!dataReleaseTagExists) {
            licenseDataGit.tag().setName(release).setMessage("SPDX License List release " + release).call();
        }
        licenseDataGit.push().setCredentialsProvider(githubCredentials).setPushTags().call();
    } catch (IOException e) {
        throw new LicensePublisherException("I/O Error publishing license list", e);
    } catch (InvalidRemoteException e) {
        throw new LicensePublisherException("Invalid remote error trying to access the git repositories", e);
    } catch (TransportException e) {
        throw new LicensePublisherException("Transport error trying to access the git repositories", e);
    } catch (GitAPIException e) {
        throw new LicensePublisherException("GIT API error trying to access the git repositories", e);
    } finally {
        if (licenseXmlGit != null) {
            licenseXmlGit.close();
        }
        if (licenseDataGit != null) {
            licenseDataGit.close();
        }
        if (licenseXmlDir != null) {
            deleteDir(licenseXmlDir);
        }
        if (licenseDataDir != null) {
            deleteDir(licenseDataDir);
        }
    }
}

From source file:org.springframework.cloud.config.server.environment.JGitEnvironmentRepository.java

License:Apache License

/**
 * Get the working directory ready./* www  .  ja  va 2s .  c o m*/
 */
public String refresh(String label) {
    initialize();
    Git git = null;
    try {
        git = createGitClient();
        if (shouldPull(git)) {
            fetch(git, label);
            //checkout after fetch so we can get any new branches, tags, ect.
            checkout(git, label);
            if (isBranch(git, label)) {
                //merge results from fetch
                merge(git, label);
                if (!isClean(git)) {
                    logger.warn("The local repository is dirty. Resetting it to origin/" + label + ".");
                    resetHard(git, label, "refs/remotes/origin/" + label);
                }
            }
        } else {
            //nothing to update so just checkout
            checkout(git, label);
        }
        //always return what is currently HEAD as the version
        return git.getRepository().getRef("HEAD").getObjectId().getName();
    } catch (RefNotFoundException e) {
        throw new NoSuchLabelException("No such label: " + label, e);
    } catch (GitAPIException e) {
        throw new IllegalStateException("Cannot clone or checkout repository", e);
    } catch (Exception e) {
        throw new IllegalStateException("Cannot load environment", e);
    } finally {
        try {
            if (git != null) {
                git.close();
            }
        } catch (Exception e) {
            this.logger.warn("Could not close git repository", e);
        }
    }
}

From source file:org.springframework.cloud.config.server.environment.JGitEnvironmentRepository.java

License:Apache License

public /*public for testing*/ boolean shouldPull(Git git) throws GitAPIException {
    boolean shouldPull;
    Status gitStatus = git.status().call();
    boolean isWorkingTreeClean = gitStatus.isClean();
    String originUrl = git.getRepository().getConfig().getString("remote", "origin", "url");

    if (this.forcePull && !isWorkingTreeClean) {
        shouldPull = true;/*w  ww . j  a v  a 2 s  .co m*/
        logDirty(gitStatus);
    } else {
        shouldPull = isWorkingTreeClean && originUrl != null;
    }
    if (!isWorkingTreeClean && !this.forcePull) {
        this.logger.info("Cannot pull from remote " + originUrl + ", the working tree is not clean.");
    }
    return shouldPull;
}