Search in sources :

Example 41 with Condition

use of com.intellij.openapi.util.Condition in project intellij-community by JetBrains.

the class CreateParameterForFieldIntention method findCandidates.

private static List<GrField> findCandidates(PsiMethod constructor, final GrTypeDefinition clazz) {
    final List<GrField> usedFields = new ArrayList<>();
    final GrOpenBlock block = constructor instanceof GrMethod ? ((GrMethod) constructor).getBlock() : null;
    if (block == null) {
        return usedFields;
    }
    final PsiManager manager = clazz.getManager();
    block.accept(new GroovyRecursiveElementVisitor() {

        @Override
        public void visitReferenceExpression(@NotNull GrReferenceExpression referenceExpression) {
            super.visitReferenceExpression(referenceExpression);
            final PsiElement resolved = referenceExpression.resolve();
            if (resolved instanceof GrField && manager.areElementsEquivalent(((GrField) resolved).getContainingClass(), clazz) && PsiUtil.isAccessedForWriting(referenceExpression)) {
                usedFields.add((GrField) resolved);
            }
        }

        @Override
        public void visitTypeDefinition(@NotNull GrTypeDefinition typeDefinition) {
        }

        @Override
        public void visitClosure(@NotNull GrClosableBlock closure) {
        }
    });
    List<GrField> fields = new ArrayList<>();
    for (final GrField field : clazz.getFields()) {
        if (field.getInitializerGroovy() != null)
            continue;
        if (ContainerUtil.find(usedFields, new Condition<PsiField>() {

            @Override
            public boolean value(PsiField o) {
                return manager.areElementsEquivalent(o, field);
            }
        }) == null) {
            fields.add(field);
        }
    }
    return fields;
}
Also used : Condition(com.intellij.openapi.util.Condition) GrField(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField) ArrayList(java.util.ArrayList) GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) GroovyRecursiveElementVisitor(org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor) GrReferenceExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression) GrTypeDefinition(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition) GrOpenBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrOpenBlock)

Example 42 with Condition

use of com.intellij.openapi.util.Condition in project intellij-community by JetBrains.

the class JavaFxFileReferenceProvider method getReferences.

public static PsiReference[] getReferences(@NotNull PsiElement element, String value, final String acceptedExtension) {
    final PsiDirectory directory = element.getContainingFile().getOriginalFile().getParent();
    if (directory == null)
        return PsiReference.EMPTY_ARRAY;
    final boolean startsWithSlash = value.startsWith("/");
    final VirtualFileSystem fs = directory.getVirtualFile().getFileSystem();
    final FileReferenceSet fileReferenceSet = new FileReferenceSet(value, element, 1, null, fs.isCaseSensitive()) {

        @NotNull
        @Override
        public Collection<PsiFileSystemItem> getDefaultContexts() {
            if (startsWithSlash || !directory.isValid()) {
                return super.getDefaultContexts();
            }
            return Collections.singletonList(directory);
        }

        @Override
        protected Condition<PsiFileSystemItem> getReferenceCompletionFilter() {
            return item -> {
                if (item instanceof PsiDirectory)
                    return true;
                final VirtualFile virtualFile = PsiUtilCore.getVirtualFile(item);
                return virtualFile != null && acceptedExtension.equals(virtualFile.getExtension());
            };
        }
    };
    if (startsWithSlash) {
        fileReferenceSet.addCustomization(FileReferenceSet.DEFAULT_PATH_EVALUATOR_OPTION, FileReferenceSet.ABSOLUTE_TOP_LEVEL);
    }
    return fileReferenceSet.getAllReferences();
}
Also used : ProcessingContext(com.intellij.util.ProcessingContext) VirtualFileSystem(com.intellij.openapi.vfs.VirtualFileSystem) PsiUtilCore(com.intellij.psi.util.PsiUtilCore) VirtualFile(com.intellij.openapi.vfs.VirtualFile) Collection(java.util.Collection) com.intellij.psi(com.intellij.psi) NotNull(org.jetbrains.annotations.NotNull) Collections(java.util.Collections) FileReferenceSet(com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReferenceSet) Condition(com.intellij.openapi.util.Condition) VirtualFile(com.intellij.openapi.vfs.VirtualFile) VirtualFileSystem(com.intellij.openapi.vfs.VirtualFileSystem) FileReferenceSet(com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReferenceSet)

Example 43 with Condition

use of com.intellij.openapi.util.Condition in project intellij-community by JetBrains.

the class GitCheckinEnvironment method commitWithCaseOnlyRename.

@NotNull
private List<VcsException> commitWithCaseOnlyRename(@NotNull Project project, @NotNull VirtualFile root, @NotNull Set<Change> caseOnlyRenames, @NotNull Set<FilePath> added, @NotNull Set<FilePath> removed, @NotNull File messageFile, @Nullable String author) {
    String rootPath = root.getPath();
    LOG.info("Committing case only rename: " + getLogString(rootPath, caseOnlyRenames) + " in " + getShortRepositoryName(project, root));
    // 1. Check what is staged besides case-only renames
    Collection<Change> stagedChanges;
    try {
        stagedChanges = GitChangeUtils.getStagedChanges(project, root);
        LOG.debug("Found staged changes: " + getLogString(rootPath, stagedChanges));
    } catch (VcsException e) {
        return Collections.singletonList(e);
    }
    // 2. Reset staged changes which are not selected for commit
    Collection<Change> excludedStagedChanges = filter(stagedChanges, change -> !caseOnlyRenames.contains(change) && !added.contains(getAfterPath(change)) && !removed.contains(getBeforePath(change)));
    if (!excludedStagedChanges.isEmpty()) {
        LOG.info("Staged changes excluded for commit: " + getLogString(rootPath, excludedStagedChanges));
        try {
            reset(project, root, excludedStagedChanges);
        } catch (VcsException e) {
            return Collections.singletonList(e);
        }
    }
    List<VcsException> exceptions = new ArrayList<>();
    try {
        // 3. Stage what else is needed to commit
        List<FilePath> newPathsOfCaseRenames = map(caseOnlyRenames, ChangesUtil::getAfterPath);
        LOG.debug("Updating index for added:" + added + "\n, removed: " + removed + "\n, and case-renames: " + newPathsOfCaseRenames);
        Set<FilePath> toAdd = new HashSet<>(added);
        toAdd.addAll(newPathsOfCaseRenames);
        updateIndex(project, root, toAdd, removed, exceptions);
        if (!exceptions.isEmpty())
            return exceptions;
        // 4. Commit the staging area
        LOG.debug("Performing commit...");
        try {
            commitWithoutPaths(project, root, messageFile, author);
        } catch (VcsException e) {
            return Collections.singletonList(e);
        }
    } finally {
        // 5. Stage back the changes unstaged before commit
        if (!excludedStagedChanges.isEmpty()) {
            LOG.debug("Restoring changes which were unstaged before commit: " + getLogString(rootPath, excludedStagedChanges));
            Set<FilePath> toAdd = map2SetNotNull(excludedStagedChanges, ChangesUtil::getAfterPath);
            Condition<Change> isMovedOrDeleted = change -> change.getType() == Change.Type.MOVED || change.getType() == Change.Type.DELETED;
            Set<FilePath> toRemove = map2SetNotNull(filter(excludedStagedChanges, isMovedOrDeleted), ChangesUtil::getBeforePath);
            updateIndex(project, root, toAdd, toRemove, exceptions);
        }
    }
    return exceptions;
}
Also used : FilePath(com.intellij.openapi.vcs.FilePath) VirtualFile(com.intellij.openapi.vfs.VirtualFile) TextCompletionProvider(com.intellij.util.textCompletion.TextCompletionProvider) ModalityState(com.intellij.openapi.application.ModalityState) com.intellij.openapi.vcs.changes(com.intellij.openapi.vcs.changes) CheckinChangeListSpecificComponent(com.intellij.openapi.vcs.checkin.CheckinChangeListSpecificComponent) GitVersionSpecialty(git4idea.config.GitVersionSpecialty) GridBag(com.intellij.util.ui.GridBag) PairConsumer(com.intellij.util.PairConsumer) JBLabel(com.intellij.ui.components.JBLabel) CheckinEnvironment(com.intellij.openapi.vcs.checkin.CheckinEnvironment) GitSimpleHandler(git4idea.commands.GitSimpleHandler) VcsPushDialog(com.intellij.dvcs.push.ui.VcsPushDialog) GitUtil(git4idea.GitUtil) DvcsUtil(com.intellij.dvcs.DvcsUtil) JBUI(com.intellij.util.ui.JBUI) StringUtil.escapeXml(com.intellij.openapi.util.text.StringUtil.escapeXml) Arrays.asList(java.util.Arrays.asList) FileUtil(com.intellij.openapi.util.io.FileUtil) FunctionUtil(com.intellij.util.FunctionUtil) Logger(com.intellij.openapi.diagnostic.Logger) VcsException(com.intellij.openapi.vcs.VcsException) GitRepository(git4idea.repo.GitRepository) FilePath(com.intellij.openapi.vcs.FilePath) EditorTextField(com.intellij.ui.EditorTextField) GitBundle(git4idea.i18n.GitBundle) NullableFunction(com.intellij.util.NullableFunction) GitChangeUtils(git4idea.changes.GitChangeUtils) KeyEvent(java.awt.event.KeyEvent) RefreshableOnComponent(com.intellij.openapi.vcs.ui.RefreshableOnComponent) TextFieldWithCompletion(com.intellij.util.textCompletion.TextFieldWithCompletion) GitUtil.getRepositoryManager(git4idea.GitUtil.getRepositoryManager) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) ServiceManager(com.intellij.openapi.components.ServiceManager) VcsUser(com.intellij.vcs.log.VcsUser) VcsUserUtil(com.intellij.vcs.log.util.VcsUserUtil) DvcsUtil.getShortRepositoryName(com.intellij.dvcs.DvcsUtil.getShortRepositoryName) GitFileUtils(git4idea.util.GitFileUtils) NotNull(org.jetbrains.annotations.NotNull) Ref(com.intellij.openapi.util.Ref) ChangesUtil.getAfterPath(com.intellij.openapi.vcs.changes.ChangesUtil.getAfterPath) java.util(java.util) GitRepositoryManager(git4idea.repo.GitRepositoryManager) NonNls(org.jetbrains.annotations.NonNls) SimpleDateFormat(java.text.SimpleDateFormat) GitVcsSettings(git4idea.config.GitVcsSettings) ContainerUtil(com.intellij.util.containers.ContainerUtil) VcsFullCommitDetails(com.intellij.vcs.log.VcsFullCommitDetails) GitBranchUtil(git4idea.branch.GitBranchUtil) GitVcs(git4idea.GitVcs) ChangesUtil.getBeforePath(com.intellij.openapi.vcs.changes.ChangesUtil.getBeforePath) ObjectUtils.assertNotNull(com.intellij.util.ObjectUtils.assertNotNull) ValuesCompletionProviderDumbAware(com.intellij.util.textCompletion.ValuesCompletionProvider.ValuesCompletionProviderDumbAware) CommonBundle(com.intellij.CommonBundle) Project(com.intellij.openapi.project.Project) VcsFileUtil(com.intellij.vcsUtil.VcsFileUtil) GitConfigUtil(git4idea.config.GitConfigUtil) SelectFilePathsDialog(com.intellij.openapi.vcs.changes.ui.SelectFilePathsDialog) CheckinProjectPanel(com.intellij.openapi.vcs.CheckinProjectPanel) VcsUtil(com.intellij.vcsUtil.VcsUtil) JBCheckBox(com.intellij.ui.components.JBCheckBox) GitUserRegistry(git4idea.GitUserRegistry) DefaultTextCompletionValueDescriptor(com.intellij.util.textCompletion.DefaultTextCompletionValueDescriptor) GitUtil.getLogString(git4idea.GitUtil.getLogString) StringUtil(com.intellij.openapi.util.text.StringUtil) GitCommand(git4idea.commands.GitCommand) GuiUtils(com.intellij.ui.GuiUtils) VcsUserRegistry(com.intellij.vcs.log.VcsUserRegistry) SystemInfo(com.intellij.openapi.util.SystemInfo) java.awt(java.awt) AmendComponent(com.intellij.dvcs.AmendComponent) java.io(java.io) Condition(com.intellij.openapi.util.Condition) javax.swing(javax.swing) GitUtil.getLogString(git4idea.GitUtil.getLogString) VcsException(com.intellij.openapi.vcs.VcsException) NotNull(org.jetbrains.annotations.NotNull) ObjectUtils.assertNotNull(com.intellij.util.ObjectUtils.assertNotNull)

Example 44 with Condition

use of com.intellij.openapi.util.Condition in project intellij-community by JetBrains.

the class GitConfigTest method test_branch_with_hash_symbol.

//inspired by IDEA-135557
public void test_branch_with_hash_symbol() throws IOException {
    createRepository();
    addRemote("http://example.git");
    git("update-ref refs/remotes/origin/a#branch HEAD");
    git("branch --track a#branch origin/a#branch");
    File gitDir = new File(myProjectPath, ".git");
    GitConfig config = GitConfig.read(new File(gitDir, "config"));
    VirtualFile dir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(gitDir);
    GitRepositoryReader reader = new GitRepositoryReader(GitRepositoryFiles.getInstance(dir));
    GitBranchState state = reader.readState(config.parseRemotes());
    Collection<GitBranchTrackInfo> trackInfos = config.parseTrackInfos(state.getLocalBranches().keySet(), state.getRemoteBranches().keySet());
    assertTrue("Couldn't find correct a#branch tracking information among: [" + trackInfos + "]", ContainerUtil.exists(trackInfos, new Condition<GitBranchTrackInfo>() {

        @Override
        public boolean value(GitBranchTrackInfo info) {
            return info.getLocalBranch().getName().equals("a#branch") && info.getRemoteBranch().getNameForLocalOperations().equals("origin/a#branch");
        }
    }));
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) Condition(com.intellij.openapi.util.Condition) VirtualFile(com.intellij.openapi.vfs.VirtualFile) File(java.io.File)

Example 45 with Condition

use of com.intellij.openapi.util.Condition in project intellij-community by JetBrains.

the class CCCreateCourseArchive method createCourseArchive.

public static void createCourseArchive(final Project project, Module module, String zipName, String locationDir, boolean showMessage) {
    final Course course = StudyTaskManager.getInstance(project).getCourse();
    if (course == null)
        return;
    final VirtualFile baseDir = project.getBaseDir();
    VirtualFile archiveFolder = CCUtils.generateFolder(project, module, zipName);
    if (archiveFolder == null) {
        return;
    }
    CCLanguageManager manager = CCUtils.getStudyLanguageManager(course);
    if (manager == null) {
        return;
    }
    FileFilter filter = pathname -> !manager.doNotPackFile(pathname);
    for (VirtualFile child : baseDir.getChildren()) {
        String name = child.getName();
        File fromFile = new File(child.getPath());
        if (CCUtils.GENERATED_FILES_FOLDER.equals(name) || Project.DIRECTORY_STORE_FOLDER.equals(name) || name.contains("iml") || manager.doNotPackFile(fromFile)) {
            continue;
        }
        copyChild(archiveFolder, filter, child, fromFile);
    }
    ApplicationManager.getApplication().runWriteAction(new Runnable() {

        @Override
        public void run() {
            archiveFolder.refresh(false, true);
            Course courseCopy = course.copy();
            replaceAnswerFilesWithTaskFiles(courseCopy);
            generateJson(archiveFolder, courseCopy);
            VirtualFileManager.getInstance().refreshWithoutFileWatcher(false);
            packCourse(archiveFolder, locationDir, zipName, showMessage);
            synchronize(project);
        }

        private void replaceAnswerFilesWithTaskFiles(Course courseCopy) {
            for (Lesson lesson : courseCopy.getLessons()) {
                String lessonDirName = EduNames.LESSON + String.valueOf(lesson.getIndex());
                final VirtualFile lessonDir = baseDir.findChild(lessonDirName);
                if (lessonDir == null)
                    continue;
                for (Task task : lesson.getTaskList()) {
                    final VirtualFile taskDir = task.getTaskDir(project);
                    if (taskDir == null)
                        continue;
                    String taskDirName = EduNames.TASK + String.valueOf(task.getIndex());
                    VirtualFile studentFileDir = VfsUtil.findRelativeFile(archiveFolder, lessonDirName, taskDirName);
                    if (studentFileDir == null) {
                        continue;
                    }
                    VirtualFile srcDir = studentFileDir.findChild(EduNames.SRC);
                    if (srcDir != null) {
                        studentFileDir = srcDir;
                    }
                    if (task.hasSubtasks()) {
                        transformSubtaskTestsToTextFiles(studentFileDir);
                    }
                    for (String taskFile : task.getTaskFiles().keySet()) {
                        VirtualFile answerFile = taskDir.findFileByRelativePath(taskFile);
                        if (answerFile == null) {
                            continue;
                        }
                        EduUtils.createStudentFile(this, project, answerFile, studentFileDir, task, 0);
                    }
                }
            }
        }

        private void transformSubtaskTestsToTextFiles(VirtualFile studentFileDir) {
            Condition<VirtualFile> isSubtaskTestFile = file -> CCUtils.isTestsFile(project, file) && file.getName().contains(EduNames.SUBTASK_MARKER);
            List<VirtualFile> subtaskTests = ContainerUtil.filter(Arrays.asList(studentFileDir.getChildren()), isSubtaskTestFile);
            for (VirtualFile subtaskTest : subtaskTests) {
                try {
                    subtaskTest.rename(this, subtaskTest.getNameWithoutExtension() + ".txt");
                } catch (IOException e) {
                    LOG.error(e);
                }
            }
        }
    });
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) ZipOutputStream(java.util.zip.ZipOutputStream) Arrays(java.util.Arrays) VirtualFile(com.intellij.openapi.vfs.VirtualFile) Presentation(com.intellij.openapi.actionSystem.Presentation) EduUsagesCollector(com.jetbrains.edu.learning.statistics.EduUsagesCollector) ContainerUtil(com.intellij.util.containers.ContainerUtil) GsonBuilder(com.google.gson.GsonBuilder) VirtualFileManager(com.intellij.openapi.vfs.VirtualFileManager) ProjectView(com.intellij.ide.projectView.ProjectView) CreateCourseArchiveDialog(com.jetbrains.edu.coursecreator.ui.CreateCourseArchiveDialog) EduUtils(com.jetbrains.edu.learning.core.EduUtils) DialogWrapper(com.intellij.openapi.ui.DialogWrapper) CCLanguageManager(com.jetbrains.edu.coursecreator.CCLanguageManager) Gson(com.google.gson.Gson) Project(com.intellij.openapi.project.Project) Messages(com.intellij.openapi.ui.Messages) CommonDataKeys(com.intellij.openapi.actionSystem.CommonDataKeys) FileUtil(com.intellij.openapi.util.io.FileUtil) Logger(com.intellij.openapi.diagnostic.Logger) Module(com.intellij.openapi.module.Module) Lesson(com.jetbrains.edu.learning.courseFormat.Lesson) StudyTaskManager(com.jetbrains.edu.learning.StudyTaskManager) Task(com.jetbrains.edu.learning.courseFormat.Task) DumbAwareAction(com.intellij.openapi.project.DumbAwareAction) List(java.util.List) java.io(java.io) EduNames(com.jetbrains.edu.learning.core.EduNames) AnActionEvent(com.intellij.openapi.actionSystem.AnActionEvent) ApplicationManager(com.intellij.openapi.application.ApplicationManager) VfsUtil(com.intellij.openapi.vfs.VfsUtil) LangDataKeys(com.intellij.openapi.actionSystem.LangDataKeys) NotNull(org.jetbrains.annotations.NotNull) ZipUtil(com.intellij.util.io.ZipUtil) CCUtils(com.jetbrains.edu.coursecreator.CCUtils) Course(com.jetbrains.edu.learning.courseFormat.Course) Condition(com.intellij.openapi.util.Condition) Condition(com.intellij.openapi.util.Condition) Task(com.jetbrains.edu.learning.courseFormat.Task) CCLanguageManager(com.jetbrains.edu.coursecreator.CCLanguageManager) Lesson(com.jetbrains.edu.learning.courseFormat.Lesson) List(java.util.List) Course(com.jetbrains.edu.learning.courseFormat.Course) VirtualFile(com.intellij.openapi.vfs.VirtualFile)

Aggregations

Condition (com.intellij.openapi.util.Condition)48 NotNull (org.jetbrains.annotations.NotNull)26 Nullable (org.jetbrains.annotations.Nullable)23 Project (com.intellij.openapi.project.Project)21 VirtualFile (com.intellij.openapi.vfs.VirtualFile)21 List (java.util.List)16 StringUtil (com.intellij.openapi.util.text.StringUtil)15 ContainerUtil (com.intellij.util.containers.ContainerUtil)14 javax.swing (javax.swing)13 PsiElement (com.intellij.psi.PsiElement)11 Module (com.intellij.openapi.module.Module)10 java.util (java.util)10 Logger (com.intellij.openapi.diagnostic.Logger)9 ApplicationManager (com.intellij.openapi.application.ApplicationManager)8 NonNls (org.jetbrains.annotations.NonNls)8 GlobalSearchScope (com.intellij.psi.search.GlobalSearchScope)7 Collection (java.util.Collection)7 ModalityState (com.intellij.openapi.application.ModalityState)6 Document (com.intellij.openapi.editor.Document)6 DialogWrapper (com.intellij.openapi.ui.DialogWrapper)6