Search in sources :

Example 21 with AccessToken

use of com.intellij.openapi.application.AccessToken in project intellij-community by JetBrains.

the class GitRollbackEnvironment method rollbackChanges.

public void rollbackChanges(@NotNull List<Change> changes, final List<VcsException> exceptions, @NotNull final RollbackProgressListener listener) {
    HashMap<VirtualFile, List<FilePath>> toUnindex = new HashMap<>();
    HashMap<VirtualFile, List<FilePath>> toUnversion = new HashMap<>();
    HashMap<VirtualFile, List<FilePath>> toRevert = new HashMap<>();
    List<FilePath> toDelete = new ArrayList<>();
    listener.determinate();
    // collect changes to revert
    for (Change c : changes) {
        switch(c.getType()) {
            case NEW:
                // note that this the only change that could happen
                // for HEAD-less working directories.
                registerFile(toUnversion, c.getAfterRevision().getFile(), exceptions);
                break;
            case MOVED:
                registerFile(toRevert, c.getBeforeRevision().getFile(), exceptions);
                registerFile(toUnindex, c.getAfterRevision().getFile(), exceptions);
                toDelete.add(c.getAfterRevision().getFile());
                break;
            case MODIFICATION:
                // note that changes are also removed from index, if they got into index somehow
                registerFile(toUnindex, c.getBeforeRevision().getFile(), exceptions);
                registerFile(toRevert, c.getBeforeRevision().getFile(), exceptions);
                break;
            case DELETED:
                registerFile(toRevert, c.getBeforeRevision().getFile(), exceptions);
                break;
        }
    }
    // unindex files
    for (Map.Entry<VirtualFile, List<FilePath>> entry : toUnindex.entrySet()) {
        listener.accept(entry.getValue());
        try {
            unindex(entry.getKey(), entry.getValue(), false);
        } catch (VcsException e) {
            exceptions.add(e);
        }
    }
    // unversion files
    for (Map.Entry<VirtualFile, List<FilePath>> entry : toUnversion.entrySet()) {
        listener.accept(entry.getValue());
        try {
            unindex(entry.getKey(), entry.getValue(), true);
        } catch (VcsException e) {
            exceptions.add(e);
        }
    }
    // delete files
    for (FilePath file : toDelete) {
        listener.accept(file);
        try {
            final File ioFile = file.getIOFile();
            if (ioFile.exists()) {
                if (!ioFile.delete()) {
                    //noinspection ThrowableInstanceNeverThrown
                    exceptions.add(new VcsException("Unable to delete file: " + file));
                }
            }
        } catch (Exception e) {
            //noinspection ThrowableInstanceNeverThrown
            exceptions.add(new VcsException("Unable to delete file: " + file, e));
        }
    }
    // revert files from HEAD
    AccessToken token = DvcsUtil.workingTreeChangeStarted(myProject);
    try {
        for (Map.Entry<VirtualFile, List<FilePath>> entry : toRevert.entrySet()) {
            listener.accept(entry.getValue());
            try {
                revert(entry.getKey(), entry.getValue());
            } catch (VcsException e) {
                exceptions.add(e);
            }
        }
    } finally {
        token.finish();
    }
    LocalFileSystem lfs = LocalFileSystem.getInstance();
    HashSet<File> filesToRefresh = new HashSet<>();
    for (Change c : changes) {
        ContentRevision before = c.getBeforeRevision();
        if (before != null) {
            filesToRefresh.add(new File(before.getFile().getPath()));
        }
        ContentRevision after = c.getAfterRevision();
        if (after != null) {
            filesToRefresh.add(new File(after.getFile().getPath()));
        }
    }
    lfs.refreshIoFiles(filesToRefresh);
    for (GitRepository repo : GitUtil.getRepositoryManager(myProject).getRepositories()) {
        repo.update();
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) FilePath(com.intellij.openapi.vcs.FilePath) ContentRevision(com.intellij.openapi.vcs.changes.ContentRevision) Change(com.intellij.openapi.vcs.changes.Change) VcsException(com.intellij.openapi.vcs.VcsException) GitRepository(git4idea.repo.GitRepository) AccessToken(com.intellij.openapi.application.AccessToken) LocalFileSystem(com.intellij.openapi.vfs.LocalFileSystem) VcsException(com.intellij.openapi.vcs.VcsException) VirtualFile(com.intellij.openapi.vfs.VirtualFile) File(java.io.File)

Example 22 with AccessToken

use of com.intellij.openapi.application.AccessToken in project intellij-community by JetBrains.

the class GitAbortRebaseProcess method doAbort.

private void doAbort(final boolean rollback) {
    new GitFreezingProcess(myProject, "rebase", new Runnable() {

        public void run() {
            AccessToken token = DvcsUtil.workingTreeChangeStarted(myProject);
            List<GitRepository> repositoriesToRefresh = ContainerUtil.newArrayList();
            try {
                if (myRepositoryToAbort != null) {
                    myIndicator.setText2("git rebase --abort" + GitUtil.mention(myRepositoryToAbort));
                    GitCommandResult result = myGit.rebaseAbort(myRepositoryToAbort);
                    repositoriesToRefresh.add(myRepositoryToAbort);
                    if (!result.success()) {
                        myNotifier.notifyError("Rebase Abort Failed", result.getErrorOutputAsHtmlString() + mentionLocalChangesRemainingInStash(mySaver));
                        return;
                    }
                }
                if (rollback) {
                    for (GitRepository repo : myRepositoriesToRollback.keySet()) {
                        myIndicator.setText2("git reset --keep" + GitUtil.mention(repo));
                        GitCommandResult res = myGit.reset(repo, GitResetMode.KEEP, myRepositoriesToRollback.get(repo));
                        repositoriesToRefresh.add(repo);
                        if (res.success()) {
                            String initialBranchPosition = myInitialCurrentBranches.get(repo);
                            if (initialBranchPosition != null && !initialBranchPosition.equals(repo.getCurrentBranchName())) {
                                myIndicator.setText2("git checkout " + initialBranchPosition + GitUtil.mention(repo));
                                res = myGit.checkout(repo, initialBranchPosition, null, true, false);
                            }
                        }
                        if (!res.success()) {
                            String description = myRepositoryToAbort != null ? "Rebase abort was successful" + GitUtil.mention(myRepositoryToAbort) + ", but rollback failed" : "Rollback failed";
                            description += GitUtil.mention(repo) + ":" + res.getErrorOutputAsHtmlString() + mentionLocalChangesRemainingInStash(mySaver);
                            myNotifier.notifyImportantWarning("Rebase Rollback Failed", description);
                            return;
                        }
                    }
                }
                if (mySaver != null) {
                    mySaver.load();
                }
                myNotifier.notifySuccess("Rebase abort succeeded");
            } finally {
                refresh(repositoriesToRefresh);
                token.finish();
            }
        }
    }).execute();
}
Also used : GitFreezingProcess(git4idea.util.GitFreezingProcess) GitRepository(git4idea.repo.GitRepository) AccessToken(com.intellij.openapi.application.AccessToken) GitCommandResult(git4idea.commands.GitCommandResult)

Example 23 with AccessToken

use of com.intellij.openapi.application.AccessToken in project intellij-community by JetBrains.

the class GitRebaseProcess method doRebase.

/**
   * Given a GitRebaseSpec this method either starts, or continues the ongoing rebase in multiple repositories.
   * <ul>
   * <li>It does nothing with "already successfully rebased repositories" (the ones which have {@link GitRebaseStatus} == SUCCESSFUL,
   * and just remembers them to use in the resulting notification.</li>
   * <li>If there is a repository with rebase in progress, it calls `git rebase --continue` (or `--skip`).
   * It is assumed that there is only one such repository.</li>
   * <li>For all remaining repositories rebase on which didn't start yet, it calls {@code git rebase <original parameters>}</li>
   * </ul>
   */
private void doRebase() {
    LOG.info("Started rebase");
    LOG.debug("Started rebase with the following spec: " + myRebaseSpec);
    Map<GitRepository, GitRebaseStatus> statuses = newLinkedHashMap(myRebaseSpec.getStatuses());
    Collection<GitRepository> toRefresh = newLinkedHashSet();
    List<GitRepository> repositoriesToRebase = myRebaseSpec.getIncompleteRepositories();
    AccessToken token = DvcsUtil.workingTreeChangeStarted(myProject);
    try {
        if (!saveDirtyRootsInitially(repositoriesToRebase))
            return;
        GitRepository failed = null;
        for (GitRepository repository : repositoriesToRebase) {
            GitRebaseResumeMode customMode = null;
            if (repository == myRebaseSpec.getOngoingRebase()) {
                customMode = myCustomMode == null ? GitRebaseResumeMode.CONTINUE : myCustomMode;
            }
            GitRebaseStatus rebaseStatus = rebaseSingleRoot(repository, customMode, getSuccessfulRepositories(statuses));
            // make the repo state info actual ASAP
            repository.update();
            statuses.put(repository, rebaseStatus);
            if (shouldBeRefreshed(rebaseStatus)) {
                toRefresh.add(repository);
            }
            if (rebaseStatus.getType() != GitRebaseStatus.Type.SUCCESS) {
                failed = repository;
                break;
            }
        }
        if (failed == null) {
            LOG.debug("Rebase completed successfully.");
            mySaver.load();
        }
        refresh(toRefresh);
        if (failed == null) {
            notifySuccess(getSuccessfulRepositories(statuses), getSkippedCommits(statuses));
        }
        saveUpdatedSpec(statuses);
    } catch (ProcessCanceledException pce) {
        throw pce;
    } catch (Throwable e) {
        myRepositoryManager.setOngoingRebaseSpec(null);
        ExceptionUtil.rethrowUnchecked(e);
    } finally {
        token.finish();
    }
}
Also used : GitRepository(git4idea.repo.GitRepository) AccessToken(com.intellij.openapi.application.AccessToken) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException)

Example 24 with AccessToken

use of com.intellij.openapi.application.AccessToken in project intellij-community by JetBrains.

the class GitUpdateProcess method update.

/**
   * Checks if update is possible, saves local changes and updates all roots.
   * In case of error shows notification and returns false. If update completes without errors, returns true.
   *
   * Perform update on all roots.
   * 0. Blocks reloading project on external change, saving/syncing on frame deactivation.
   * 1. Checks if update is possible (rebase/merge in progress, no tracked branches...) and provides merge dialog to solve problems.
   * 2. Finds updaters to use (merge or rebase).
   * 3. Preserves local changes if needed (not needed for merge sometimes).
   * 4. Updates via 'git pull' or equivalent.
   * 5. Restores local changes if update completed or failed with error. If update is incomplete, i.e. some unmerged files remain,
   * local changes are not restored.
   *
   */
@NotNull
public GitUpdateResult update(final UpdateMethod updateMethod) {
    LOG.info("update started|" + updateMethod);
    String oldText = myProgressIndicator.getText();
    myProgressIndicator.setText("Updating...");
    for (GitRepository repository : myRepositories) {
        repository.update();
    }
    // check if update is possible
    if (checkRebaseInProgress() || isMergeInProgress() || areUnmergedFiles() || !checkTrackedBranchesConfigured()) {
        return GitUpdateResult.NOT_READY;
    }
    if (!fetchAndNotify()) {
        return GitUpdateResult.NOT_READY;
    }
    AccessToken token = DvcsUtil.workingTreeChangeStarted(myProject);
    GitUpdateResult result;
    try {
        result = updateImpl(updateMethod);
    } finally {
        token.finish();
    }
    myProgressIndicator.setText(oldText);
    return result;
}
Also used : GitRepository(git4idea.repo.GitRepository) AccessToken(com.intellij.openapi.application.AccessToken) NotNull(org.jetbrains.annotations.NotNull)

Example 25 with AccessToken

use of com.intellij.openapi.application.AccessToken in project intellij-community by JetBrains.

the class GroovySuppressableInspectionTool method getElementToolSuppressedIn.

@Nullable
public static PsiElement getElementToolSuppressedIn(final PsiElement place, @NotNull String toolId) {
    if (place == null)
        return null;
    AccessToken accessToken = ApplicationManager.getApplication().acquireReadActionLock();
    try {
        final PsiElement statement = PsiUtil.findEnclosingStatement(place);
        if (statement != null) {
            PsiElement prev = statement.getPrevSibling();
            while (prev != null && StringUtil.isEmpty(prev.getText().trim())) {
                prev = prev.getPrevSibling();
            }
            if (prev instanceof PsiComment) {
                String text = prev.getText();
                Matcher matcher = SuppressionUtil.SUPPRESS_IN_LINE_COMMENT_PATTERN.matcher(text);
                if (matcher.matches() && SuppressionUtil.isInspectionToolIdMentioned(matcher.group(1), toolId)) {
                    return prev;
                }
            }
        }
        GrMember member = null;
        GrDocComment docComment = PsiTreeUtil.getParentOfType(place, GrDocComment.class);
        if (docComment != null) {
            GrDocCommentOwner owner = docComment.getOwner();
            if (owner instanceof GrMember) {
                member = (GrMember) owner;
            }
        }
        if (member == null) {
            member = PsiTreeUtil.getNonStrictParentOfType(place, GrMember.class);
        }
        while (member != null) {
            GrModifierList modifierList = member.getModifierList();
            for (String ids : getInspectionIdsSuppressedInAnnotation(modifierList)) {
                if (SuppressionUtil.isInspectionToolIdMentioned(ids, toolId)) {
                    return modifierList;
                }
            }
            member = PsiTreeUtil.getParentOfType(member, GrMember.class);
        }
        return null;
    } finally {
        accessToken.finish();
    }
}
Also used : GrModifierList(org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList) PsiComment(com.intellij.psi.PsiComment) GrMember(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMember) Matcher(java.util.regex.Matcher) AccessToken(com.intellij.openapi.application.AccessToken) GrDocCommentOwner(org.jetbrains.plugins.groovy.lang.groovydoc.psi.api.GrDocCommentOwner) PsiElement(com.intellij.psi.PsiElement) GrDocComment(org.jetbrains.plugins.groovy.lang.groovydoc.psi.api.GrDocComment) Nullable(org.jetbrains.annotations.Nullable)

Aggregations

AccessToken (com.intellij.openapi.application.AccessToken)97 VirtualFile (com.intellij.openapi.vfs.VirtualFile)28 Nullable (org.jetbrains.annotations.Nullable)15 Module (com.intellij.openapi.module.Module)13 Project (com.intellij.openapi.project.Project)12 Document (com.intellij.openapi.editor.Document)10 GitRepository (git4idea.repo.GitRepository)9 ArrayList (java.util.ArrayList)9 PsiElement (com.intellij.psi.PsiElement)7 NotNull (org.jetbrains.annotations.NotNull)6 File (java.io.File)5 IOException (java.io.IOException)5 ModifiableRootModel (com.intellij.openapi.roots.ModifiableRootModel)4 PsiFile (com.intellij.psi.PsiFile)4 List (java.util.List)4 HgCommandResult (org.zmlx.hg4idea.execution.HgCommandResult)4 ReadAction (com.intellij.openapi.application.ReadAction)3 CompileContext (com.intellij.openapi.compiler.CompileContext)3 CompileTask (com.intellij.openapi.compiler.CompileTask)3 ProgressIndicator (com.intellij.openapi.progress.ProgressIndicator)3