Example usage for org.eclipse.jgit.api PullCommand call

List of usage examples for org.eclipse.jgit.api PullCommand call

Introduction

In this page you can find the example usage for org.eclipse.jgit.api PullCommand call.

Prototype

@Override
public PullResult call() throws GitAPIException, WrongRepositoryStateException, InvalidConfigurationException,
        InvalidRemoteException, CanceledException, RefNotFoundException, RefNotAdvertisedException,
        NoHeadException, org.eclipse.jgit.api.errors.TransportException 

Source Link

Document

Execute the Pull command with all the options and parameters collected by the setter methods (e.g.

Usage

From source file:com.bb.extensions.plugin.unittests.internal.git.GitWrapper.java

License:Open Source License

/**
 * @return performs a pull from origin/* ww  w  .j  a  v  a  2 s  . c  o  m*/
 */
public boolean pullMocks() {
    PullCommand pullCmd = git.pull();
    try {
        PullResult pullResult = pullCmd.call();
        return pullResult.isSuccessful();
    } catch (WrongRepositoryStateException e) {
        e.printStackTrace();
    } catch (InvalidConfigurationException e) {
        e.printStackTrace();
    } catch (DetachedHeadException e) {
        e.printStackTrace();
    } catch (InvalidRemoteException e) {
        e.printStackTrace();
    } catch (CanceledException e) {
        e.printStackTrace();
    } catch (RefNotFoundException e) {
        e.printStackTrace();
    } catch (NoHeadException e) {
        e.printStackTrace();
    } catch (TransportException e) {
        e.printStackTrace();
    } catch (GitAPIException e) {
        e.printStackTrace();
    }
    return false;
}

From source file:com.centurylink.mdw.dataaccess.file.VersionControlGit.java

License:Apache License

public void pull(String branch) throws Exception {
    PullCommand pull = git.pull().setRemote("origin").setRemoteBranchName(branch);
    if (credentialsProvider != null)
        pull.setCredentialsProvider(credentialsProvider);
    pull.call();
}

From source file:com.chungkwong.jgitgui.RemoteTreeItem.java

License:Open Source License

private void gitPull() {
    ProgressDialog progressDialog = new ProgressDialog(
            java.util.ResourceBundle.getBundle("com/chungkwong/jgitgui/text").getString("PULLING"));
    PullCommand command = ((Git) getParent().getValue()).pull().setRemote(((RemoteConfig) getValue()).getName())
            .setProgressMonitor(progressDialog);
    new Thread(() -> {
        try {/*from   w  w w  .j a  va2  s . com*/
            PullResult result = command.call();
            HashSet<CommitTreeItem> commits = new HashSet<>();
            Platform.runLater(() -> {
                if (result.getFetchResult() != null) {
                    for (Ref ref : result.getFetchResult().getAdvertisedRefs())
                        try {
                            commits.add(new CommitTreeItem(((Git) getParent().getValue()).log()
                                    .addRange(ref.getObjectId(), ref.getObjectId()).call().iterator().next()));
                        } catch (Exception ex) {
                            Logger.getLogger(RemoteTreeItem.class.getName()).log(Level.SEVERE, null, ex);
                            Util.informUser(ex);
                        }
                }
                if (result.getMergeResult() != null
                        && result.getMergeResult().getMergeStatus().equals(MergeResult.MergeStatus.MERGED)) {
                    try {
                        ObjectId head = result.getMergeResult().getNewHead();
                        commits.add(new CommitTreeItem(((Git) getParent().getValue()).log().addRange(head, head)
                                .call().iterator().next()));
                    } catch (Exception ex) {
                        Logger.getLogger(RemoteTreeItem.class.getName()).log(Level.SEVERE, null, ex);
                        Util.informUser(ex);
                    }
                } else {
                    new Alert(Alert.AlertType.INFORMATION, result.toString(), ButtonType.CLOSE).show();
                }
                getParent().getChildren().filtered(item -> item instanceof LocalTreeItem)
                        .forEach((item) -> item.getChildren().addAll(commits));
            });
        } catch (Exception ex) {
            Logger.getLogger(GitTreeItem.class.getName()).log(Level.SEVERE, null, ex);
            Platform.runLater(() -> {
                progressDialog.hide();
                Util.informUser(ex);
            });
        }
    }).start();
}

From source file:com.door43.translationstudio.tasks.PullTargetTranslationTask.java

private String pull(Repo repo, String remote) {
    Git git;// w  ww.j  a  va2s .co  m
    try {
        repo.deleteRemote("origin");
        repo.setRemote("origin", remote);
        git = repo.getGit();
    } catch (IOException e) {
        return null;
    }

    Manifest localManifest = Manifest.generate(this.targetTranslation.getPath());

    // TODO: we might want to get some progress feedback for the user
    PullCommand pullCommand = git.pull().setTransportConfigCallback(new TransportCallback()).setRemote("origin")
            .setStrategy(mergeStrategy).setRemoteBranchName("master").setProgressMonitor(new ProgressMonitor() {
                @Override
                public void start(int totalTasks) {

                }

                @Override
                public void beginTask(String title, int totalWork) {

                }

                @Override
                public void update(int completed) {

                }

                @Override
                public void endTask() {

                }

                @Override
                public boolean isCancelled() {
                    return false;
                }
            });
    try {
        PullResult result = pullCommand.call();
        MergeResult mergeResult = result.getMergeResult();
        if (mergeResult != null && mergeResult.getConflicts() != null
                && mergeResult.getConflicts().size() > 0) {
            this.status = Status.MERGE_CONFLICTS;
            this.conflicts = mergeResult.getConflicts();

            // revert manifest merge conflict to avoid corruption
            if (this.conflicts.containsKey("manifest.json")) {
                Logger.i("PullTargetTranslationTask", "Reverting to server manifest");
                try {
                    git.checkout().setStage(CheckoutCommand.Stage.THEIRS).addPath("manifest.json").call();
                    Manifest remoteManifest = Manifest.generate(this.targetTranslation.getPath());
                    localManifest = TargetTranslation.mergeManifests(localManifest, remoteManifest);
                } catch (CheckoutConflictException e) {
                    // failed to reset manifest.json
                    Logger.e(this.getClass().getName(), "Failed to reset manifest: " + e.getMessage(), e);
                } finally {
                    localManifest.save();
                }
            }

            // keep our license
            if (this.conflicts.containsKey("LICENSE.md")) {
                Logger.i("PullTargetTranslationTask", "Reverting to local license");
                try {
                    git.checkout().setStage(CheckoutCommand.Stage.OURS).addPath("LICENSE.md").call();
                } catch (CheckoutConflictException e) {
                    Logger.e(this.getClass().getName(), "Failed to reset license: " + e.getMessage(), e);
                }
            }
        } else {
            this.status = Status.UP_TO_DATE;
        }

        return "message";
    } catch (TransportException e) {
        Logger.e(this.getClass().getName(), e.getMessage(), e);
        Throwable cause = e.getCause();
        if (cause != null) {
            Throwable subException = cause.getCause();
            if (subException != null) {
                String detail = subException.getMessage();
                if ("Auth fail".equals(detail)) {
                    this.status = Status.AUTH_FAILURE; // we do special handling for auth failure
                }
            } else if (cause instanceof NoRemoteRepositoryException) {
                this.status = Status.NO_REMOTE_REPO;
            }
        }
        return null;
    } catch (Exception e) {
        Throwable cause = e.getCause();
        if (cause instanceof NoRemoteRepositoryException) {
            this.status = Status.NO_REMOTE_REPO;
        }
        Logger.e(this.getClass().getName(), e.getMessage(), e);
        return null;
    } catch (OutOfMemoryError e) {
        Logger.e(this.getClass().getName(), e.getMessage(), e);
        this.status = Status.OUT_OF_MEMORY;
        return null;
    } catch (Throwable e) {
        Logger.e(this.getClass().getName(), e.getMessage(), e);
        return null;
    }
}

From source file:com.rimerosolutions.ant.git.tasks.PullTask.java

License:Apache License

@Override
public void doExecute() {
    try {//from   ww w  . j a  v  a  2s.  com
        PullCommand pullCommand = git.pull().setRebase(rebase);

        if (getProgressMonitor() != null) {
            pullCommand.setProgressMonitor(getProgressMonitor());
        }

        setupCredentials(pullCommand);
        PullResult pullResult = pullCommand.call();

        if (!pullResult.isSuccessful()) {
            FetchResult fetchResult = pullResult.getFetchResult();
            GitTaskUtils.validateTrackingRefUpdates(MESSAGE_PULLED_FAILED, fetchResult.getTrackingRefUpdates());
            MergeStatus mergeStatus = pullResult.getMergeResult().getMergeStatus();

            if (!mergeStatus.isSuccessful()) {
                throw new BuildException(String.format(MESSAGE_PULLED_FAILED_WITH_STATUS, mergeStatus.name()));
            }
        }
    } catch (Exception e) {
        throw new GitBuildException(String.format(MESSAGE_PULLED_FAILED_WITH_URI, getUri()), e);
    }
}

From source file:com.romanenco.gitt.git.GitHelper.java

License:Open Source License

/**
 * Pull repo./*  w  w  w .  j  ava 2 s.  c  o m*/
 * 
 * @param localPath
 * @param user
 * @param password
 * @param pm
 * @throws GitError
 */
public static void pull(String localPath, String user, String password, ProgressMonitor pm) throws GitError {
    try {
        Git git = Git.open(new File(localPath));
        PullCommand pull = git.pull();
        pull.setProgressMonitor(pm);
        if ((user != null) && (password != null)) {
            UsernamePasswordCredentialsProvider access = new UsernamePasswordCredentialsProvider(user,
                    password);
            pull.setCredentialsProvider(access);
        }
        pull.call();
        return;
    } catch (DetachedHeadException e) {
        Log.e(TAG, "Detached head", e);
        GittApp.saveErrorTrace(e);
        throw new NoHeadError();
    } catch (InvalidRemoteException e) {
        Log.e(TAG, "InvalidRemote", e);
        GittApp.saveErrorTrace(e);
        throw new NotGitRepoError();
    } catch (TransportException e) {
        String trace = GittApp.saveErrorTrace(e);
        if (trace.indexOf("not authorized") != -1) {
            Log.e(TAG, "Auth", e);
            throw new AuthFailError();
        }
        Log.e(TAG, "Transport", e);
        throw new ConnectionError();
    } catch (GitAPIException e) {
        Log.e(TAG, "GitApi", e);
        GittApp.saveErrorTrace(e);
    } catch (IOException e) {
        Log.e(TAG, "IO", e);
        GittApp.saveErrorTrace(e);
    } catch (JGitInternalException e) {
        Log.e(TAG, "GitInternal", e);
        GittApp.saveErrorTrace(e);
        if (e.getCause() instanceof NotSupportedException) {
            throw new ConnectionError();
        }
    }
    throw new GitError();
}

From source file:com.sap.dirigible.ide.jgit.connector.JGitConnector.java

License:Open Source License

/**
 * /*w ww.  j  a  v  a2 s  .co m*/
 * Fetches from a remote repository and tries to merge into the current
 * branch.
 * 
 * @throws WrongRepositoryStateException
 * @throws InvalidConfigurationException
 * @throws DetachedHeadException
 * @throws InvalidRemoteException
 * @throws CanceledException
 * @throws RefNotFoundException
 * @throws NoHeadException
 * @throws TransportException
 * @throws GitAPIException
 */
public void pull() throws WrongRepositoryStateException, InvalidConfigurationException, DetachedHeadException,
        InvalidRemoteException, CanceledException, RefNotFoundException, NoHeadException, TransportException,
        GitAPIException {
    PullCommand pullCommand = git.pull();
    pullCommand.call();
}

From source file:com.searchcode.app.jobs.IndexGitRepoJob.java

private RepositoryChanged updateGitRepository(String repoName, String repoRemoteLocation, String repoUserName,
        String repoPassword, String repoLocations, String branch, boolean useCredentials) {
    boolean changed = false;
    List<String> changedFiles = new ArrayList<>();
    List<String> deletedFiles = new ArrayList<>();
    Singleton.getLogger().info("Attempting to pull latest from " + repoRemoteLocation + " for " + repoName);

    try {//  ww w  .  j a  va 2 s.co  m
        Repository localRepository = new FileRepository(new File(repoLocations + "/" + repoName + "/.git"));

        Ref head = localRepository.getRef("HEAD");

        Git git = new Git(localRepository);
        git.reset();
        git.clean();

        PullCommand pullCmd = git.pull();

        if (useCredentials) {
            pullCmd.setCredentialsProvider(new UsernamePasswordCredentialsProvider(repoUserName, repoPassword));
        }

        pullCmd.call();
        Ref newHEAD = localRepository.getRef("HEAD");

        if (!head.toString().equals(newHEAD.toString())) {
            changed = true;

            // Get the differences between the the heads which we updated at
            // and use these to just update the differences between them
            ObjectId oldHead = localRepository.resolve(head.getObjectId().getName() + "^{tree}");
            ObjectId newHead = localRepository.resolve(newHEAD.getObjectId().getName() + "^{tree}");

            ObjectReader reader = localRepository.newObjectReader();

            CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
            oldTreeIter.reset(reader, oldHead);

            CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
            newTreeIter.reset(reader, newHead);

            List<DiffEntry> entries = git.diff().setNewTree(newTreeIter).setOldTree(oldTreeIter).call();

            for (DiffEntry entry : entries) {
                if ("DELETE".equals(entry.getChangeType().name())) {
                    deletedFiles.add(FilenameUtils.separatorsToUnix(entry.getOldPath()));
                } else {
                    changedFiles.add(FilenameUtils.separatorsToUnix(entry.getNewPath()));
                }
            }
        }

    } catch (IOException | GitAPIException | InvalidPathException ex) {
        changed = false;
        Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass()
                + "\n with message: " + ex.getMessage());
    }

    return new RepositoryChanged(changed, changedFiles, deletedFiles);
}

From source file:com.searchcode.app.jobs.repository.IndexGitRepoJob.java

License:Open Source License

/**
 * Update a git repository and return if it has changed and the differences
 *//*from ww  w .  j  av a2 s . c o  m*/
public RepositoryChanged updateGitRepository(String repoName, String repoRemoteLocation, String repoUserName,
        String repoPassword, String repoLocations, String branch, boolean useCredentials) {
    boolean changed = false;
    List<String> changedFiles = new ArrayList<>();
    List<String> deletedFiles = new ArrayList<>();
    Singleton.getLogger().info("Attempting to pull latest from " + repoRemoteLocation + " for " + repoName);

    Repository localRepository = null;
    Git git = null;

    try {
        localRepository = new FileRepository(new File(repoLocations + "/" + repoName + "/.git"));

        Ref head = localRepository.getRef("HEAD");
        git = new Git(localRepository);

        git.reset();
        git.clean();

        PullCommand pullCmd = git.pull();

        if (useCredentials) {
            pullCmd.setCredentialsProvider(new UsernamePasswordCredentialsProvider(repoUserName, repoPassword));
        }

        pullCmd.call();
        Ref newHEAD = localRepository.getRef("HEAD");

        if (!head.toString().equals(newHEAD.toString())) {
            changed = true;

            // Get the differences between the the heads which we updated at
            // and use these to just update the differences between them
            ObjectId oldHead = localRepository.resolve(head.getObjectId().getName() + "^{tree}");
            ObjectId newHead = localRepository.resolve(newHEAD.getObjectId().getName() + "^{tree}");

            ObjectReader reader = localRepository.newObjectReader();

            CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
            oldTreeIter.reset(reader, oldHead);

            CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
            newTreeIter.reset(reader, newHead);

            List<DiffEntry> entries = git.diff().setNewTree(newTreeIter).setOldTree(oldTreeIter).call();

            for (DiffEntry entry : entries) {
                if ("DELETE".equals(entry.getChangeType().name())) {
                    deletedFiles.add(FilenameUtils.separatorsToUnix(entry.getOldPath()));
                } else {
                    changedFiles.add(FilenameUtils.separatorsToUnix(entry.getNewPath()));
                }
            }
        }

    } catch (IOException | GitAPIException | InvalidPathException ex) {
        changed = false;
        Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass()
                + " updateGitRepository for " + repoName + "\n with message: " + ex.getMessage());
    } finally {
        Singleton.getHelpers().closeQuietly(localRepository);
        Singleton.getHelpers().closeQuietly(git);
    }

    return new RepositoryChanged(changed, changedFiles, deletedFiles);
}

From source file:com.sillelien.dollar.plugins.pipe.GithubModuleResolver.java

License:Apache License

@NotNull
@Override/*  w  ww  . j  a  v  a2  s  . com*/
public <T> Pipeable resolve(@NotNull String uriWithoutScheme, @NotNull T scope) throws Exception {
    logger.debug(uriWithoutScheme);
    String[] githubRepo = uriWithoutScheme.split(":");
    GitHub github = GitHub.connect();
    final String githubUser = githubRepo[0];
    GHRepository repository = github.getUser(githubUser).getRepository(githubRepo[1]);
    final String branch = githubRepo[2].length() > 0 ? githubRepo[2] : "master";
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    final File dir = new File(BASE_PATH + "/" + githubUser + "/" + githubRepo[1] + "/" + branch);
    dir.mkdirs();

    final File gitDir = new File(dir, ".git");
    if (gitDir.exists()) {
        Repository localRepo = builder.setGitDir(gitDir).readEnvironment().findGitDir().build();
        Git git = new Git(localRepo);
        PullCommand pull = git.pull();
        pull.call();
    } else {
        Repository localRepo = builder.setGitDir(dir).readEnvironment().findGitDir().build();
        Git git = new Git(localRepo);
        CloneCommand clone = Git.cloneRepository();
        clone.setBranch(branch);
        clone.setBare(false);
        clone.setCloneAllBranches(false);
        clone.setDirectory(dir).setURI(repository.getGitTransportUrl());
        //        UsernamePasswordCredentialsProvider user = new UsernamePasswordCredentialsProvider(login, password);
        //        clone.setCredentialsProvider(user);
        clone.call();
    }
    final ClassLoader classLoader;
    String content;
    File mainFile;
    if (githubRepo.length == 4) {
        classLoader = getClass().getClassLoader();
        mainFile = new File(dir, githubRepo[3]);
        content = new String(Files.readAllBytes(mainFile.toPath()));
    } else {
        final File moduleFile = new File(dir, "module.json");
        var module = DollarStatic.$(new String(Files.readAllBytes(moduleFile.toPath())));
        mainFile = new File(dir, module.$("main").$S());
        content = new String(Files.readAllBytes(mainFile.toPath()));
        classLoader = DependencyRetriever.retrieve(
                module.$("dependencies").$list().stream().map(var::toString).collect(Collectors.toList()));
    }
    return (params) -> ((Scope) scope).getDollarParser().inScope(false, "github-module", ((Scope) scope),
            newScope -> {

                final ImmutableMap<var, var> paramMap = params[0].$map();
                for (Map.Entry<var, var> entry : paramMap.entrySet()) {
                    newScope.set(entry.getKey().$S(), entry.getValue(), true, null, null, false, false, false);
                }
                return new DollarParserImpl(((Scope) scope).getDollarParser().options(), classLoader, dir)
                        .parse(newScope, content);
            });
}