Java Code Examples for com.intellij.psi.PsiDirectory

The following examples show how to use com.intellij.psi.PsiDirectory. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: svgtoandroid   Source File: ModulesUtil.java    License: MIT License 6 votes vote down vote up
public Set<String> getModules() {
    Set<String> modules = new HashSet<String>();
    PsiDirectory baseDir = PsiDirectoryFactory.getInstance(project).createDirectory(project.getBaseDir());
    if (isAndroidProject(baseDir)) {
        Logger.debug(project.getName() + " is an Android project");
        PsiDirectory[] dirs = baseDir.getSubdirectories();
        for (PsiDirectory dir : dirs) {
            if (!dir.getName().equals("build") && !dir.getName().equals("gradle")) {
                if (isModule(dir)) {
                    Logger.debug(dir.getName() + " is a Module");
                    modules.add(dir.getName());
                }
            }
        }
    }
    Logger.debug(modules.toString());
    return modules;
}
 
Example 2
Source Project: idea-php-typo3-plugin   Source File: TYPO3ExtensionUtil.java    License: MIT License 6 votes vote down vote up
/**
 * Traverses the given directories and returns the first valid
 * extension definition that's applicable.
 *
 * @param directories List of directories to analyze
 */
public static TYPO3ExtensionDefinition findContainingExtension(PsiDirectory[] directories) {
    for (PsiDirectory directory : directories) {
        VirtualDirectoryImpl virtualFile = (VirtualDirectoryImpl) directory.getVirtualFile();

        while (!isExtensionRootDirectory(virtualFile)) {
            if (virtualFile.getParent() == null) {
                return null;
            }

            virtualFile = virtualFile.getParent();
        }

        TYPO3ExtensionDefinition extensionDefinition = ExtensionDefinitionFactory.fromDirectory(virtualFile);
        if (extensionDefinition != null) {
            return extensionDefinition;
        }
    }

    return null;
}
 
Example 3
private void renameDirs(final Project project,
                        final PsiElement nameSuggestionContext,
                        final Editor editor,
                        final PsiDirectory contextDirectory,
                        final T aPackage,
                        final PsiDirectory... dirsToRename) {
  final RenameDialog dialog = new RenameDialog(project, contextDirectory, nameSuggestionContext, editor) {
    @Override
    protected void doAction() {
      String newQName = StringUtil.getQualifiedName(StringUtil.getPackageName(getQualifiedName(aPackage)), getNewName());
      BaseRefactoringProcessor moveProcessor = createProcessor(newQName, project, dirsToRename, isSearchInComments(),
                                                               isSearchInNonJavaFiles());
      invokeRefactoring(moveProcessor);
    }
  };
  dialog.show();
}
 
Example 4
Source Project: consulo   Source File: DirectoryUrl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object[] createPath(final Project project) {
  if (moduleName != null) {
    final Module module = ApplicationManager.getApplication().runReadAction(new Computable<Module>() {
      @Nullable
      @Override
      public Module compute() {
        return ModuleManager.getInstance(project).findModuleByName(moduleName);
      }
    });
    if (module == null) return null;
  }
  final VirtualFileManager virtualFileManager = VirtualFileManager.getInstance();
  final VirtualFile file = virtualFileManager.findFileByUrl(url);
  if (file == null) return null;
  final PsiDirectory directory = ApplicationManager.getApplication().runReadAction(new Computable<PsiDirectory>() {
    @Nullable
    @Override
    public PsiDirectory compute() {
      return PsiManager.getInstance(project).findDirectory(file);
    }
  });
  if (directory == null) return null;
  return new Object[]{directory};
}
 
Example 5
Source Project: consulo   Source File: LibraryGroupNode.java    License: Apache License 2.0 6 votes vote down vote up
public static void addLibraryChildren(final OrderEntry entry, final List<AbstractTreeNode> children, Project project, ProjectViewNode node) {
  final PsiManager psiManager = PsiManager.getInstance(project);
  VirtualFile[] files =
    entry instanceof LibraryOrderEntry ? getLibraryRoots((LibraryOrderEntry)entry) : entry.getFiles(BinariesOrderRootType.getInstance());
  for (final VirtualFile file : files) {
    if (!file.isValid()) continue;
    if (file.isDirectory()) {
      final PsiDirectory psiDir = psiManager.findDirectory(file);
      if (psiDir == null) {
        continue;
      }
      children.add(new PsiDirectoryNode(project, psiDir, node.getSettings()));
    }
    else {
      final PsiFile psiFile = psiManager.findFile(file);
      if (psiFile == null) continue;
      children.add(new PsiFileNode(project, psiFile, node.getSettings()));
    }
  }
}
 
Example 6
@Nullable
public static PhpClass getBundleClassInDirectory(@NotNull PsiDirectory bundleDirContext) {

    for (PsiFile psiFile : bundleDirContext.getFiles()) {

        if(!(psiFile instanceof PhpFile)) {
            continue;
        }

        PhpClass aClass = PhpPsiUtil.findClass((PhpFile) psiFile, phpClass ->
            PhpElementsUtil.isInstanceOf(phpClass, "\\Symfony\\Component\\HttpKernel\\Bundle\\BundleInterface")
        );

        if(aClass != null) {
            return aClass;
        }

    }

    return null;
}
 
Example 7
Source Project: JHelper   Source File: TaskUtils.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
private static PsiElement generateCPP(Project project, TaskData taskData) {
	VirtualFile parent = FileUtils.findOrCreateByRelativePath(project.getBaseDir(), FileUtils.getDirectory(taskData.getCppPath()));
	PsiDirectory psiParent = PsiManager.getInstance(project).findDirectory(parent);
	if (psiParent == null) {
		throw new NotificationException("Couldn't open parent directory as PSI");
	}

	Language objC = Language.findLanguageByID("ObjectiveC");
	if (objC == null) {
		throw new NotificationException("Language not found");
	}

	PsiFile file = PsiFileFactory.getInstance(project).createFileFromText(
			FileUtils.getFilename(taskData.getCppPath()),
			objC,
			getTaskContent(project, taskData.getClassName())
	);
	if (file == null) {
		throw new NotificationException("Couldn't generate file");
	}
	return ApplicationManager.getApplication().runWriteAction(
			(Computable<PsiElement>) () -> psiParent.add(file)
	);

}
 
Example 8
Source Project: weex-language-support   Source File: ExtraModulesUtil.java    License: MIT License 6 votes vote down vote up
private static PsiFile getMain(PsiDirectory moduleRoot) {
    PsiFile pkg = moduleRoot.findFile("package.json");
    if (pkg != null && pkg instanceof JsonFile) {
        if (((JsonFile) pkg).getTopLevelValue() instanceof JsonObject) {
            JsonObject object = (JsonObject) ((JsonFile) pkg).getTopLevelValue();
            if (object != null) {
                JsonProperty property = object.findProperty("main");
                if (property != null && property.getValue() != null && property.getValue() instanceof JsonStringLiteral) {
                    JsonStringLiteral propValue = (JsonStringLiteral) property.getValue();
                    String value = propValue.getValue();
                    PsiFile psiFile = moduleRoot.findFile(value.replace("./", ""));
                    return psiFile;
                }
            }
        }
    }
    return null;
}
 
Example 9
Source Project: consulo   Source File: ContentFolderTypeProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
@RequiredReadAction
public final Image getChildDirectoryIcon(@Nullable PsiDirectory psiDirectory, @Nullable PsiPackageManager oldPsiPackageManager) {
  Image packageIcon = getChildPackageIcon();
  if (packageIcon == null) {
    return getChildDirectoryIcon();
  }

  if (psiDirectory != null) {
    PsiPackageManager psiPackageManager = oldPsiPackageManager == null ? PsiPackageManager.getInstance(psiDirectory.getProject()) : oldPsiPackageManager;
    PsiPackage anyPackage = psiPackageManager.findAnyPackage(psiDirectory);
    if (anyPackage != null) {
      return packageIcon;
    }
    else {
      return getChildDirectoryIcon();
    }
  }
  else {
    //
    return packageIcon;
  }
}
 
Example 10
@Test
public void testResolvableImportPrefix() {
  Label label = Label.create("//foo/bar:baz");
  PsiDirectory externalGithubDirectory = mockPsiDirectory("github.com", null);
  PsiDirectory externalGithubUserDirectory = mockPsiDirectory("user", externalGithubDirectory);
  PsiDirectory fooDirectory = mockPsiDirectory("foo", externalGithubUserDirectory);
  PsiDirectory fooBarDirectory = mockPsiDirectory("bar", fooDirectory);
  BuildFile fooBarBuild = mockBuildFile(fooBarDirectory);
  FuncallExpression fooBarBazRule = mockRule("baz", fooBarBuild);
  PsiElement[] importReferences =
      BlazeGoPackage.getImportReferences(label, fooBarBazRule, "github.com/user/foo/bar/baz");
  assertThat(importReferences)
      .isEqualTo(
          new PsiElement[] {
            externalGithubDirectory, // github.com
            externalGithubUserDirectory, // user
            fooDirectory, // foo
            fooBarDirectory, // bar
            fooBarBazRule, // baz
          });
}
 
Example 11
Source Project: PackageTemplates   Source File: FileWriter.java    License: Apache License 2.0 6 votes vote down vote up
public static PsiDirectory writeDirectory(PsiDirectory dir, DirectoryWrapper dirWrapper, Project project) {
    if (dir == null) {
        //todo print error
        return null;
    }

    RunnableFuture<PsiDirectory> runnableFuture = new FutureTask<>(() ->
            ApplicationManager.getApplication().runWriteAction(new Computable<PsiDirectory>() {
                @Override
                public PsiDirectory compute() {
                    return writeDirectoryAction(dir, dirWrapper, project);
                }
            }));

    ApplicationManager.getApplication().invokeLater(runnableFuture);

    try {
        return runnableFuture.get();
    } catch (InterruptedException | ExecutionException e) {
        Logger.log("runnableFuture  " + e.getMessage());
        Logger.printStack(e);
    }

    return null;
}
 
Example 12
Source Project: consulo   Source File: MoveDirectoryWithClassesProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private static void collectFiles2Move(Map<PsiFile, TargetDirectoryWrapper> files2Move,
                                   PsiDirectory directory,
                                   PsiDirectory rootDirectory,
                                   @Nonnull TargetDirectoryWrapper targetDirectory) {
  final PsiElement[] children = directory.getChildren();
  final String relativePath = VfsUtilCore.getRelativePath(directory.getVirtualFile(), rootDirectory.getVirtualFile(), '/');

  final TargetDirectoryWrapper newTargetDirectory = relativePath.length() == 0
                                                    ? targetDirectory
                                                    : targetDirectory.findOrCreateChild(relativePath);
  for (PsiElement child : children) {
    if (child instanceof PsiFile) {
      files2Move.put((PsiFile)child, newTargetDirectory);
    }
    else if (child instanceof PsiDirectory){
      collectFiles2Move(files2Move, (PsiDirectory)child, directory, newTargetDirectory);
    }
  }
}
 
Example 13
Source Project: PackageTemplates   Source File: PackageTemplateWrapper.java    License: Apache License 2.0 6 votes vote down vote up
public void collectSimpleActions(Project project, VirtualFile virtualFile, List<SimpleAction> listSimpleAction) {
    ApplicationManager.getApplication().runReadAction(() -> {
        PsiDirectory currentDir = FileWriter.findCurrentDirectory(project, virtualFile);
        if (currentDir == null) {
            return;
        }

        // Disabled
        if (!getRootElement().getDirectory().isEnabled()) {
            return;
        }

        SimpleAction rootAction = getRootAction(project, listSimpleAction, currentDir);

        CollectSimpleActionVisitor visitor = new CollectSimpleActionVisitor(rootAction, project);

        for (ElementWrapper elementWrapper : rootElement.getListElementWrapper()) {
            elementWrapper.accept(visitor);
        }
    });
}
 
Example 14
Source Project: CleanArchitecturePlugin   Source File: BaseController.java    License: Apache License 2.0 6 votes vote down vote up
public static void generateBaseArchitecture(PsiDirectory parent) {

        // Check if exists main package
        PsiDirectory packageResult = containsPackage(parent, MAIN.toLowerCase());

        // Not exists
        if (packageResult == null) {
            // Create main package
            mainDirectory = createDirectory(parent, MAIN.toLowerCase());
        } else {  // Exists

            // Set user main package
            setMainDirectory(packageResult);
        }

        // Create data package
        BaseDataController.create();

        // Create domain package
        BaseDomainController.create();

        // Create view package
        BaseViewController.create();
    }
 
Example 15
Source Project: idea-php-symfony2-plugin   Source File: FileResourceUtil.java    License: MIT License 6 votes vote down vote up
/**
 * Gives targets to files which relative to current file directory
 */
@NotNull
public static Collection<PsiFile> getFileResourceTargetsInDirectoryScope(@NotNull PsiFile psiFile, @NotNull String content) {

    // bundle scope
    if(content.startsWith("@")) {
        return Collections.emptyList();
    }

    PsiDirectory containingDirectory = psiFile.getContainingDirectory();
    if(containingDirectory == null) {
        return Collections.emptyList();
    }

    VirtualFile relativeFile = VfsUtil.findRelativeFile(content, containingDirectory.getVirtualFile());
    if(relativeFile == null) {
        return Collections.emptyList();
    }

    PsiFile targetFile = PsiElementUtils.virtualFileToPsiFile(psiFile.getProject(), relativeFile);
    if(targetFile == null) {
        return Collections.emptyList();
    }

    return Collections.singletonList(targetFile);
}
 
Example 16
Source Project: netbeans-mmd-plugin   Source File: FileMoveHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public List<UsageInfo> findUsages(final PsiFile psiFile, final PsiDirectory newParent, final boolean searchInComments, final boolean searchInNonJavaFiles) {
  Query<PsiReference> search = ReferencesSearch.search(psiFile);
  final List<PsiExtraFileReference> extraFileRefs = new ArrayList<PsiExtraFileReference>();
  search.forEach(new Processor<PsiReference>() {
    @Override
    public boolean process(PsiReference psiReference) {
      if (psiReference instanceof PsiExtraFileReference) {
        extraFileRefs.add((PsiExtraFileReference) psiReference);
      }
      return true;
    }
  });

  if (extraFileRefs.isEmpty()) {
    return null;
  } else {
    final List<UsageInfo> result = new ArrayList<UsageInfo>(extraFileRefs.size());
    for (final PsiExtraFileReference e : extraFileRefs) {
      result.add(new FileUsageInfo(e));
    }
    return result;
  }
}
 
Example 17
Source Project: PackageTemplates   Source File: DeleteDirectoryAction.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void doRun() {
    PsiDirectory psiDirectory = VFSHelper.findPsiDirByPath(project, fileDirToDelete.getPath());
    if (psiDirectory == null) {
        ReportHelper.setState(ExecutionState.FAILED);
        return;
    }

    try {
        psiDirectory.delete();
    } catch (IncorrectOperationException ex) {
        Logger.log("DeleteDirectoryAction " + ex.getMessage());
        Logger.printStack(ex);
        ReportHelper.setState(ExecutionState.FAILED);
        return;
    }
}
 
Example 18
Source Project: consulo   Source File: FileTreeIterator.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
public static List<PsiDirectory> collectModuleDirectories(Module module) {
  List<PsiDirectory> dirs = ContainerUtil.newArrayList();

  VirtualFile[] contentRoots = ModuleRootManager.getInstance(module).getContentRoots();
  for (VirtualFile root : contentRoots) {
    PsiDirectory dir = PsiManager.getInstance(module.getProject()).findDirectory(root);
    if (dir != null) {
      dirs.add(dir);
    }
  }

  return dirs;
}
 
Example 19
Source Project: Intellij-Plugin   Source File: SpecsExecutionProducer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean isConfigurationFromContext(RunConfiguration config, ConfigurationContext context) {
    if (!(config.getType() instanceof GaugeRunTaskConfigurationType)) return false;
    if (!(context.getPsiLocation() instanceof PsiDirectory) && !(context.getPsiLocation() instanceof PsiFile))
        return false;
    VirtualFile[] selectedFiles = CommonDataKeys.VIRTUAL_FILE_ARRAY.getData(context.getDataContext());
    if (selectedFiles == null) return false;
    String specs = ((GaugeRunConfiguration) config).getSpecsToExecute();
    return StringUtil.join(getSpecs(selectedFiles), Constants.SPEC_FILE_DELIMITER).equals(specs);
}
 
Example 20
Source Project: consulo   Source File: TodoDirNode.java    License: Apache License 2.0 5 votes vote down vote up
public int getTodoItemCount(PsiDirectory directory) {
  if (TodoTreeHelper.skipDirectory(directory)) {
    return 0;
  }
  int count = 0;
  Iterator<PsiFile> iterator = myBuilder.getFiles(directory);
  while (iterator.hasNext()) {
    PsiFile psiFile = iterator.next();
    count += getStructure().getTodoItemCount(psiFile);
  }
  return count;
}
 
Example 21
@Override
@RequiredReadAction
public void prepareProperties(Map<String, Object> props)
{
	PsiDirectory directory = (PsiDirectory) props.get("psiDirectory");
	if(directory == null)
	{
		return;
	}

	Module module = ModuleUtilCore.findModuleForPsiElement(directory);
	if(module != null)
	{
		props.put("MODULE", module.getName());
	}
	props.put("GUID", UUID.randomUUID().toString());

	DotNetSimpleModuleExtension<?> extension = ModuleUtilCore.getExtension(directory, DotNetSimpleModuleExtension.class);
	if(extension == null)
	{
		Module moduleByPsiDirectory = findModuleByPsiDirectory(directory);
		if(moduleByPsiDirectory != null)
		{
			extension = ModuleUtilCore.getExtension(moduleByPsiDirectory, DotNetSimpleModuleExtension.class);
		}
	}

	String namespace = null;
	if(extension != null)
	{
		namespace = formatNamespace(extension.getNamespaceGeneratePolicy().calculateNamespace(directory));
	}
	props.put("NAMESPACE_NAME", namespace);
}
 
Example 22
Source Project: consulo   Source File: ProjectViewPane.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean addSubtreeToUpdateByElement(@Nonnull Object element) {
  if (element instanceof PsiDirectory && !myProject.isDisposed()) {
    final PsiDirectory dir = (PsiDirectory)element;
    final ProjectTreeStructure treeStructure = (ProjectTreeStructure)myTreeStructure;
    PsiDirectory dirToUpdateFrom = dir;

    // optimization
    // isEmptyMiddleDirectory can be slow when project VFS is not fully loaded (initial dumb mode).
    // It's easiest to disable the optimization in any dumb mode
    if (!treeStructure.isFlattenPackages() && treeStructure.isHideEmptyMiddlePackages() && !DumbService.isDumb(myProject)) {
      while (dirToUpdateFrom != null && BaseProjectViewDirectoryHelper.isEmptyMiddleDirectory(dirToUpdateFrom, true)) {
        dirToUpdateFrom = dirToUpdateFrom.getParentDirectory();
      }
    }
    boolean addedOk;
    while (!(addedOk = super.addSubtreeToUpdateByElement(dirToUpdateFrom == null ? myTreeStructure.getRootElement() : dirToUpdateFrom))) {
      if (dirToUpdateFrom == null) {
        break;
      }
      dirToUpdateFrom = dirToUpdateFrom.getParentDirectory();
    }
    return addedOk;
  }

  return super.addSubtreeToUpdateByElement(element);
}
 
Example 23
Source Project: intellij   Source File: GlobFindUsagesTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testExcludeDirectories() {
  PsiDirectory dir = workspace.createPsiDirectory(new WorkspacePath("java/com/google/tests"));
  workspace.createPsiFile(new WorkspacePath("java/com/google/tests/Test.java"));
  workspace.createPsiFile(new WorkspacePath("java/com/google/Foo.java"));
  BuildFile file =
      createBuildFile(
          new WorkspacePath("java/com/google/BUILD"),
          "glob(" + "  ['**/*']," + "  exclude = ['BUILD'])");

  PsiUtils.findFirstChildOfClassRecursive(file, GlobExpression.class);

  PsiReference[] references = FindUsages.findAllReferences(dir);
  assertThat(references).isEmpty();
}
 
Example 24
Source Project: intellij-haxe   Source File: HaxePackageModel.java    License: Apache License 2.0 5 votes vote down vote up
protected HaxeFile getFile(String fileName) {
  PsiDirectory directory = root.access(path);
  if (directory != null && directory.isValid()) {
    PsiFile file = directory.findFile(fileName + ".hx");
    if (file != null && file.isValid() && file instanceof HaxeFile) {
      return (HaxeFile)file;
    }
  }

  return null;
}
 
Example 25
@Override
protected PsiFile createFile(String name, String templateName, PsiDirectory dir) {
    String nameWithoutPrefix = name.replaceFirst("NodeTypes\\.", "");
    String prefix = "";
    switch (templateName) {
        case DOCUMENT_NODE_TYPE_TEMPLATE_NAME:
            prefix = "Document.";
            break;
        case CONTENT_NODE_TYPE_TEMPLATE_NAME:
            prefix = "Content.";
            break;
        case COLLECTION_NODE_TYPE_TEMPLATE_NAME:
            prefix = "Collection.";
            break;
        case MIXIN_NODE_TYPE_TEMPLATE_NAME:
            prefix = "Mixin.";
            break;
        case CONSTRAINT_NODE_TYPE_TEMPLATE_NAME:
            prefix = "Constraint.";
            break;
    }

    if (!nameWithoutPrefix.startsWith(prefix)) {
        nameWithoutPrefix = prefix + nameWithoutPrefix;
    }

    name = "NodeTypes." + nameWithoutPrefix;
    return super.createFile(name, templateName, dir);
}
 
Example 26
Source Project: idea-gitignore   Source File: Utils.java    License: MIT License 5 votes vote down vote up
/**
 * Gets Ignore file for given {@link Project} and root {@link PsiDirectory}.
 * If file is missing - creates new one.
 *
 * @param project         current project
 * @param fileType        current ignore file type
 * @param directory       root directory
 * @param createIfMissing create new file if missing
 * @return Ignore file
 */
@Nullable
public static PsiFile getIgnoreFile(@NotNull Project project, @NotNull IgnoreFileType fileType,
                                    @Nullable PsiDirectory directory, boolean createIfMissing) {
    VirtualFile projectDir = Utils.guessProjectDir(project);
    if (projectDir == null) {
        return null;
    }
    if (directory == null) {
        directory = PsiManager.getInstance(project).findDirectory(projectDir);
    }

    assert directory != null;
    String filename = fileType.getIgnoreLanguage().getFilename();
    PsiFile file = directory.findFile(filename);
    VirtualFile virtualFile = file == null ? directory.getVirtualFile().findChild(filename) : file.getVirtualFile();

    if (file == null && virtualFile == null && createIfMissing) {
        try {
            file = new CreateFileCommandAction(project, directory, fileType).execute();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }

    return file;
}
 
Example 27
Source Project: intellij-haxe   Source File: HaxePackageModel.java    License: Apache License 2.0 5 votes vote down vote up
@NotNull
public List<HaxePackageModel> getChildren() {
  PsiDirectory directory = root.access(path);
  if (directory != null) {
    return Arrays.stream(directory.getSubdirectories())
      .map(subDirectory -> new HaxePackageModel(root, subDirectory.getName(), this))
      .collect(Collectors.toList());
  }
  return Collections.emptyList();
}
 
Example 28
Source Project: intellij   Source File: BlazePyUseScopeEnlarger.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean isPyPackageOutsideProject(PsiElement element) {
  if (!(element instanceof PsiDirectory)) {
    return false;
  }
  PsiDirectory dir = (PsiDirectory) element;
  return dir.findFile(PyNames.INIT_DOT_PY) != null
      && !inProjectScope(dir.getProject(), dir.getVirtualFile());
}
 
Example 29
void createOrUpdateIntrospectionOutputFile(String schemaText, IntrospectionOutputFormat format, VirtualFile introspectionSourceFile, String outputFileName) {
    ApplicationManager.getApplication().runWriteAction(() -> {
        try {
            final String header;
            switch (format) {
                case SDL:
                    header = "# This file was generated based on \"" + introspectionSourceFile.getName() + "\". Do not edit manually.\n\n";
                    break;
                case JSON:
                    header = "";
                    break;
                default:
                    throw new IllegalArgumentException("unsupported output format: " + format);
            }
            String relativeOutputFileName = StringUtils.replaceChars(outputFileName, '\\', '/');
            VirtualFile outputFile = introspectionSourceFile.getParent().findFileByRelativePath(relativeOutputFileName);
            if (outputFile == null) {
                PsiDirectory directory = PsiDirectoryFactory.getInstance(myProject).createDirectory(introspectionSourceFile.getParent());
                CreateFileAction.MkDirs dirs = new CreateFileAction.MkDirs(relativeOutputFileName, directory);
                outputFile = dirs.directory.getVirtualFile().createChildData(introspectionSourceFile, dirs.newName);
            }
            outputFile.putUserData(GraphQLSchemaKeys.IS_GRAPHQL_INTROSPECTION_JSON, true);
            final FileEditor[] fileEditors = FileEditorManager.getInstance(myProject).openFile(outputFile, true, true);
            if (fileEditors.length > 0) {
                final FileEditor fileEditor = fileEditors[0];
                setEditorTextAndFormatLines(header + schemaText, fileEditor);
            } else {
                Notifications.Bus.notify(new Notification("GraphQL", "GraphQL Error", "Unable to open an editor for '" + outputFile.getPath() + "'", NotificationType.ERROR));
            }
        } catch (IOException ioe) {
            Notifications.Bus.notify(new Notification("GraphQL", "GraphQL IO Error", "Unable to create file '" + outputFileName + "' in directory '" + introspectionSourceFile.getParent().getPath() + "': " + ioe.getMessage(), NotificationType.ERROR));
        }
    });
}
 
Example 30
Source Project: consulo   Source File: CreateFromTemplateActionBase.java    License: Apache License 2.0 5 votes vote down vote up
@RequiredUIAccess
@Override
public final void actionPerformed(@Nonnull AnActionEvent e) {
  DataContext dataContext = e.getDataContext();
  IdeView view = dataContext.getData(LangDataKeys.IDE_VIEW);
  if (view == null) return;
  PsiDirectory dir = getTargetDirectory(dataContext, view);
  if (dir == null) return;
  Project project = dir.getProject();

  FileTemplate selectedTemplate = getTemplate(project, dir);
  if (selectedTemplate != null) {
    AnAction action = getReplacedAction(selectedTemplate);
    if (action != null) {
      action.actionPerformed(e);
    }
    else {
      FileTemplateManager.getInstance(project).addRecentName(selectedTemplate.getName());
      AttributesDefaults defaults = getAttributesDefaults(dataContext);
      Map<String, Object> properties = defaults != null ? defaults.getDefaultProperties() : null;
      CreateFromTemplateDialog dialog = new CreateFromTemplateDialog(dir, selectedTemplate, defaults, properties);
      PsiElement createdElement = dialog.create();
      if (createdElement != null) {
        elementCreated(dialog, createdElement);
        view.selectElement(createdElement);
        if (selectedTemplate.isLiveTemplateEnabled() && createdElement instanceof PsiFile) {
          Map<String, String> defaultValues = getLiveTemplateDefaults(dataContext, ((PsiFile)createdElement));
          startLiveTemplate((PsiFile)createdElement, notNull(defaultValues, Collections.emptyMap()));
        }
      }
    }
  }
}
 
Example 31
Source Project: consulo   Source File: MoveDirectoryWithClassesProcessor.java    License: Apache License 2.0 5 votes vote down vote up
public PsiDirectory findOrCreateTargetDirectory() throws IncorrectOperationException{
  if (myTargetDirectory == null) {
    final PsiDirectory root = myParentDirectory.findOrCreateTargetDirectory();

    myTargetDirectory = root.findSubdirectory(myRelativePath);
    if (myTargetDirectory == null) {
      myTargetDirectory = root.createSubdirectory(myRelativePath);
    }
  }
  return myTargetDirectory;
}
 
Example 32
Source Project: consulo   Source File: DirectoryChooser.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
@RequiredReadAction
private static PsiDirectory getDefaultSelection(PsiDirectory[] directories, Project project) {
  final String defaultSelectionPath = PropertiesComponent.getInstance(project).getValue(DEFAULT_SELECTION);
  if (defaultSelectionPath != null) {
    final VirtualFile directoryByDefault = LocalFileSystem.getInstance().findFileByPath(defaultSelectionPath);
    if (directoryByDefault != null) {
      final PsiDirectory directory = PsiManager.getInstance(project).findDirectory(directoryByDefault);
      return directory != null && ArrayUtil.find(directories, directory) > -1 ? directory : null;
    }
  }
  return null;
}
 
Example 33
Source Project: consulo   Source File: TodoDirNode.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void setupIcon(PresentationData data, PsiDirectory psiDirectory) {
  final VirtualFile virtualFile = psiDirectory.getVirtualFile();
  if (ProjectRootsUtil.isModuleContentRoot(virtualFile, psiDirectory.getProject())) {
    data.setIcon(IconDescriptorUpdaters.getIcon(psiDirectory, 0));
  }
  else {
    super.setupIcon(data, psiDirectory);
  }
}
 
Example 34
Source Project: intellij   Source File: BlazePackage.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
private static PsiDirectory getPsiDirectory(PsiFileSystemItem file) {
  if (file instanceof PsiDirectory) {
    return (PsiDirectory) file;
  }
  if (file instanceof PsiFile) {
    return ((PsiFile) file).getContainingDirectory();
  }
  if (file instanceof PackagePrefixFileSystemItem) {
    return ((PackagePrefixFileSystemItem) file).getDirectory();
  }
  return null;
}
 
Example 35
Source Project: consulo-csharp   Source File: CSharpCreateFileAction.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@RequiredUIAccess
protected boolean isAvailable(DataContext dataContext)
{
	Module module = findModule(dataContext);
	if(module != null)
	{
		DotNetModuleExtension extension = ModuleUtilCore.getExtension(module, DotNetModuleExtension.class);
		if(extension != null && extension.isAllowSourceRoots())
		{
			final IdeView view = dataContext.getData(LangDataKeys.IDE_VIEW);
			if(view == null)
			{
				return false;
			}

			PsiDirectory orChooseDirectory = view.getOrChooseDirectory();
			if(orChooseDirectory == null)
			{
				return false;
			}
			PsiPackage aPackage = PsiPackageManager.getInstance(module.getProject()).findPackage(orChooseDirectory, DotNetModuleExtension.class);

			if(aPackage == null)
			{
				return false;
			}
		}
	}
	return module != null && ModuleUtilCore.getExtension(module, CSharpSimpleModuleExtension.class) != null;
}
 
Example 36
Source Project: consulo   Source File: DirectoryChooser.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean isParent(PsiDirectory directory, PsiDirectory parentCandidate) {
  while (directory != null) {
    if (directory.equals(parentCandidate)) return true;
    directory = directory.getParentDirectory();
  }
  return false;
}
 
Example 37
Source Project: consulo   Source File: FavoritesTreeNodeDescriptor.java    License: Apache License 2.0 5 votes vote down vote up
public static String getLocation(final AbstractTreeNode element, final Project project) {
  Object nodeElement = element.getValue();
  if (nodeElement instanceof SmartPsiElementPointer) {
    nodeElement = ((SmartPsiElementPointer)nodeElement).getElement();
  }
  if (nodeElement instanceof PsiElement) {
    if (nodeElement instanceof PsiDirectory) {
      return ((PsiDirectory)nodeElement).getVirtualFile().getPresentableUrl();
    }
    if (nodeElement instanceof PsiFile) {
      final PsiFile containingFile = (PsiFile)nodeElement;
      final VirtualFile virtualFile = containingFile.getVirtualFile();
      return virtualFile != null ? virtualFile.getPresentableUrl() : "";
    }
  }

  if (nodeElement instanceof LibraryGroupElement) {
    return ((LibraryGroupElement)nodeElement).getModule().getName();
  }
  if (nodeElement instanceof NamedLibraryElement) {
    final NamedLibraryElement namedLibraryElement = ((NamedLibraryElement)nodeElement);
    final Module module = namedLibraryElement.getModule();
    return (module != null ? module.getName() : "") + ":" + namedLibraryElement.getOrderEntry().getPresentableName();
  }

  final FavoriteNodeProvider[] nodeProviders = Extensions.getExtensions(FavoriteNodeProvider.EP_NAME, project);
  for (FavoriteNodeProvider provider : nodeProviders) {
    String location = provider.getElementLocation(nodeElement);
    if (location != null) return location;
  }
  return null;
}
 
Example 38
Source Project: consulo   Source File: CreateFileAction.java    License: Apache License 2.0 5 votes vote down vote up
@RequiredUIAccess
@Override
public boolean canClose(final String inputString) {
  if (inputString.length() == 0) {
    return super.canClose(inputString);
  }

  final PsiDirectory psiDirectory = getDirectory();

  final Project project = psiDirectory.getProject();
  final boolean[] result = {false};
  FileTypeChooser.getKnownFileTypeOrAssociate(psiDirectory.getVirtualFile(), getFileName(inputString), project);
  result[0] = super.canClose(getFileName(inputString));
  return result[0];
}
 
Example 39
Source Project: consulo   Source File: AddToFavoritesAction.java    License: Apache License 2.0 5 votes vote down vote up
private static Class<? extends AbstractTreeNode> getPsiElementNodeClass(PsiElement psiElement) {
  Class<? extends AbstractTreeNode> klass = null;
  if (psiElement instanceof PsiFile) {
    klass = PsiFileNode.class;
  }
  else if (psiElement instanceof PsiDirectory) {
    klass = PsiDirectoryNode.class;
  }
  return klass;
}
 
Example 40
@NotNull
protected final PsiElement[] invokeDialog(final Project project, final PsiDirectory directory) {
    final MyInputValidator validator = new MyInputValidator(project, directory);
    Messages.showInputDialog(project, getDialogPrompt(), getDialogTitle(), Messages.getQuestionIcon(), "", validator);

    final PsiElement[] elements = validator.getCreatedElements();
    return elements;
}