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:sh.isaac.provider.sync.git.SyncServiceGIT.java

License:Apache License

/**
 * Gets the git.//from   w w  w.j  ava 2  s.com
 *
 * @return the git
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws IllegalArgumentException the illegal argument exception
 */
private Git getGit() throws IOException, IllegalArgumentException {
    if (this.localFolder == null) {
        throw new IllegalArgumentException(
                "localFolder has not yet been set - please call setRootLocation(...)");
    }

    if (!this.localFolder.isDirectory()) {
        LOG.error("The passed in local folder '{}' didn't exist", this.localFolder);
        throw new IllegalArgumentException("The localFolder must be a folder, and must exist");
    }

    final File gitFolder = new File(this.localFolder, ".git");

    if (!gitFolder.isDirectory()) {
        LOG.error("The passed in local folder '{}' does not appear to be a git repository", this.localFolder);
        throw new IllegalArgumentException("The localFolder does not appear to be a git repository");
    }

    return Git.open(gitFolder);
}

From source file:tests.GitTestsUtils.java

License:Open Source License

public static Repository inflate(File archive, File where) throws Exception {
    assert archive.exists();
    assert archive.isFile();
    assert archive.canRead();
    assert where.exists();
    assert where.isDirectory();
    assert where.canWrite();

    if (where.list().length > 0) {
        FileUtils.delete(where, FileUtils.RECURSIVE);
        if (!where.exists()) {
            where.mkdir();/*  ww  w  . ja  va 2s .  co  m*/
        } else if (where.list().length > 0) {
            throw new Exception("Couldn't clean up !");
        }
    }

    final int BUFFER = 2048;
    try {
        ZipInputStream zin = new ZipInputStream(new BufferedInputStream(new FileInputStream(archive)));

        ZipEntry entry;
        while ((entry = zin.getNextEntry()) != null) {
            File output = new File(where, entry.getName());
            output.getParentFile().mkdirs();
            if (!entry.isDirectory()) {

                FileOutputStream fos = new FileOutputStream(output.getAbsolutePath());
                BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);

                int count;
                byte data[] = new byte[BUFFER];
                while ((count = zin.read(data, 0, BUFFER)) != -1) {
                    dest.write(data, 0, count);

                }

                dest.flush();
                dest.close();
            }
        }

        zin.close();

    } catch (IOException e) {
        log.error("Error while inflating repository from " + archive.getPath(), e);
    }
    try {
        return Git.open(where).getRepository();
    } catch (IOException e) {
        log.error("Error while opening repository " + where.getPath(), e);
    }
    return null;
}

From source file:to.sauerkraut.krautadmin.core.Toolkit.java

License:Open Source License

public static boolean updateFromGit(final File repositoryDirectory, final URI repositoryUri) throws Exception {
    final String unexpectedExceptionText = "incremental plugin-update from git failed";
    final String upstream = "refs/remotes/origin/master";
    boolean hasUpdated = false;
    Git gitRepo = null;//from ww  w  . ja  va  2  s . c  om

    try {
        gitRepo = Git.open(repositoryDirectory);
        // first reset local changes
        gitRepo.reset().setMode(ResetCommand.ResetType.HARD).call();
        LOG.info("starting incremental plugin-update from git...");
        gitRepo.fetch().setRemote(Constants.DEFAULT_REMOTE_NAME).call();
        final RebaseResult rebaseResult = gitRepo.rebase().setStrategy(MergeStrategy.THEIRS)
                .setUpstream(upstream).setUpstreamName(upstream).call();
        final Status rebaseStatus = rebaseResult.getStatus();
        if (rebaseStatus.isSuccessful()) {
            if (!(Status.UP_TO_DATE.equals(rebaseStatus))) {
                hasUpdated = true;
            }
        } else {
            throw new WTFException(unexpectedExceptionText);
        }

        if (hasUpdated) {
            LOG.info("incremental plugin-update from git successful");
        } else {
            LOG.info("plugin-files are up-to-date");
        }
    } finally {
        try {
            if (gitRepo != null) {
                gitRepo.close();
            }
        } catch (Exception closex) {
            LOG.debug("closing git repo failed");
        }
    }

    return hasUpdated;
}

From source file:uk.ac.cam.cl.dtg.segue.database.GitDb.java

License:Apache License

/**
 * Create a new instance of a GitDb object
 * /*from   ww w.j a  va2  s . c om*/
 * This will immediately try and connect to the Git folder specified to check its validity.
 * 
 * @param repoLocation
 *            - location of the local git repository
 * @throws IOException
 *             - if we cannot access the repo location.
 */
public GitDb(final String repoLocation) throws IOException {
    Validate.notBlank(repoLocation);

    // unused for this constructor
    this.privateKey = null;
    this.sshFetchUrl = null;

    gitHandle = Git.open(new File(repoLocation));
}

From source file:uk.ac.cam.cl.dtg.segue.database.GitDb.java

License:Apache License

/**
 * Create a new instance of a GitDb object
 * /*from   ww w  .j  a v  a 2 s. c  o  m*/
 * This will immediately try and connect to the Git folder specified to check its validity.
 * 
 * This constructor is only necessary if we want to access a private repository.
 * 
 * @param repoLocation
 *            - location of the local git repository
 * @param sshFetchUrl
 *            - location of the remote git repository (ssh url used for fetching only)
 * @param privateKeyFileLocation
 *            - location of the local private key file used to access the ssh FetchUrl
 * @throws IOException
 *             - if we cannot access the repo location.
 */
@Inject
public GitDb(final String repoLocation, final String sshFetchUrl, final String privateKeyFileLocation)
        throws IOException {
    Validate.notBlank(repoLocation);

    this.sshFetchUrl = sshFetchUrl;
    this.privateKey = privateKeyFileLocation;

    gitHandle = Git.open(new File(repoLocation));
}

From source file:uk.ac.cam.UROP.twentyfourteen.database.GitDb.java

/**
 * Create a new instance of a GitDb object
 *
 * This will immediately try and connect to the Git folder specified to
 * check its validity./*  w  ww . ja va2 s .  co m*/
 *
 * @param repoLocation
 *            - location of the local git repository
 * @throws IOException
 */
public GitDb(String repoLocation) throws IOException {
    Validate.notBlank(repoLocation);

    // unused for this constructor
    this.privateKey = null;
    this.sshFetchUrl = null;

    gitHandle = Git.open(new File(repoLocation));
}

From source file:uk.ac.cam.UROP.twentyfourteen.database.GitDb.java

/**
 * Create a new instance of a GitDb object
 *
 * This will immediately try and connect to the Git folder specified to
 * check its validity./*from   w w  w.j a v a2 s .co m*/
 *
 * This constructor is only necessary if we want to access a private
 * repository.
 *
 * @param repoLocation
 *            - location of the local git repository
 * @param sshFetchUrl
 *            - location of the remote git repository (ssh url used for
 *            fetching only)
 * @param privateKeyFileLocation
 *            - location of the local private key file used to access the
 *            ssh FetchUrl
 * @throws IOException
 */
@Inject
public GitDb(String repoLocation, String sshFetchUrl, String privateKeyFileLocation) throws IOException {
    Validate.notBlank(repoLocation);

    this.sshFetchUrl = sshFetchUrl;
    this.privateKey = privateKeyFileLocation;

    gitHandle = Git.open(new File(repoLocation));
}

From source file:uk.ac.cam.UROP.twentyfourteen.database.GitDb.java

/**
 * Clone a repository and return a GitDb object.
 * <p>/*from   w w  w  . ja  v  a2s  .  com*/
 * Note, you may wish to delete the directory after you have finished with it.
 * This is entirely your responsibility!
 *
 * @param src Source repository path
 * @param dest Destination directory
 * @param bare Clone bare?
 * @param branch Branch to clone
 */
public GitDb(String src, File dest, boolean bare, String branch, String remote, final String privateKey)
        throws IOException {
    this.privateKey = privateKey;
    this.sshFetchUrl = src;

    try {
        SshSessionFactory factory = new JschConfigSessionFactory() {
            @Override
            public void configure(Host hc, com.jcraft.jsch.Session session) {
                // // TODO: Bad!
                // session.setConfig("StrictHostKeyChecking", "no");
            }

            @Override
            protected JSch getJSch(final OpenSshConfig.Host hc, org.eclipse.jgit.util.FS fs)
                    throws JSchException {
                JSch jsch = super.getJSch(hc, fs);
                jsch.removeAllIdentity();

                if (null != privateKey) {
                    jsch.addIdentity(privateKey);
                }

                return jsch;
            }
        };

        if (src != null)
            SshSessionFactory.setInstance(factory);

        this.gitHandle = Git.cloneRepository().setURI(src).setDirectory(dest).setBare(bare).setBranch(branch)
                .setRemote(remote).call();
        this.gitHandle = Git.open(dest);

    } catch (GitAPIException e) {
        log.error("Error while trying to clone the repository.", e);
        throw new RuntimeException("Error while trying to clone the repository." + e);
    }
}

From source file:us.rader.dinodocs.GitPuller.java

License:Apache License

/**
 * Pull the latest sources for the "master" branch from the "origin" remote
 * of a local Git repository.//  w w w  .j a  v  a  2 s.  com
 * 
 * @param localRepository
 *            File system path to local repository
 * 
 * @param branch
 *            Branch name
 * 
 * @throws Exception
 *             Thrown if the Git pull operation fails.
 */
private void pullRepository(File localRepository, String branch) throws Exception {

    try (Git git = Git.open(localRepository)) {

        PullCommand pullCommand = git.pull();
        pullCommand.setRemote(REMOTE_NAME);
        pullCommand.setRemoteBranchName(branch);
        PullResult pullResult = pullCommand.call();

        if (!pullResult.isSuccessful()) {

            throw new Exception(
                    MessageFormat.format("Failed to pull into {0}", localRepository.getCanonicalPath())); //$NON-NLS-1$

        }

        CheckoutCommand checkoutCommand = git.checkout();
        checkoutCommand.setName(branch);
        checkoutCommand.call();
        CheckoutResult checkoutResult = checkoutCommand.getResult();

        if (!checkoutResult.getStatus().equals(CheckoutResult.Status.OK)) {

            throw new Exception(MessageFormat.format("Failed to check out {0}", branch)); //$NON-NLS-1$

        }

        if (logger.isLoggable(Level.FINE)) {

            logger.logp(Level.FINE, getClass().getName(), "pullRepository)", MessageFormat //$NON-NLS-1$
                    .format("successfully pulled {0}/{1}", localRepository.getCanonicalPath(), branch)); //$NON-NLS-1$

        }
    }
}

From source file:util.DifferenceComputer.java

License:Apache License

public static void main(String[] args) throws IOException, GitAPIException {
    ////*w  ww.  jav a2s  . c om*/
    String coreRepoPath = "/Users/Onekin/Desktop/VODPlayer-CoreAssets-2";//args[0];
    String branchToLookInto = "develop.coreAssets";
    try {
        Git git = Git.open(new File(coreRepoPath));
        Repository repository = git.getRepository();
        Ref ref = repository.findRef(branchToLookInto);
        if (ref == null) {
            ref = git.checkout().setCreateBranch(true).setName(branchToLookInto)
                    .setUpstreamMode(SetupUpstreamMode.TRACK).setStartPoint("origin/" + branchToLookInto)
                    .call();
        }

        ObjectId parentCommit = repository
                .resolve(repository.findRef(branchToLookInto).getObjectId().getName() + "^^{commit}");//http://download.eclipse.org/jgit/site/4.2.0.201601211800-r/apidocs/org/eclipse/jgit/lib/Repository.html#resolve(java.lang.String)
        ObjectId currentCommit = repository
                .resolve(repository.findRef(branchToLookInto).getObjectId().getName() + "^{commit}");

        List<DiffEntry> listOfChangedFiles = getChangedFilesBetweenTwoCommits(coreRepoPath, currentCommit,
                parentCommit);
    } catch (Exception e) {
        e.getMessage();
        e.printStackTrace();
    }

}