Search in sources :

Example 1 with PullCommand

use of org.eclipse.jgit.api.PullCommand in project MGit by maks.

the class PullTask method pullRepo.

public boolean pullRepo() {
    Git git;
    try {
        git = mRepo.getGit();
    } catch (StopTaskException e) {
        return false;
    }
    PullCommand pullCommand = git.pull().setRemote(mRemote).setProgressMonitor(new BasicProgressMonitor()).setTransportConfigCallback(new SgitTransportCallback());
    setCredentials(pullCommand);
    try {
        String branch = null;
        if (mForcePull) {
            branch = git.getRepository().getFullBranch();
            if (!branch.startsWith("refs/heads/")) {
                setException(new GitAPIException("not on branch") {
                }, R.string.error_pull_failed_not_on_branch);
                return false;
            }
            branch = branch.substring(11);
            BasicProgressMonitor bpm = new BasicProgressMonitor();
            bpm.beginTask("clearing repo state", 3);
            git.getRepository().writeMergeCommitMsg(null);
            git.getRepository().writeMergeHeads(null);
            bpm.update(1);
            try {
                git.rebase().setOperation(RebaseCommand.Operation.ABORT).call();
            } catch (Exception e) {
            }
            bpm.update(2);
            git.reset().setMode(ResetCommand.ResetType.HARD).setRef("HEAD").call();
            bpm.endTask();
        }
        pullCommand.call();
        if (mForcePull) {
            BasicProgressMonitor bpm = new BasicProgressMonitor();
            bpm.beginTask("resetting to " + mRemote + "/" + branch, 1);
            git.reset().setMode(ResetCommand.ResetType.HARD).setRef(mRemote + "/" + branch).call();
            bpm.endTask();
        }
    } catch (TransportException e) {
        setException(e);
        handleAuthError(this);
        return false;
    } catch (Exception e) {
        setException(e, R.string.error_pull_failed);
        return false;
    } catch (OutOfMemoryError e) {
        setException(e, R.string.error_out_of_memory);
        return false;
    } catch (Throwable e) {
        setException(e);
        return false;
    }
    mRepo.updateLatestCommitInfo();
    return true;
}
Also used : GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) PullCommand(org.eclipse.jgit.api.PullCommand) SgitTransportCallback(me.sheimi.sgit.ssh.SgitTransportCallback) Git(org.eclipse.jgit.api.Git) StopTaskException(me.sheimi.sgit.exception.StopTaskException) TransportException(org.eclipse.jgit.api.errors.TransportException) TransportException(org.eclipse.jgit.api.errors.TransportException) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) StopTaskException(me.sheimi.sgit.exception.StopTaskException)

Example 2 with PullCommand

use of org.eclipse.jgit.api.PullCommand in project egit by eclipse.

the class PullOperation method execute.

@Override
public void execute(IProgressMonitor m) throws CoreException {
    if (!results.isEmpty())
        throw new CoreException(new Status(IStatus.ERROR, Activator.getPluginId(), CoreText.OperationAlreadyExecuted));
    SubMonitor totalProgress = SubMonitor.convert(m, NLS.bind(CoreText.PullOperation_TaskName, Integer.valueOf(repositories.length)), 1);
    IWorkspaceRunnable action = new IWorkspaceRunnable() {

        @Override
        public void run(IProgressMonitor mymonitor) throws CoreException {
            if (mymonitor.isCanceled())
                throw new CoreException(Status.CANCEL_STATUS);
            SubMonitor progress = SubMonitor.convert(mymonitor, repositories.length * 2);
            for (int i = 0; i < repositories.length; i++) {
                Repository repository = repositories[i];
                IProject[] validProjects = ProjectUtil.getValidOpenProjects(repository);
                PullResult pullResult = null;
                try (Git git = new Git(repository)) {
                    PullCommand pull = git.pull();
                    SubMonitor newChild = progress.newChild(1, SubMonitor.SUPPRESS_NONE);
                    pull.setProgressMonitor(new EclipseGitProgressTransformer(newChild));
                    pull.setTimeout(timeout);
                    pull.setCredentialsProvider(credentialsProvider);
                    PullReferenceConfig config = configs.get(repository);
                    newChild.setTaskName(getPullTaskName(repository, config));
                    if (config != null) {
                        if (config.getRemote() != null) {
                            pull.setRemote(config.getRemote());
                        }
                        if (config.getReference() != null) {
                            pull.setRemoteBranchName(config.getReference());
                        }
                        pull.setRebase(config.getUpstreamConfig());
                    }
                    MergeStrategy strategy = Activator.getDefault().getPreferredMergeStrategy();
                    if (strategy != null) {
                        pull.setStrategy(strategy);
                    }
                    pullResult = pull.call();
                    results.put(repository, pullResult);
                } catch (DetachedHeadException e) {
                    results.put(repository, Activator.error(CoreText.PullOperation_DetachedHeadMessage, e));
                } catch (InvalidConfigurationException e) {
                    IStatus error = Activator.error(CoreText.PullOperation_PullNotConfiguredMessage, e);
                    results.put(repository, error);
                } catch (GitAPIException e) {
                    results.put(repository, Activator.error(e.getMessage(), e));
                } catch (JGitInternalException e) {
                    Throwable cause = e.getCause();
                    if (cause == null || !(cause instanceof TransportException))
                        cause = e;
                    results.put(repository, Activator.error(cause.getMessage(), cause));
                } finally {
                    if (refreshNeeded(pullResult)) {
                        ProjectUtil.refreshValidProjects(validProjects, progress.newChild(1, SubMonitor.SUPPRESS_NONE));
                    } else {
                        progress.worked(1);
                    }
                }
            }
        }
    };
    // lock workspace to protect working tree changes
    ResourcesPlugin.getWorkspace().run(action, getSchedulingRule(), IWorkspace.AVOID_UPDATE, totalProgress);
}
Also used : IStatus(org.eclipse.core.runtime.IStatus) MergeStatus(org.eclipse.jgit.api.MergeResult.MergeStatus) Status(org.eclipse.core.runtime.Status) IWorkspaceRunnable(org.eclipse.core.resources.IWorkspaceRunnable) PullCommand(org.eclipse.jgit.api.PullCommand) IStatus(org.eclipse.core.runtime.IStatus) MergeStrategy(org.eclipse.jgit.merge.MergeStrategy) SubMonitor(org.eclipse.core.runtime.SubMonitor) EclipseGitProgressTransformer(org.eclipse.egit.core.EclipseGitProgressTransformer) TransportException(org.eclipse.jgit.errors.TransportException) IProject(org.eclipse.core.resources.IProject) PullResult(org.eclipse.jgit.api.PullResult) InvalidConfigurationException(org.eclipse.jgit.api.errors.InvalidConfigurationException) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) Repository(org.eclipse.jgit.lib.Repository) Git(org.eclipse.jgit.api.Git) CoreException(org.eclipse.core.runtime.CoreException) JGitInternalException(org.eclipse.jgit.api.errors.JGitInternalException) DetachedHeadException(org.eclipse.jgit.api.errors.DetachedHeadException)

Example 3 with PullCommand

use of org.eclipse.jgit.api.PullCommand in project searchcode-server by boyter.

the class IndexGitRepoJob method updateGitRepository.

/**
 * Update a git repository and return if it has changed and the differences
 */
public RepositoryChanged updateGitRepository(RepoResult repoResult, String repoLocations, boolean useCredentials) {
    boolean changed = false;
    List<String> changedFiles = new ArrayList<>();
    List<String> deletedFiles = new ArrayList<>();
    this.logger.info(String.format("6cffea0f::attempting to pull latest from %s for %s", repoLocations, repoResult.getName()));
    Repository localRepository = null;
    Git git = null;
    try {
        localRepository = new FileRepository(new File(repoLocations + "/" + repoResult.getDirectoryName() + "/.git"));
        Ref head = localRepository.getRef("HEAD");
        git = new Git(localRepository);
        git.reset();
        git.clean();
        PullCommand pullCmd = git.pull();
        if (useCredentials) {
            pullCmd.setCredentialsProvider(new UsernamePasswordCredentialsProvider(repoResult.getUsername(), repoResult.getPassword()));
        }
        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;
        String error = String.format("c6646806::error in class %s exception %s repository %s", ex.getClass(), ex.getMessage(), repoResult.getName());
        this.logger.severe(error);
        repoResult.getData().indexError = error;
        Singleton.getRepo().saveRepo(repoResult);
    } finally {
        Singleton.getHelpers().closeQuietly(localRepository);
        Singleton.getHelpers().closeQuietly(git);
    }
    return new RepositoryChanged(changed, changedFiles, deletedFiles);
}
Also used : FileRepository(org.eclipse.jgit.internal.storage.file.FileRepository) PullCommand(org.eclipse.jgit.api.PullCommand) UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) ArrayList(java.util.ArrayList) CanonicalTreeParser(org.eclipse.jgit.treewalk.CanonicalTreeParser) InvalidPathException(java.nio.file.InvalidPathException) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) RepositoryChanged(com.searchcode.app.dto.RepositoryChanged) FileRepository(org.eclipse.jgit.internal.storage.file.FileRepository) Git(org.eclipse.jgit.api.Git) DiffEntry(org.eclipse.jgit.diff.DiffEntry)

Example 4 with PullCommand

use of org.eclipse.jgit.api.PullCommand in project kie-wb-common by kiegroup.

the class KieDefaultMavenCompilerTest method buildWithPullRebaseUberfireTest.

@Test
public void buildWithPullRebaseUberfireTest() throws Exception {
    // Setup origin in memory
    final URI originRepo = URI.create("git://repo");
    final JGitFileSystem origin = (JGitFileSystem) ioService.newFileSystem(originRepo, new HashMap<String, Object>() {

        {
            put("init", Boolean.TRUE);
            put("internal", Boolean.TRUE);
            put("listMode", "ALL");
        }
    });
    ioService.startBatch(origin);
    ioService.write(origin.getPath("/pom.xml"), new String(java.nio.file.Files.readAllBytes(new File("src/test/projects/dummy_multimodule_untouched/pom.xml").toPath())));
    ioService.write(origin.getPath("/dummyA/src/main/java/dummy/DummyA.java"), new String(java.nio.file.Files.readAllBytes(new File("src/test/projects/dummy_multimodule_untouched/dummyA/src/main/java/dummy/DummyA.java").toPath())));
    ioService.write(origin.getPath("/dummyB/src/main/java/dummy/DummyB.java"), new String(java.nio.file.Files.readAllBytes(new File("src/test/projects/dummy_multimodule_untouched/dummyB/src/main/java/dummy/DummyB.java").toPath())));
    ioService.write(origin.getPath("/dummyA/pom.xml"), new String(java.nio.file.Files.readAllBytes(new File("src/test/projects/dummy_multimodule_untouched/dummyA/pom.xml").toPath())));
    ioService.write(origin.getPath("/dummyB/pom.xml"), new String(java.nio.file.Files.readAllBytes(new File("src/test/projects/dummy_multimodule_untouched/dummyB/pom.xml").toPath())));
    ioService.endBatch();
    // clone into a regularfs
    Path tmpRootCloned = Files.createTempDirectory("cloned");
    Path tmpCloned = Files.createDirectories(Paths.get(tmpRootCloned.toString(), ".clone"));
    final Git cloned = Git.cloneRepository().setURI(origin.getGit().getRepository().getDirectory().toURI().toString()).setBare(false).setDirectory(tmpCloned.toFile()).call();
    assertThat(cloned).isNotNull();
    PullCommand pc = cloned.pull().setRemote("origin").setRebase(Boolean.TRUE);
    PullResult pullRes = pc.call();
    // nothing changed yet
    assertThat(pullRes.getRebaseResult().getStatus()).isEqualTo(RebaseResult.Status.UP_TO_DATE);
    RebaseCommand rb = cloned.rebase().setUpstream("origin/master");
    RebaseResult rbResult = rb.setPreserveMerges(true).call();
    assertThat(rbResult.getStatus().isSuccessful()).isTrue();
    // Compile the repo
    byte[] encoded = Files.readAllBytes(Paths.get(tmpCloned + "/pom.xml"));
    String pomAsAstring = new String(encoded, StandardCharsets.UTF_8);
    assertThat(pomAsAstring).doesNotContain(TestConstants.TAKARI_LIFECYCLE_ARTIFACT);
    Path prjFolder = Paths.get(tmpCloned + "/");
    final AFCompiler compiler = KieMavenCompilerFactory.getCompiler(EnumSet.of(KieDecorator.ENABLE_LOGGING, KieDecorator.ENABLE_INCREMENTAL_BUILD));
    WorkspaceCompilationInfo info = new WorkspaceCompilationInfo(prjFolder);
    CompilationRequest req = new DefaultCompilationRequest(mavenRepoPath, info, new String[] { MavenCLIArgs.COMPILE }, Boolean.TRUE);
    CompilationResponse res = compiler.compile(req);
    TestUtil.saveMavenLogIfCompilationResponseNotSuccessfull(tmpCloned, res, this.getClass(), testName);
    assertThat(res.isSuccessful()).isTrue();
    Path incrementalConfiguration = Paths.get(prjFolder + TestConstants.TARGET_TAKARI_PLUGIN);
    assertThat(incrementalConfiguration.toFile()).exists();
    encoded = Files.readAllBytes(Paths.get(prjFolder + "/pom.xml"));
    pomAsAstring = new String(encoded, StandardCharsets.UTF_8);
    assertThat(pomAsAstring).contains(TestConstants.KIE_TAKARI_LIFECYCLE_ARTIFACT);
    TestUtil.rm(tmpRootCloned.toFile());
}
Also used : Path(org.uberfire.java.nio.file.Path) PullCommand(org.eclipse.jgit.api.PullCommand) HashMap(java.util.HashMap) RebaseCommand(org.eclipse.jgit.api.RebaseCommand) CompilationResponse(org.kie.workbench.common.services.backend.compiler.CompilationResponse) URI(java.net.URI) PullResult(org.eclipse.jgit.api.PullResult) TestUtilGit(org.kie.workbench.common.services.backend.compiler.TestUtilGit) Git(org.eclipse.jgit.api.Git) WorkspaceCompilationInfo(org.kie.workbench.common.services.backend.compiler.impl.WorkspaceCompilationInfo) DefaultCompilationRequest(org.kie.workbench.common.services.backend.compiler.impl.DefaultCompilationRequest) File(java.io.File) RebaseResult(org.eclipse.jgit.api.RebaseResult) JGitFileSystem(org.uberfire.java.nio.fs.jgit.JGitFileSystem) AFCompiler(org.kie.workbench.common.services.backend.compiler.AFCompiler) CompilationRequest(org.kie.workbench.common.services.backend.compiler.CompilationRequest) DefaultCompilationRequest(org.kie.workbench.common.services.backend.compiler.impl.DefaultCompilationRequest) Test(org.junit.Test)

Example 5 with PullCommand

use of org.eclipse.jgit.api.PullCommand in project searchcode-server by boyter.

the class IndexGitRepoJob method updateGitRepository.

/**
     * Update a git repository and return if it has changed and the differences
     */
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);
}
Also used : FileRepository(org.eclipse.jgit.internal.storage.file.FileRepository) PullCommand(org.eclipse.jgit.api.PullCommand) UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) ArrayList(java.util.ArrayList) CanonicalTreeParser(org.eclipse.jgit.treewalk.CanonicalTreeParser) InvalidPathException(java.nio.file.InvalidPathException) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) RepositoryChanged(com.searchcode.app.dto.RepositoryChanged) FileRepository(org.eclipse.jgit.internal.storage.file.FileRepository) Git(org.eclipse.jgit.api.Git) DiffEntry(org.eclipse.jgit.diff.DiffEntry)

Aggregations

PullCommand (org.eclipse.jgit.api.PullCommand)14 Git (org.eclipse.jgit.api.Git)12 PullResult (org.eclipse.jgit.api.PullResult)7 RebaseResult (org.eclipse.jgit.api.RebaseResult)6 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)6 File (java.io.File)5 HashMap (java.util.HashMap)5 RebaseCommand (org.eclipse.jgit.api.RebaseCommand)5 UsernamePasswordCredentialsProvider (org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider)5 Test (org.junit.Test)5 URI (java.net.URI)4 Path (org.uberfire.java.nio.file.Path)4 JGitFileSystem (org.uberfire.java.nio.fs.jgit.JGitFileSystem)4 CompilationResponse (org.kie.workbench.common.services.backend.compiler.CompilationResponse)3 RepositoryChanged (com.searchcode.app.dto.RepositoryChanged)2 InvalidPathException (java.nio.file.InvalidPathException)2 ArrayList (java.util.ArrayList)2 DiffEntry (org.eclipse.jgit.diff.DiffEntry)2 FileRepository (org.eclipse.jgit.internal.storage.file.FileRepository)2 CanonicalTreeParser (org.eclipse.jgit.treewalk.CanonicalTreeParser)2