com.intellij.psi.PsiDirectory Java Examples

The following examples show how to use com.intellij.psi.PsiDirectory. 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 check out the related API usage on the sidebar.
Example #1
Source File: ModulesUtil.java    From svgtoandroid with 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 File: TYPO3ExtensionUtil.java    From idea-php-typo3-plugin with 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
Source File: DirectoryAsPackageRenameHandlerBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
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 File: DirectoryUrl.java    From consulo with 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 File: LibraryGroupNode.java    From consulo with 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
Source File: BundleClassGeneratorUtil.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@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 File: TaskUtils.java    From JHelper with 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 File: ExtraModulesUtil.java    From weex-language-support with 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 File: ContentFolderTypeProvider.java    From consulo with 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
Source File: BlazeGoPackageImportReferencesTest.java    From intellij with Apache License 2.0 6 votes vote down vote up
@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 File: FileWriter.java    From PackageTemplates with 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 File: MoveDirectoryWithClassesProcessor.java    From consulo with 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 File: PackageTemplateWrapper.java    From PackageTemplates with 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 File: BaseController.java    From CleanArchitecturePlugin with 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 File: FileResourceUtil.java    From idea-php-symfony2-plugin with 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 File: FileMoveHandler.java    From netbeans-mmd-plugin with 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 File: DeleteDirectoryAction.java    From PackageTemplates with 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 File: FileTreeIterator.java    From consulo with 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 File: SpecsExecutionProducer.java    From Intellij-Plugin with 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 File: TodoDirNode.java    From consulo with 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
Source File: CSharpCreateFromTemplateHandler.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@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 File: ProjectViewPane.java    From consulo with 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 File: GlobFindUsagesTest.java    From intellij with 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 File: HaxePackageModel.java    From intellij-haxe with 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
Source File: CreateNodeTypeDefinition.java    From intellij-neos with GNU General Public License v3.0 5 votes vote down vote up
@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 File: Utils.java    From idea-gitignore with 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 File: HaxePackageModel.java    From intellij-haxe with 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 File: BlazePyUseScopeEnlarger.java    From intellij with 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
Source File: GraphQLIntrospectionHelper.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
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 File: CreateFromTemplateActionBase.java    From consulo with 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()));
        }
      }
    }
  }
}