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

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

Introduction

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

Prototype

public FetchCommand fetch() 

Source Link

Document

Return a command object to execute a Fetch command

Usage

From source file:nz.co.fortytwo.signalk.handler.GitHandler.java

License:Open Source License

protected String install(String path) throws Exception {
    //staticDir.mkdirs();
    Git result = null;
    try {//ww  w  .j  av a  2 s .  c  o  m
        File installLogDir = new File(staticDir, "logs");
        installLogDir.mkdirs();
        //make log name
        String logFile = "output.log";
        File output = new File(installLogDir, logFile);
        File destDir = new File(staticDir, SLASH + path);
        destDir.mkdirs();
        String gitPath = github + path + ".git";
        logger.debug("Cloning from " + gitPath + " to " + destDir.getAbsolutePath());
        FileUtils.writeStringToFile(output,
                "Updating from " + gitPath + " to " + destDir.getAbsolutePath() + "\n", false);
        try {
            result = Git.cloneRepository().setURI(gitPath).setDirectory(destDir).call();
            result.fetch().setRemote(gitPath);
            logger.debug("Cloned " + gitPath + " repository: " + result.getRepository().getDirectory());
            FileUtils.writeStringToFile(output,
                    "DONE: Cloned " + gitPath + " repository: " + result.getRepository().getDirectory(), true);
        } catch (Exception e) {
            FileUtils.writeStringToFile(output, e.getMessage(), true);
            FileUtils.writeStringToFile(output, e.getStackTrace().toString(), true);
            logger.debug("Error updating " + gitPath + " repository: " + e.getMessage(), e);
        }
        /*try{
           //now run npm install
           runNpmInstall(output, destDir);
        }catch(Exception e){
           FileUtils.writeStringToFile(output, e.getMessage(),true);
           FileUtils.writeStringToFile(output, e.getStackTrace().toString(),true);
           logger.debug("Error updating "+gitPath+" repository: " + e.getMessage(),e);
        }*/
        return logFile;

    } finally {
        if (result != null)
            result.close();
    }

}

From source file:org.apache.maven.scm.provider.git.jgit.command.checkout.JGitCheckOutCommand.java

License:Apache License

/**
 * For git, the given repository is a remote one. We have to clone it first if the working directory does not
 * contain a git repo yet, otherwise we have to git-pull it.
 * <p/>/*from  w  ww. j av  a2 s .co m*/
 * {@inheritDoc}
 */
protected CheckOutScmResult executeCheckOutCommand(ScmProviderRepository repo, ScmFileSet fileSet,
        ScmVersion version, boolean recursive) throws ScmException {
    GitScmProviderRepository repository = (GitScmProviderRepository) repo;

    if (GitScmProviderRepository.PROTOCOL_FILE.equals(repository.getFetchInfo().getProtocol())
            && repository.getFetchInfo().getPath().indexOf(fileSet.getBasedir().getPath()) >= 0) {
        throw new ScmException("remote repository must not be the working directory");
    }

    Git git = null;
    try {

        ProgressMonitor monitor = JGitUtils.getMonitor(getLogger());

        String branch = version != null ? version.getName() : null;

        if (StringUtils.isBlank(branch)) {
            branch = Constants.MASTER;
        }

        getLogger().debug("try checkout of branch: " + branch);

        if (!fileSet.getBasedir().exists() || !(new File(fileSet.getBasedir(), ".git").exists())) {
            if (fileSet.getBasedir().exists()) {
                // git refuses to clone otherwise
                fileSet.getBasedir().delete();
            }

            // FIXME only if windauze
            WindowCacheConfig cfg = new WindowCacheConfig();
            cfg.setPackedGitMMAP(false);
            cfg.install();

            // no git repo seems to exist, let's clone the original repo
            CredentialsProvider credentials = JGitUtils.getCredentials((GitScmProviderRepository) repo);
            getLogger().info("cloning [" + branch + "] to " + fileSet.getBasedir());
            CloneCommand command = Git.cloneRepository().setURI(repository.getFetchUrl());
            command.setCredentialsProvider(credentials).setBranch(branch).setDirectory(fileSet.getBasedir());
            command.setProgressMonitor(monitor);
            git = command.call();
        }

        JGitRemoteInfoCommand remoteInfoCommand = new JGitRemoteInfoCommand();
        remoteInfoCommand.setLogger(getLogger());
        RemoteInfoScmResult result = remoteInfoCommand.executeRemoteInfoCommand(repository, fileSet, null);

        if (git == null) {
            git = Git.open(fileSet.getBasedir());
        }

        if (fileSet.getBasedir().exists() && new File(fileSet.getBasedir(), ".git").exists()
                && result.getBranches().size() > 0) {
            // git repo exists, so we must git-pull the changes
            CredentialsProvider credentials = JGitUtils.prepareSession(getLogger(), git, repository);

            if (version != null && StringUtils.isNotEmpty(version.getName()) && (version instanceof ScmTag)) {
                // A tag will not be pulled but we only fetch all the commits from the upstream repo
                // This is done because checking out a tag might not happen on the current branch
                // but create a 'detached HEAD'.
                // In fact, a tag in git may be in multiple branches. This occurs if
                // you create a branch after the tag has been created
                getLogger().debug("fetch...");
                git.fetch().setCredentialsProvider(credentials).setProgressMonitor(monitor).call();
            } else {
                getLogger().debug("pull...");
                git.pull().setCredentialsProvider(credentials).setProgressMonitor(monitor).call();
            }
        }

        Set<String> localBranchNames = JGitBranchCommand.getShortLocalBranchNames(git);
        if (version instanceof ScmTag) {
            getLogger().info("checkout tag [" + branch + "] at " + fileSet.getBasedir());
            git.checkout().setName(branch).call();
        } else if (localBranchNames.contains(branch)) {
            getLogger().info("checkout [" + branch + "] at " + fileSet.getBasedir());
            git.checkout().setName(branch).call();
        } else {
            getLogger().info("checkout remote branch [" + branch + "] at " + fileSet.getBasedir());
            git.checkout().setName(branch).setCreateBranch(true)
                    .setStartPoint(Constants.DEFAULT_REMOTE_NAME + "/" + branch).call();
        }

        RevWalk revWalk = new RevWalk(git.getRepository());
        RevCommit commit = revWalk.parseCommit(git.getRepository().resolve(Constants.HEAD));
        revWalk.release();

        final TreeWalk walk = new TreeWalk(git.getRepository());
        walk.reset(); // drop the first empty tree, which we do not need here
        walk.setRecursive(true);
        walk.addTree(commit.getTree());

        List<ScmFile> listedFiles = new ArrayList<ScmFile>();
        while (walk.next()) {
            listedFiles.add(new ScmFile(walk.getPathString(), ScmFileStatus.CHECKED_OUT));
        }
        walk.release();

        getLogger().debug("current branch: " + git.getRepository().getBranch());

        return new CheckOutScmResult("checkout via JGit", listedFiles);
    } catch (Exception e) {
        throw new ScmException("JGit checkout failure!", e);
    } finally {
        JGitUtils.closeRepo(git);
    }
}

From source file:org.aysada.licensescollector.dependencies.impl.GitCodeBaseProvider.java

License:Open Source License

public File getLocalRepositoryRoot(String remoteUrl) {
    try {/*  w  w w .j a  v a2  s . c  o  m*/
        File prjWs = getLocalWSFor(remoteUrl);
        if (prjWs.exists()) {
            Repository repo = Git.open(prjWs).getRepository();
            Git git = new Git(repo);
            git.fetch().call();
            git.close();
            LOGGER.info("Lcoal git repo for {} updated.", remoteUrl);
            return repo.getDirectory();
        } else {
            prjWs.mkdir();
            Git localRepo = Git.cloneRepository().setDirectory(prjWs).setURI(remoteUrl)
                    .setCloneAllBranches(false).call();
            File directory = localRepo.getRepository().getDirectory();
            localRepo.close();
            LOGGER.info("Cloned lcoal git repo for {}.", remoteUrl);
            return directory;
        }
    } catch (IOException | GitAPIException e) {
        LOGGER.error("Error working with git.", e);
    }
    return null;
}

From source file:org.commonwl.view.git.GitService.java

License:Apache License

/**
 * Gets a repository, cloning into a local directory or
 * @param gitDetails The details of the Git repository
 * @param reuseDir Whether the cached repository can be used
 * @return The git object for the repository
 *///from   ww w .j  av  a2  s . c  o  m
public Git getRepository(GitDetails gitDetails, boolean reuseDir) throws GitAPIException, IOException {
    Git repo;
    if (reuseDir) {
        // Base dir from configuration, name from hash of repository URL
        String baseName = DigestUtils.sha1Hex(GitDetails.normaliseUrl(gitDetails.getRepoUrl()));

        // Check if folder already exists
        Path repoDir = gitStorage.resolve(baseName);
        if (Files.isReadable(repoDir) && Files.isDirectory(repoDir)) {
            repo = Git.open(repoDir.toFile());
            repo.fetch().call();
        } else {
            // Create a folder and clone repository into it
            Files.createDirectory(repoDir);
            repo = cloneRepo(gitDetails.getRepoUrl(), repoDir.toFile());
        }
    } else {
        // Another thread is already using the existing folder
        // Must create another temporary one
        repo = cloneRepo(gitDetails.getRepoUrl(), createTempDir());
    }

    // Checkout the specific branch or commit ID
    if (repo != null) {
        // Create a new local branch if it does not exist and not a commit ID
        String branchOrCommitId = gitDetails.getBranch();
        final boolean isId = ObjectId.isId(branchOrCommitId);
        if (!isId) {
            branchOrCommitId = "refs/remotes/origin/" + branchOrCommitId;
        }
        try {
            repo.checkout().setName(branchOrCommitId).call();
        } catch (Exception ex) {
            // Maybe it was a tag
            if (!isId && ex instanceof RefNotFoundException) {
                final String tag = gitDetails.getBranch();
                try {
                    repo.checkout().setName(tag).call();
                } catch (Exception ex2) {
                    // Throw the first exception, to keep the same behavior as before.
                    throw ex;
                }
            } else {
                throw ex;
            }
        }
    }

    return repo;
}

From source file:org.craftercms.studio.impl.v1.deployment.EnvironmentStoreGitBranchDeployer.java

License:Open Source License

private void checkoutEnvironment(Repository repository, String site) {
    Git git = null;
    try {//from   w w  w .j  a va 2  s . co m
        Ref branchRef = repository.findRef(environment);
        git = new Git(repository);
        git.checkout().setCreateBranch(true).setName(environment)
                .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
                .setStartPoint("origin/" + environment).call();
        git.fetch().call();
        git.pull().call();
    } catch (RefNotFoundException e) {
        try {
            git.checkout().setOrphan(true).setName(environment).call();
            ProcessBuilder pb = new ProcessBuilder();
            pb.command("git", "rm", "-rf", ".");
            pb.directory(repository.getDirectory().getParentFile());
            Process p = pb.start();
            p.waitFor();

            git.commit().setMessage("initial content").setAllowEmpty(true).call();
        } catch (GitAPIException | InterruptedException | IOException e1) {
            logger.error("Error checking out environment store branch for site " + site + " environment "
                    + environment, e1);
        }
    } catch (IOException | GitAPIException e) {
        logger.error(
                "Error checking out environment store branch for site " + site + " environment " + environment,
                e);
    }
}

From source file:org.eclipse.egit.core.op.ConfigureFetchAfterCloneTask.java

License:Open Source License

/**
 * @param repository the cloned repository
 * @param monitor//from   ww  w .  j av a  2s  .co  m
 * @throws CoreException
 */
public void execute(Repository repository, IProgressMonitor monitor) throws CoreException {
    try {
        RemoteConfig configToUse = new RemoteConfig(repository.getConfig(), remoteName);
        if (fetchRefSpec != null)
            configToUse.addFetchRefSpec(new RefSpec(fetchRefSpec));
        configToUse.update(repository.getConfig());
        repository.getConfig().save();
        Git git = new Git(repository);
        try {
            git.fetch().setRemote(remoteName).call();
        } catch (Exception e) {
            Activator.logError(NLS.bind(CoreText.ConfigureFetchAfterCloneTask_couldNotFetch, fetchRefSpec), e);
        }
    } catch (Exception e) {
        throw new CoreException(Activator.error(e.getMessage(), e));
    }

}

From source file:org.eclipse.orion.server.git.jobs.FetchJob.java

License:Open Source License

private IStatus doFetch() throws IOException, CoreException, URISyntaxException, GitAPIException {
    Repository db = getRepository();/*from ww  w  .ja  v a 2  s . c  om*/

    Git git = new Git(db);
    FetchCommand fc = git.fetch();

    RemoteConfig remoteConfig = new RemoteConfig(git.getRepository().getConfig(), remote);
    credentials.setUri(remoteConfig.getURIs().get(0));

    fc.setCredentialsProvider(credentials);
    fc.setRemote(remote);
    if (branch != null) {
        // refs/heads/{branch}:refs/remotes/{remote}/{branch}
        RefSpec spec = new RefSpec(
                Constants.R_HEADS + branch + ":" + Constants.R_REMOTES + remote + "/" + branch); //$NON-NLS-1$ //$NON-NLS-2$
        spec = spec.setForceUpdate(force);
        fc.setRefSpecs(spec);
    }
    FetchResult fetchResult = fc.call();
    return handleFetchResult(fetchResult);
}

From source file:org.eclipse.orion.server.git.servlets.FetchJob.java

License:Open Source License

private IStatus doFetch()
        throws IOException, CoreException, JGitInternalException, InvalidRemoteException, URISyntaxException {
    Repository db = getRepository();//from   w  w w .ja  v  a2 s.  c  o  m
    String branch = getRemoteBranch();

    Git git = new Git(db);
    FetchCommand fc = git.fetch();

    RemoteConfig remoteConfig = new RemoteConfig(git.getRepository().getConfig(), remote);
    credentials.setUri(remoteConfig.getURIs().get(0));

    fc.setCredentialsProvider(credentials);
    fc.setRemote(remote);
    if (branch != null) {
        // refs/heads/{branch}:refs/remotes/{remote}/{branch}
        RefSpec spec = new RefSpec(
                Constants.R_HEADS + branch + ":" + Constants.R_REMOTES + remote + "/" + branch); //$NON-NLS-1$ //$NON-NLS-2$
        spec = spec.setForceUpdate(force);
        fc.setRefSpecs(spec);
    }
    FetchResult fetchResult = fc.call();

    // handle result
    for (TrackingRefUpdate updateRes : fetchResult.getTrackingRefUpdates()) {
        Result res = updateRes.getResult();
        // handle status for given ref
        switch (res) {
        case NOT_ATTEMPTED:
        case NO_CHANGE:
        case NEW:
        case FORCED:
        case FAST_FORWARD:
        case RENAMED:
            // do nothing, as these statuses are OK
            break;
        case REJECTED:
        case REJECTED_CURRENT_BRANCH:
            // show warning, as only force fetch can finish successfully 
            return new Status(IStatus.WARNING, GitActivator.PI_GIT, res.name());
        default:
            return new Status(IStatus.ERROR, GitActivator.PI_GIT, res.name());
        }
    }
    return Status.OK_STATUS;
}

From source file:org.eclipse.recommenders.snipmatch.GitSnippetRepository.java

License:Open Source License

private Git fetch() throws GitAPIException, IOException {
    localRepo = new FileRepositoryBuilder().setGitDir(gitFile).build();
    Git git = new Git(localRepo);
    git.fetch().call();
    return git;//ww w.j  a va2  s  .  c o  m
}

From source file:org.fedoraproject.eclipse.packager.tests.utils.git.GitConvertTestProject.java

License:Open Source License

/**
 * Adds a remote repository to the existing local packager project
 *
 * @throws Exception/*  w  ww.j  a v  a2s. com*/
 */
public void addRemoteRepository(String uri, Git git) throws Exception {

    RemoteConfig config = new RemoteConfig(git.getRepository().getConfig(), "origin"); //$NON-NLS-1$
    config.addURI(new URIish(uri));
    String dst = Constants.R_REMOTES + config.getName();
    RefSpec refSpec = new RefSpec();
    refSpec = refSpec.setForceUpdate(true);
    refSpec = refSpec.setSourceDestination(Constants.R_HEADS + "*", dst + "/*"); //$NON-NLS-1$ //$NON-NLS-2$

    config.addFetchRefSpec(refSpec);
    config.update(git.getRepository().getConfig());
    git.getRepository().getConfig().save();

    // fetch all the remote branches,
    // create corresponding branches locally and merge them
    FetchCommand fetch = git.fetch();
    fetch.setRemote("origin"); //$NON-NLS-1$
    fetch.setTimeout(0);
    fetch.setRefSpecs(refSpec);
    fetch.call();
    // refresh after checkout
    project.refreshLocal(IResource.DEPTH_INFINITE, null);
}