Search in sources :

Example 1 with RevertCommand

use of org.eclipse.jgit.api.RevertCommand in project archi-modelrepository-plugin by archi-contribs.

the class RevertCommitAction method doRevertCommand.

/**
 * @throws IOException
 */
protected RevertCommand doRevertCommand(Git git) throws GitAPIException, IOException {
    RevertCommand revertCommand = git.revert();
    revertCommand.include(fCommit);
    revertCommand.call();
    return revertCommand;
}
Also used : RevertCommand(org.eclipse.jgit.api.RevertCommand)

Example 2 with RevertCommand

use of org.eclipse.jgit.api.RevertCommand in project archi-modelrepository-plugin by archi-contribs.

the class RevertCommitAction method run.

@Override
public void run() {
    // Offer to save the model if open and dirty
    // We need to do this to keep grafico and temp files in sync
    IArchimateModel model = getRepository().locateModel();
    if (model != null && IEditorModelManager.INSTANCE.isModelDirty(model)) {
        if (!offerToSaveModel(model)) {
            return;
        }
    }
    // Do the Grafico Export first
    try {
        getRepository().exportModelToGraficoFiles();
    } catch (IOException ex) {
        displayErrorDialog(Messages.RevertCommitAction_0, ex);
        return;
    }
    // Then offer to Commit
    try {
        if (getRepository().hasChangesToCommit()) {
            if (!offerToCommitChanges()) {
                return;
            }
        }
    } catch (IOException | GitAPIException ex) {
        displayErrorDialog(Messages.RevertCommitAction_3, ex);
        return;
    }
    // Revert
    try (Git git = Git.open(getRepository().getLocalRepositoryFolder())) {
        RevertCommand revertCommand = doRevertCommand(git);
        MergeResult failingResult = revertCommand.getFailingResult();
        if (failingResult != null) {
            MergeConflictHandler handler = new MergeConflictHandler(failingResult, getRepository(), fWindow.getShell());
            boolean result = handler.checkForMergeConflicts();
            if (result) {
                handler.mergeAndCommit(Messages.RevertCommitAction_4, false);
            } else {
                // User cancelled - we assume user has committed all changes so we can reset
                handler.resetToLocalState();
            }
        } else {
            new GraficoModelLoader(getRepository()).loadModel();
        }
        // Save the checksum
        getRepository().saveChecksum();
        notifyChangeListeners(IRepositoryListener.HISTORY_CHANGED);
    } catch (IOException | GitAPIException ex) {
        displayErrorDialog(Messages.RevertCommitAction_1, ex);
    }
}
Also used : GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) Git(org.eclipse.jgit.api.Git) GraficoModelLoader(org.archicontribs.modelrepository.grafico.GraficoModelLoader) RevertCommand(org.eclipse.jgit.api.RevertCommand) MergeResult(org.eclipse.jgit.api.MergeResult) IOException(java.io.IOException) MergeConflictHandler(org.archicontribs.modelrepository.grafico.MergeConflictHandler) IArchimateModel(com.archimatetool.model.IArchimateModel)

Example 3 with RevertCommand

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

the class RevertCommitOperation method execute.

@Override
public void execute(IProgressMonitor m) throws CoreException {
    IWorkspaceRunnable action = new IWorkspaceRunnable() {

        @Override
        public void run(IProgressMonitor pm) throws CoreException {
            SubMonitor progress = SubMonitor.convert(pm, 2);
            progress.subTask(MessageFormat.format(CoreText.RevertCommitOperation_reverting, Integer.valueOf(commits.size())));
            try (Git git = new Git(repo)) {
                RevertCommand command = git.revert();
                MergeStrategy strategy = Activator.getDefault().getPreferredMergeStrategy();
                if (strategy != null) {
                    command.setStrategy(strategy);
                }
                for (RevCommit commit : commits) {
                    command.include(commit);
                }
                newHead = command.call();
                reverted = command.getRevertedRefs();
                result = command.getFailingResult();
                progress.worked(1);
                ProjectUtil.refreshValidProjects(ProjectUtil.getValidOpenProjects(repo), progress.newChild(1));
            } catch (GitAPIException e) {
                throw new TeamException(e.getLocalizedMessage(), e.getCause());
            }
        }
    };
    ResourcesPlugin.getWorkspace().run(action, getSchedulingRule(), IWorkspace.AVOID_UPDATE, m);
}
Also used : GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) IWorkspaceRunnable(org.eclipse.core.resources.IWorkspaceRunnable) TeamException(org.eclipse.team.core.TeamException) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) Git(org.eclipse.jgit.api.Git) RevertCommand(org.eclipse.jgit.api.RevertCommand) MergeStrategy(org.eclipse.jgit.merge.MergeStrategy) SubMonitor(org.eclipse.core.runtime.SubMonitor) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 4 with RevertCommand

use of org.eclipse.jgit.api.RevertCommand in project fabric8 by jboss-fuse.

the class GitPatchManagementServiceImpl method rollback.

@Override
public void rollback(PatchData patchData) {
    Git fork = null;
    try {
        fork = gitPatchRepository.cloneRepository(gitPatchRepository.findOrCreateMainGitRepository(), true);
        Ref installationBranch = null;
        PatchKind kind = patchData.isRollupPatch() ? PatchKind.ROLLUP : PatchKind.NON_ROLLUP;
        switch(kind) {
            case ROLLUP:
                {
                    Activator.log2(LogService.LOG_INFO, String.format("Rolling back rollup patch \"%s\"", patchData.getId()));
                    // rolling back a rollup patch should rebase all user commits on top of current baseline
                    // to previous baseline
                    RevTag currentBaseline = gitPatchRepository.findCurrentBaseline(fork);
                    RevCommit c1 = new RevWalk(fork.getRepository()).parseCommit(fork.getRepository().resolve(currentBaseline.getTagName() + "^{commit}"));
                    // remember the commit to discover P patch tags installed on top of rolledback baseline
                    RevCommit since = c1;
                    RevCommit c2 = new RevWalk(fork.getRepository()).parseCommit(fork.getRepository().resolve("HEAD"));
                    RevCommit to = c2;
                    Iterable<RevCommit> mainChangesSinceRollupPatch = fork.log().addRange(c1, c2).call();
                    List<RevCommit> userChanges = new LinkedList<>();
                    for (RevCommit rc : mainChangesSinceRollupPatch) {
                        if (isUserChangeCommit(rc)) {
                            userChanges.add(rc);
                        }
                    }
                    if (env == EnvType.STANDALONE) {
                        // remove the tag
                        fork.tagDelete().setTags(currentBaseline.getTagName()).call();
                    }
                    // baselines are stacked on each other
                    RevTag previousBaseline = gitPatchRepository.findNthPreviousBaseline(fork, env == EnvType.STANDALONE ? 0 : 1);
                    c1 = new RevWalk(fork.getRepository()).parseCommit(fork.getRepository().resolve(previousBaseline.getTagName() + "^{commit}"));
                    // hard reset of main patch branch - to point to other branch, originating from previous baseline
                    fork.reset().setMode(ResetCommand.ResetType.HARD).setRef(previousBaseline.getTagName() + "^{commit}").call();
                    // reapply those user changes that are not conflicting
                    ListIterator<RevCommit> it = userChanges.listIterator(userChanges.size());
                    Status status = fork.status().call();
                    if (!status.isClean()) {
                        // unstage any garbage
                        fork.reset().setMode(ResetCommand.ResetType.MIXED).call();
                        for (String p : status.getModified()) {
                            gitPatchRepository.checkout(fork).addPath(p).call();
                        }
                    }
                    while (it.hasPrevious()) {
                        RevCommit userChange = it.previous();
                        CherryPickResult cpr = fork.cherryPick().include(userChange.getId()).setNoCommit(true).call();
                        // this time prefer user change on top of previous baseline - this change shouldn't be
                        // conflicting, because when rolling back, patch change was preferred over user change
                        handleCherryPickConflict(patchData.getPatchDirectory(), fork, cpr, userChange, true, PatchKind.ROLLUP, null, false, true);
                        // restore backed up content from the reapplied user change
                        String[] commitMessage = userChange.getFullMessage().split("\n\n");
                        if (commitMessage.length > 1) {
                            // we have original commit (that had conflicts) stored in this commit's full message
                            String ref = commitMessage[commitMessage.length - 1];
                            File backupDir = new File(patchesDir, patchData.getId() + ".backup");
                            if (isStandaloneChild()) {
                                backupDir = new File(patchesDir, patchData.getId() + "." + System.getProperty("karaf.name") + ".backup");
                            }
                            backupDir = new File(backupDir, ref);
                            if (backupDir.exists() && backupDir.isDirectory()) {
                                Activator.log2(LogService.LOG_DEBUG, String.format("Restoring content of %s", backupDir.getCanonicalPath()));
                                copyManagedDirectories(backupDir, karafBase, false, false, false);
                            }
                        }
                        gitPatchRepository.prepareCommit(fork, userChange.getFullMessage()).call();
                    }
                    gitPatchRepository.push(fork);
                    if (env == EnvType.STANDALONE) {
                        // remove remote tag
                        fork.push().setRefSpecs(new RefSpec().setSource(null).setDestination("refs/tags/" + currentBaseline.getTagName())).call();
                    }
                    // remove tags related to non-rollup patches installed between
                    // rolled back baseline and previous HEAD, because rolling back to previous rollup patch
                    // (previous baseline) equal effectively to starting from fresh baseline
                    RevWalk walk = new RevWalk(fork.getRepository());
                    Map<String, RevTag> tags = gitPatchRepository.findTagsBetween(fork, since, to);
                    for (Map.Entry<String, RevTag> entry : tags.entrySet()) {
                        if (entry.getKey().startsWith("patch-")) {
                            fork.tagDelete().setTags(entry.getKey()).call();
                            fork.push().setRefSpecs(new RefSpec().setSource(null).setDestination("refs/tags/" + entry.getKey())).call();
                        }
                    }
                    // HEAD of main patch branch after reset and cherry-picks
                    c2 = new RevWalk(fork.getRepository()).parseCommit(fork.getRepository().resolve("HEAD"));
                    // applyChanges(fork, c1, c2);
                    applyChanges(fork, false);
                    break;
                }
            case NON_ROLLUP:
                {
                    Activator.log2(LogService.LOG_INFO, String.format("Rolling back non-rollup patch \"%s\"", patchData.getId()));
                    // rolling back a non-rollup patch is a revert of the patch commit and removal of patch tag
                    String patchTagName = String.format("patch-%s", env == EnvType.STANDALONE ? patchData.getId() : patchData.getId() + "-" + gitPatchRepository.getStandaloneChildkarafName());
                    ObjectId oid = fork.getRepository().resolve(patchTagName);
                    if (oid == null) {
                        throw new PatchException(String.format("Can't find installed patch (tag %s is missing)", patchTagName));
                    }
                    RevCommit commit = new RevWalk(fork.getRepository()).parseCommit(oid);
                    RevertCommand revertCommand = fork.revert().include(commit);
                    RevCommit reverted = revertCommand.call();
                    if (reverted == null) {
                        List<String> unmerged = revertCommand.getUnmergedPaths();
                        Activator.log2(LogService.LOG_WARNING, "Problem rolling back patch \"" + patchData.getId() + "\". The following files where updated later:");
                        for (String path : unmerged) {
                            Activator.log2(LogService.LOG_WARNING, " - " + path);
                        }
                        RevWalk walk = new RevWalk(fork.getRepository());
                        RevCommit head = walk.parseCommit(fork.getRepository().resolve("HEAD"));
                        Map<String, RevTag> tags = gitPatchRepository.findTagsBetween(fork, commit, head);
                        List<RevTag> laterPatches = new LinkedList<>();
                        if (tags.size() > 0) {
                            for (Map.Entry<String, RevTag> tag : tags.entrySet()) {
                                if (tag.getKey().startsWith("patch-")) {
                                    laterPatches.add(tag.getValue());
                                }
                            }
                            Activator.log2(LogService.LOG_INFO, "The following patches were installed after \"" + patchData.getId() + "\":");
                            for (RevTag t : laterPatches) {
                                String message = " - " + t.getTagName().substring("patch-".length());
                                RevObject object = walk.peel(t);
                                if (object != null) {
                                    RevCommit c = walk.parseCommit(object.getId());
                                    String date = GitPatchRepository.FULL_DATE.format(new Date(c.getCommitTime() * 1000L));
                                    message += " (" + date + ")";
                                }
                                Activator.log2(LogService.LOG_INFO, message);
                            }
                        }
                        return;
                    }
                    // TODO: should we restore the backup possibly created when instalilng P patch?
                    // remove the tag
                    fork.tagDelete().setTags(patchTagName).call();
                    gitPatchRepository.push(fork);
                    // remove remote tag
                    fork.push().setRefSpecs(new RefSpec().setSource(null).setDestination(String.format("refs/tags/%s", patchTagName))).call();
                    // HEAD of main patch branch after reset and cherry-picks
                    RevCommit c = new RevWalk(fork.getRepository()).parseCommit(fork.getRepository().resolve("HEAD"));
                    applyChanges(fork, c.getParent(0), c);
                    break;
                }
        }
    } catch (IOException | GitAPIException e) {
        throw new PatchException(e.getMessage(), e);
    } finally {
        if (fork != null) {
            gitPatchRepository.closeRepository(fork, true);
        }
    }
}
Also used : PatchKind(io.fabric8.patch.management.PatchKind) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) DirCacheEntry(org.eclipse.jgit.dircache.DirCacheEntry) ZipArchiveEntry(org.apache.commons.compress.archivers.zip.ZipArchiveEntry) DiffEntry(org.eclipse.jgit.diff.DiffEntry) CherryPickResult(org.eclipse.jgit.api.CherryPickResult) RefSpec(org.eclipse.jgit.transport.RefSpec) ArrayList(java.util.ArrayList) List(java.util.List) LinkedList(java.util.LinkedList) RevCommit(org.eclipse.jgit.revwalk.RevCommit) Status(org.eclipse.jgit.api.Status) RevTag(org.eclipse.jgit.revwalk.RevTag) ObjectId(org.eclipse.jgit.lib.ObjectId) RevObject(org.eclipse.jgit.revwalk.RevObject) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) ListIterator(java.util.ListIterator) Date(java.util.Date) Ref(org.eclipse.jgit.lib.Ref) Git(org.eclipse.jgit.api.Git) RevertCommand(org.eclipse.jgit.api.RevertCommand) PatchException(io.fabric8.patch.management.PatchException) ZipFile(org.apache.commons.compress.archivers.zip.ZipFile) File(java.io.File) Map(java.util.Map) TreeMap(java.util.TreeMap) HashMap(java.util.HashMap)

Example 5 with RevertCommand

use of org.eclipse.jgit.api.RevertCommand in project archi-modelrepository-plugin by archi-contribs.

the class RevertCommitsAction method doRevertCommand.

@Override
protected RevertCommand doRevertCommand(Git git) throws GitAPIException, IOException {
    RevertCommand revertCommand = git.revert();
    try (RevWalk revWalk = new RevWalk(git.getRepository())) {
        // We are interested in the HEAD
        revWalk.markStart(revWalk.parseCommit(git.getRepository().resolve(IGraficoConstants.HEAD)));
        for (RevCommit c : revWalk) {
            if (c.getParentCount() > 1) {
                throw new MultipleParentsNotAllowedException(NLS.bind(Messages.RevertCommitsAction_1, c.getName()));
            }
            if (c.equals(fCommit)) {
                break;
            }
            revertCommand.include(c);
        }
        revWalk.dispose();
    }
    revertCommand.call();
    return revertCommand;
}
Also used : RevertCommand(org.eclipse.jgit.api.RevertCommand) RevWalk(org.eclipse.jgit.revwalk.RevWalk) MultipleParentsNotAllowedException(org.eclipse.jgit.api.errors.MultipleParentsNotAllowedException) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Aggregations

RevertCommand (org.eclipse.jgit.api.RevertCommand)6 Git (org.eclipse.jgit.api.Git)4 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)4 RevCommit (org.eclipse.jgit.revwalk.RevCommit)4 IOException (java.io.IOException)3 RevWalk (org.eclipse.jgit.revwalk.RevWalk)3 File (java.io.File)2 ArrayList (java.util.ArrayList)2 Date (java.util.Date)2 HashMap (java.util.HashMap)2 LinkedList (java.util.LinkedList)2 List (java.util.List)2 ListIterator (java.util.ListIterator)2 Map (java.util.Map)2 ZipArchiveEntry (org.apache.commons.compress.archivers.zip.ZipArchiveEntry)2 ZipFile (org.apache.commons.compress.archivers.zip.ZipFile)2 CherryPickResult (org.eclipse.jgit.api.CherryPickResult)2 Status (org.eclipse.jgit.api.Status)2 DiffEntry (org.eclipse.jgit.diff.DiffEntry)2 DirCacheEntry (org.eclipse.jgit.dircache.DirCacheEntry)2