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:com.hazelcast.simulator.utils.jars.GitSupport.java

License:Open Source License

private void fetchAllRepositories(Git git) throws GitAPIException {
    Repository repository = git.getRepository();
    Set<String> remotes = repository.getRemoteNames();
    for (String remoteRepository : remotes) {
        git.fetch().setRemote(remoteRepository).call();
    }/*  w  w w .  j ava 2  s . c om*/
}

From source file:com.maiereni.sling.sources.git.GitProjectDownloader.java

License:Apache License

private void update(final Git git) throws Exception {
    logger.debug("Fetch from remote");
    FetchResult fr = git.fetch().call(); // .setRemote(url)
    Collection<Ref> refs = fr.getAdvertisedRefs();
    Iterable<RevCommit> logs = git.log().call();
    for (RevCommit rev : logs) {
        PersonIdent authorIdent = rev.getAuthorIdent();
        Date date = authorIdent.getWhen();
        String authName = authorIdent.getName();
        logger.debug("Commit at " + SDF.format(date) + " by " + authName + ": " + rev.getId().name() + " text: "
                + rev.getShortMessage());
    }/*from w  w w  .  j a  va 2  s. c  o m*/
    List<Note> notes = git.notesList().call();
    for (Ref ref : refs) {
        if (ref.getName().equals("HEAD")) {
            git.rebase().setUpstream(ref.getObjectId()).call();
            logger.debug("Rebase on HEAD");
            for (Note note : notes) {
                if (note.getName().equals(ref.getObjectId().getName())) {
                    logger.debug("Found note: " + note + " for commit " + ref.getName());
                    // displaying the contents of the note is done via a simple blob-read
                    ObjectLoader loader = git.getRepository().open(note.getData());
                    loader.copyTo(System.out);
                }
            }
        }
    }
}

From source file:com.maiereni.synchronizer.git.utils.GitDownloaderImpl.java

License:Apache License

private List<Change> update(final Git git, final GitProperties properties, final Ref localBranch,
        final Ref tagRef) throws Exception {
    logger.debug("Fetch from remote");
    List<Change> ret = null;
    FetchCommand cmd = git.fetch();
    if (StringUtils.isNotBlank(properties.getUserName()) && StringUtils.isNotBlank(properties.getPassword())) {
        logger.debug("Set credentials");
        cmd.setCredentialsProvider(//  w  w w .  ja  v a  2s.  co  m
                new UsernamePasswordCredentialsProvider(properties.getUserName(), properties.getPassword()));
    }
    if (tagRef != null) {
        RefSpec spec = new RefSpec().setSourceDestination(localBranch.getName(), tagRef.getName());
        List<RefSpec> specs = new ArrayList<RefSpec>();
        specs.add(spec);
        cmd.setRefSpecs(specs);
    }
    FetchResult fr = cmd.call();
    Collection<Ref> refs = fr.getAdvertisedRefs();
    for (Ref ref : refs) {
        if (ref.getName().equals("HEAD")) {
            ret = checkDifferences(git, localBranch, ref);
            logger.debug("Rebase on HEAD");
            RebaseResult rebaseResult = git.rebase().setUpstream(ref.getObjectId()).call();
            if (rebaseResult.getStatus().isSuccessful()) {

            }
        }
    }
    return ret;
}

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

License:Open Source License

@Override
public boolean fetch(final LocalRepoBean repoBean, final String remoteName) throws GitException {
    String remoteToPull = (remoteName != null) ? remoteName : "origin";

    FetchResult result;/* ww  w  . jav a  2s . com*/
    try {
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setGitDir(repoBean.getGitConfigDirectory().toFile()).findGitDir()
                .build();
        Git git = new org.eclipse.jgit.api.Git(repository);
        FetchCommand fetchCommand = git.fetch();
        fetchCommand.setRemote(remoteToPull);
        fetchCommand.setRefSpecs(new RefSpec("+refs/heads/*:refs/heads/*"));
        result = fetchCommand.call();
        repository.close();
    } catch (GitAPIException | IOException e) {
        LOGGER.error(e);
        throw new GitException(e);
    }

    boolean hadUpdates = !result.getTrackingRefUpdates().isEmpty();
    return hadUpdates;
}

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

License:Open Source License

private void doMirrorFetch(String projectId, File mirroredRepo) {
    try {//from   w  w  w . 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:de.blizzy.documentr.repository.ProjectRepositoryManager.java

License:Open Source License

ILockedRepository createBranchRepository(String branchName, String startingBranch)
        throws IOException, GitAPIException {
    Assert.hasLength(branchName);//  w w w . jav  a 2s.  c  o m
    if (startingBranch != null) {
        Assert.hasLength(startingBranch);
    }

    File repoDir = new File(reposDir, branchName);
    if (repoDir.isDirectory()) {
        throw new IllegalStateException("repository already exists: " + repoDir.getAbsolutePath()); //$NON-NLS-1$
    }

    List<String> branches = listBranches();
    if (branches.contains(branchName)) {
        throw new IllegalArgumentException("branch already exists: " + branchName); //$NON-NLS-1$
    }

    if ((startingBranch == null) && !branches.isEmpty()) {
        throw new IllegalArgumentException("must specify a starting branch"); //$NON-NLS-1$
    }

    ILock lock = lockManager.lockAll();
    try {
        Repository centralRepo = null;
        File centralRepoGitDir;
        try {
            centralRepo = getCentralRepositoryInternal(true);
            centralRepoGitDir = centralRepo.getDirectory();
        } finally {
            RepositoryUtil.closeQuietly(centralRepo);
            centralRepo = null;
        }

        Repository repo = null;
        try {
            repo = Git.cloneRepository().setURI(centralRepoGitDir.toURI().toString()).setDirectory(repoDir)
                    .call().getRepository();

            try {
                centralRepo = getCentralRepositoryInternal(true);
                if (!RepositoryUtils.getBranches(centralRepo).contains(branchName)) {
                    CreateBranchCommand createBranchCommand = Git.wrap(centralRepo).branchCreate();
                    if (startingBranch != null) {
                        createBranchCommand.setStartPoint(startingBranch);
                    }
                    createBranchCommand.setName(branchName).call();
                }
            } finally {
                RepositoryUtil.closeQuietly(centralRepo);
            }

            Git git = Git.wrap(repo);
            RefSpec refSpec = new RefSpec("refs/heads/" + branchName + ":refs/remotes/origin/" + branchName); //$NON-NLS-1$ //$NON-NLS-2$
            git.fetch().setRemote("origin").setRefSpecs(refSpec).call(); //$NON-NLS-1$
            git.branchCreate().setName(branchName).setStartPoint("origin/" + branchName).call(); //$NON-NLS-1$
            git.checkout().setName(branchName).call();
        } finally {
            RepositoryUtil.closeQuietly(repo);
        }
    } finally {
        lockManager.unlock(lock);
    }

    return getBranchRepository(branchName);
}

From source file:de.blizzy.documentr.repository.ProjectRepositoryManager.java

License:Open Source License

public void importSampleContents() throws IOException, GitAPIException {
    // TODO: synchronization is not quite correct here, but should be okay in this edge case
    if (listBranches().isEmpty()) {
        ILock lock = lockManager.lockAll();
        List<String> branches;
        try {//from   ww  w .  j a v a 2 s  .co m
            File gitDir = new File(centralRepoDir, ".git"); //$NON-NLS-1$
            FileUtils.forceDelete(gitDir);

            Git.cloneRepository().setURI(DocumentrConstants.SAMPLE_REPO_URL).setDirectory(gitDir).setBare(true)
                    .call();

            Repository centralRepo = null;
            File centralRepoGitDir;
            try {
                centralRepo = getCentralRepositoryInternal(true);
                centralRepoGitDir = centralRepo.getDirectory();
                StoredConfig config = centralRepo.getConfig();
                config.unsetSection("remote", "origin"); //$NON-NLS-1$ //$NON-NLS-2$
                config.unsetSection("branch", "master"); //$NON-NLS-1$ //$NON-NLS-2$
                config.save();
            } finally {
                RepositoryUtil.closeQuietly(centralRepo);
            }

            branches = listBranches();
            for (String branchName : branches) {
                File repoDir = new File(reposDir, branchName);
                Repository repo = null;
                try {
                    repo = Git.cloneRepository().setURI(centralRepoGitDir.toURI().toString())
                            .setDirectory(repoDir).call().getRepository();

                    Git git = Git.wrap(repo);
                    RefSpec refSpec = new RefSpec(
                            "refs/heads/" + branchName + ":refs/remotes/origin/" + branchName); //$NON-NLS-1$ //$NON-NLS-2$
                    git.fetch().setRemote("origin").setRefSpecs(refSpec).call(); //$NON-NLS-1$
                    git.branchCreate().setName(branchName).setStartPoint("origin/" + branchName).call(); //$NON-NLS-1$
                    git.checkout().setName(branchName).call();
                } finally {
                    RepositoryUtil.closeQuietly(repo);
                }
            }
        } finally {
            lockManager.unlock(lock);
        }

        for (String branch : branches) {
            eventBus.post(new BranchCreatedEvent(projectName, branch));
        }
    }
}

From source file:de._692b8c32.cdlauncher.tasks.GITUpdateTask.java

License:Open Source License

@Override
public void doWork() {
    try {/*w w w.  ja  v  a 2s . co m*/
        Git git;
        if (!cacheDir.exists()) {
            cacheDir.mkdirs();
            git = Git.cloneRepository().setURI(repoUri).setDirectory(cacheDir).setNoCheckout(true)
                    .setProgressMonitor(this).call();
        } else {
            git = Git.open(cacheDir);
            git.fetch().setProgressMonitor(this).call();
        }
        git.close();
    } catch (RepositoryNotFoundException | InvalidRemoteException ex) {
        Logger.getLogger(GITUpdateTask.class.getName()).log(Level.SEVERE, "Could not find repository", ex);
        try {
            FileUtils.delete(cacheDir);
            run();
        } catch (IOException | StackOverflowError ex1) {
            throw new RuntimeException("Fix of broken repository failed", ex1);
        }
    } catch (GitAPIException | IOException ex) {
        throw new RuntimeException("Could not download data", ex);
    }
}

From source file:fi.otavanopisto.changelogger.Changelogger.java

private static void prependLine(String line, String message) throws IOException, GitAPIException {
    FileRepositoryBuilder frBuilder = new FileRepositoryBuilder();
    Repository repository = frBuilder.setGitDir(new File("./.git")).readEnvironment().build();
    Git git = new Git(repository);

    git.reset().setMode(ResetCommand.ResetType.HARD).call();
    git.clean().call();//from w  w  w.  j  ava 2 s  .  c o  m
    git.fetch().call();
    git.pull().call();

    File file = new File(CHANGELOG_FILE);
    List<String> lines = FileUtils.readLines(file, Charsets.UTF_8);
    lines.add(0, line);
    FileUtils.writeLines(file, lines);

    git.commit().setMessage(message).setAuthor("Changelogger", "changelogger@otavanopisto.fi").call();

    git.push().call();
}

From source file:fi.otavanopisto.santra.Santra.java

License:Open Source License

private void reload(String botName) throws IOException, GitAPIException {
    log.info("Starting bot reload");
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository repository = builder.setGitDir(new File(arguments.getBasePath() + "/.git")).readEnvironment()
            .build();//from   ww w .j a v  a 2  s. c o m
    log.info("Starting repository update");
    Git git = new Git(repository);
    git.reset().setMode(ResetCommand.ResetType.HARD).call();
    log.info("Reset complete");
    git.clean().call();
    log.info("Clean compete");
    git.fetch().call();
    log.info("Fetch complete");
    git.pull().call();
    log.info("Repository update finished");

    initBot(botName);
    log.info("Bot reloaded");
}