com.intellij.openapi.fileTypes.FileTypeRegistry Java Examples

The following examples show how to use com.intellij.openapi.fileTypes.FileTypeRegistry. 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: ProjectUnresolvedResourceStatsCollector.java    From intellij with Apache License 2.0 6 votes vote down vote up
@NonInjectable
ProjectUnresolvedResourceStatsCollector(
    Project project,
    WorkspacePathResolverProvider workspacePathResolverProvider,
    BlazeProjectDataManager blazeProjectDataManager,
    WorkspaceFileFinder.Provider workspaceFileFinderProvider,
    FileTypeRegistry fileTypeRegistry) {

  this.project = project;
  fileToHighlightStats = Collections.synchronizedMap(new HashMap<>());

  this.workspacePathResolverProvider = workspacePathResolverProvider;
  this.blazeProjectDataManager = blazeProjectDataManager;
  this.workspaceFileFinderProvider = workspaceFileFinderProvider;
  this.fileTypeRegistry = fileTypeRegistry;

  LowMemoryWatcher.register(this::clearMap, project);
}
 
Example #2
Source File: ReviewDiffRequest.java    From review-board-idea-plugin with Apache License 2.0 6 votes vote down vote up
@NotNull
@Override
public DiffContent[] getContents() {
    try {
        ContentRevision beforeRevision = selectedChange.getBeforeRevision();
        ContentRevision afterRevision = selectedChange.getAfterRevision();
        FileType srcFileType = FileTypeRegistry.getInstance()
                .getFileTypeByFileName(beforeRevision.getFile().getName());
        FileType dstFileType = FileTypeRegistry.getInstance()
                .getFileTypeByFileName(afterRevision.getFile().getName());

        return new DiffContent[]{
                new SimpleContent(defaultString(beforeRevision.getContent()), srcFileType),
                new SimpleContent(defaultString(afterRevision.getContent()), dstFileType)
        };
    } catch (Exception e1) {
        throw new RuntimeException(e1);
    }
}
 
Example #3
Source File: PsiDirectoryNode.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public boolean contains(@Nonnull VirtualFile file) {
  final PsiDirectory value = getValue();
  if (value == null) {
    return false;
  }

  VirtualFile directory = value.getVirtualFile();
  if (directory.getFileSystem() instanceof LocalFileSystem) {
    file = PathUtil.getLocalFile(file);
  }

  if (!VfsUtilCore.isAncestor(directory, file, false)) {
    return false;
  }

  return !FileTypeRegistry.getInstance().isFileIgnored(file);
}
 
Example #4
Source File: OuterIgnoreLoaderComponent.java    From idea-gitignore with MIT License 6 votes vote down vote up
/**
 * If language provided by platform (e.g. GitLanguage) then map to language provided by plugin
 * with extended functionality.
 *
 * @param file     file to check
 * @param fileType file's FileType
 * @return mapped language
 */
@Nullable
private IgnoreLanguage determineIgnoreLanguage(@NotNull VirtualFile file, FileType fileType) {
    FileTypeRegistry typeRegistry = FileTypeRegistry.getInstance();
    if (Utils.isGitPluginEnabled()) {
        if (typeRegistry.isFileOfType(file, GitIgnoreFileType.INSTANCE)) {
            return GitLanguage.INSTANCE;
        }
        if (typeRegistry.isFileOfType(file, GitExcludeFileType.INSTANCE)) {
            return GitExcludeLanguage.INSTANCE;
        }
    } else if (Utils.isMercurialPluginEnabled() && typeRegistry.isFileOfType(file, HgIgnoreFileType.INSTANCE)) {
        return MercurialLanguage.INSTANCE;
    } else if (fileType instanceof IgnoreFileType) {
        return ((IgnoreFileType) fileType).getIgnoreLanguage();
    }
    return null;
}
 
Example #5
Source File: LightApplicationBuilder.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void registerServices(@Nonnull InjectingContainerBuilder builder) {
  builder.bind(PsiBuilderFactory.class).to(PsiBuilderFactoryImpl.class);
  builder.bind(FileTypeRegistry.class).to(LightFileTypeRegistry.class);
  builder.bind(FileDocumentManager.class).to(LightFileDocumentManager.class);
  builder.bind(JobLauncher.class).to(LightJobLauncher.class);
  builder.bind(EncodingManager.class).to(LightEncodingManager.class);
  builder.bind(PathMacrosService.class).to(LightPathMacrosService.class);
  builder.bind(PathMacros.class).to(LightPathMacros.class);
  builder.bind(UISettings.class);
  builder.bind(ExpandableItemsHandlerFactory.class).to(LightExpandableItemsHandlerFactory.class);
  builder.bind(TreeUIHelper.class).to(LightTreeUIHelper.class);
  builder.bind(UiActivityMonitor.class).to(LightUiActivityMonitor.class);
  builder.bind(TreeAnchorizer.class).to(TreeAnchorizer.class);
  builder.bind(ProgressManager.class).to(CoreProgressManager.class);
}
 
Example #6
Source File: NewLibraryEditor.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void collectJarFiles(@Nonnull VirtualFile dir, @Nonnull List<? super VirtualFile> container, final boolean recursively) {
  VfsUtilCore.visitChildrenRecursively(dir, new VirtualFileVisitor(VirtualFileVisitor.SKIP_ROOT, recursively ? null : VirtualFileVisitor.ONE_LEVEL_DEEP) {
    @Override
    public boolean visitFile(@Nonnull VirtualFile file) {
      FileType type;
      if (!file.isDirectory() && (type = FileTypeRegistry.getInstance().getFileTypeByFileName(file.getNameSequence())) instanceof ArchiveFileType) {
        VirtualFile jarRoot = ((ArchiveFileType)type).getFileSystem().findFileByPath(file.getPath() + URLUtil.JAR_SEPARATOR);
        if (jarRoot != null) {
          container.add(jarRoot);
          return false;
        }
      }
      return true;
    }
  });
}
 
Example #7
Source File: PsiFileImplUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredUIAccess
public static PsiFile setName(final PsiFile file, String newName) throws IncorrectOperationException {
  VirtualFile vFile = file.getViewProvider().getVirtualFile();
  PsiManagerImpl manager = (PsiManagerImpl)file.getManager();

  try{
    final FileType newFileType = FileTypeRegistry.getInstance().getFileTypeByFileName(newName);
    if (UnknownFileType.INSTANCE.equals(newFileType) || newFileType.isBinary()) {
      // before the file becomes unknown or a binary (thus, not openable in the editor), save it to prevent data loss
      final FileDocumentManager fdm = FileDocumentManager.getInstance();
      final Document doc = fdm.getCachedDocument(vFile);
      if (doc != null) {
        fdm.saveDocumentAsIs(doc);
      }
    }

    vFile.rename(manager, newName);
  }
  catch(IOException e){
    throw new IncorrectOperationException(e);
  }

  return file.getViewProvider().isPhysical() ? manager.findFile(vFile) : file;
}
 
Example #8
Source File: BaseProjectViewDirectoryHelper.java    From consulo with Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
public static Collection<AbstractTreeNode> doGetDirectoryChildren(final PsiDirectory psiDirectory, final ViewSettings settings, final boolean withSubDirectories) {
  final List<AbstractTreeNode> children = new ArrayList<>();
  final Project project = psiDirectory.getProject();
  final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
  final Module module = fileIndex.getModuleForFile(psiDirectory.getVirtualFile());
  final ModuleFileIndex moduleFileIndex = module == null ? null : ModuleRootManager.getInstance(module).getFileIndex();
  if (!settings.isFlattenPackages() || skipDirectory(psiDirectory)) {
    processPsiDirectoryChildren(psiDirectory, directoryChildrenInProject(psiDirectory, settings), children, fileIndex, null, settings, withSubDirectories);
  }
  else { // source directory in "flatten packages" mode
    final PsiDirectory parentDir = psiDirectory.getParentDirectory();
    if (parentDir == null || skipDirectory(parentDir) /*|| !rootDirectoryFound(parentDir)*/ && withSubDirectories) {
      addAllSubpackages(children, psiDirectory, moduleFileIndex, settings);
    }
    PsiDirectory[] subdirs = psiDirectory.getSubdirectories();
    for (PsiDirectory subdir : subdirs) {
      if (!skipDirectory(subdir)) {
        continue;
      }
      VirtualFile directoryFile = subdir.getVirtualFile();
      if (FileTypeRegistry.getInstance().isFileIgnored(directoryFile)) continue;

      if (withSubDirectories) {
        children.add(new PsiDirectoryNode(project, subdir, settings));
      }
    }
    processPsiDirectoryChildren(psiDirectory, psiDirectory.getFiles(), children, fileIndex, moduleFileIndex, settings, withSubDirectories);
  }
  return children;
}
 
Example #9
Source File: ProjectUnresolvedResourceStatsCollector.java    From intellij with Apache License 2.0 5 votes vote down vote up
ProjectUnresolvedResourceStatsCollector(Project project) {
  this(
      project,
      WorkspacePathResolverProvider.getInstance(project),
      BlazeProjectDataManager.getInstance(project),
      WorkspaceFileFinder.Provider.getInstance(project),
      FileTypeRegistry.getInstance());
}
 
Example #10
Source File: IdIndexImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public int getVersion() {
  FileType[] types = FileTypeRegistry.getInstance().getRegisteredFileTypes();
  Arrays.sort(types, (o1, o2) -> Comparing.compare(o1.getName(), o2.getName()));

  int version = super.getVersion();
  for (FileType fileType : types) {
    if (!isIndexable(myCacheBuilderRegistry, fileType)) continue;
    IdIndexer indexer = IdTableBuilding.getFileTypeIndexer(fileType);
    if (indexer == null) continue;
    version = version * 31 + (indexer.getVersion() ^ indexer.getClass().getName().hashCode());
  }
  return version;
}
 
Example #11
Source File: StubVersionMap.java    From consulo with Apache License 2.0 5 votes vote down vote up
StubVersionMap() throws IOException {
  for (final FileType fileType : FileTypeRegistry.getInstance().getRegisteredFileTypes()) {
    Object owner = getVersionOwner(fileType);
    if (owner != null) {
      fileTypeToVersionOwner.put(fileType, owner);
    }
  }

  updateState();
}
 
Example #12
Source File: FileTypeIndexImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public int getVersion() {
  FileType[] types = FileTypeRegistry.getInstance().getRegisteredFileTypes();
  int version = 2;
  for (FileType type : types) {
    version += type.getName().hashCode();
  }

  version *= 31;
  for (FileTypeRegistry.FileTypeDetector detector : FileTypeRegistry.FileTypeDetector.EP_NAME.getExtensionList()) {
    version += detector.getVersion();
  }
  return version;
}
 
Example #13
Source File: CopyrightFileConfigManager.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void readExternal(Element element) throws InvalidDataException {
  List<Element> langs = element.getChildren("LanguageOptions");
  for (Element configElement : langs) {
    String name = configElement.getAttributeValue("name");

    final LoadedOption option;

    if(LANG_TEMPLATE.equals(name)) {
      option = new TemplateLoadedOption();
    }
    else {
      FileType fileTypeByName = FileTypeRegistry.getInstance().findFileTypeByName(name);
      if (fileTypeByName == null) {
        option = new UnknownLoadedOption();
      }
      else {
        UpdateCopyrightsProvider updateCopyrightsProvider = CopyrightUpdaters.INSTANCE.forFileType(fileTypeByName);
        if(updateCopyrightsProvider == null) {
          option = new UnknownLoadedOption();
        }
        else {
          option = new ValidLoadedOption(updateCopyrightsProvider.createDefaultOptions());
        }
      }
    }

    option.read(configElement);

    myConfigs.put(name, option);
  }
}
 
Example #14
Source File: FileContentImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private FileContentImpl(@Nonnull VirtualFile file, CharSequence contentAsText, byte[] content, long stamp, boolean physicalContent) {
  super(file, FileTypeRegistry.getInstance().getFileTypeByFile(file, content));
  myContentAsText = contentAsText;
  myContent = content;
  myStamp = stamp;
  myPhysicalContent = physicalContent;
}
 
Example #15
Source File: PsiFileFactoryImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public PsiFile createFileFromText(@Nonnull String name, @Nonnull String text) {
  FileType type = FileTypeRegistry.getInstance().getFileTypeByFileName(name);
  if (type.isBinary()) {
    throw new RuntimeException("Cannot create binary files from text: name " + name + ", file type " + type);
  }

  return createFileFromText(name, type, text);
}
 
Example #16
Source File: AbstractConvertLineSeparatorsAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static boolean shouldProcess(@Nonnull VirtualFile file, @Nonnull Project project) {
  if (file.isDirectory() ||
      !file.isWritable() ||
      FileTypeRegistry.getInstance().isFileIgnored(file) ||
      file.getFileType().isBinary() ||
      file.equals(project.getProjectFile()) ||
      file.equals(project.getWorkspaceFile())) {
    return false;
  }
  return true;
}
 
Example #17
Source File: ProjectFileNode.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a {@link Module} to which the specified {@code file} belongs;
 * or a {@link Project} if the specified {@code file} does not belong to any module, but is located under the base project directory;
 * or {@code null} if the specified {@code file} does not correspond to the given {@code project}
 */
@Nullable
static ComponentManager findArea(@Nonnull VirtualFile file, @Nullable Project project) {
  if (project == null || project.isDisposed() || !file.isValid()) return null;
  Module module = ProjectFileIndex.getInstance(project).getModuleForFile(file, false);
  if (module != null) return module.isDisposed() ? null : module;
  if (!is("projectView.show.base.dir")) return null;
  VirtualFile ancestor = findBaseDir(project);
  // file does not belong to any content root, but it is located under the project directory and not ignored
  return ancestor == null || FileTypeRegistry.getInstance().isFileIgnored(file) || !isAncestor(ancestor, file, false) ? null : project;
}
 
Example #18
Source File: BaseApplication.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected void bootstrapInjectingContainer(@Nonnull InjectingContainerBuilder builder) {
  super.bootstrapInjectingContainer(builder);

  builder.bind(Application.class).to(this);
  builder.bind(ApplicationEx.class).to(this);
  builder.bind(ApplicationEx2.class).to(this);
  builder.bind(ApplicationInfo.class).to(ApplicationInfo::getInstance);
  builder.bind(ContainerPathManager.class).to(ContainerPathManager::get);

  builder.bind(IApplicationStore.class).to(ApplicationStoreImpl.class).forceSingleton();
  builder.bind(ApplicationPathMacroManager.class).to(ApplicationPathMacroManager.class).forceSingleton();

  builder.bind(FileTypeRegistry.class).to(FileTypeManager::getInstance);
}
 
Example #19
Source File: PsiUtilCore.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Tries to find PSI file for a virtual file and throws assertion error with debug info if it is null.
 */
@Nonnull
public static PsiFile getPsiFile(@Nonnull Project project, @Nonnull VirtualFile file) {
  PsiManager psiManager = PsiManager.getInstance(project);
  PsiFile psi = psiManager.findFile(file);
  if (psi != null) return psi;
  FileType fileType = file.getFileType();
  FileViewProvider viewProvider = psiManager.findViewProvider(file);
  Document document = FileDocumentManager.getInstance().getDocument(file);
  boolean ignored = !(file instanceof LightVirtualFile) && FileTypeRegistry.getInstance().isFileIgnored(file);
  VirtualFile vDir = file.getParent();
  PsiDirectory psiDir = vDir == null ? null : PsiManager.getInstance(project).findDirectory(vDir);
  FileIndexFacade indexFacade = FileIndexFacade.getInstance(project);
  StringBuilder sb = new StringBuilder();
  sb.append("valid=").append(file.isValid()).
          append(" isDirectory=").append(file.isDirectory()).
          append(" hasDocument=").append(document != null).
          append(" length=").append(file.getLength());
  sb.append("\nproject=").append(project.getName()).
          append(" default=").append(project.isDefault()).
          append(" open=").append(project.isOpen());;
  sb.append("\nfileType=").append(fileType.getName()).append("/").append(fileType.getClass().getName());
  sb.append("\nisIgnored=").append(ignored);
  sb.append(" underIgnored=").append(indexFacade.isUnderIgnored(file));
  sb.append(" inLibrary=").append(indexFacade.isInLibrarySource(file) || indexFacade.isInLibraryClasses(file));
  sb.append(" parentDir=").append(vDir == null ? "no-vfs" : vDir.isDirectory() ? "has-vfs-dir" : "has-vfs-file").
          append("/").append(psiDir == null ? "no-psi" : "has-psi");
  sb.append("\nviewProvider=").append(viewProvider == null ? "null" : viewProvider.getClass().getName());
  if (viewProvider != null) {
    List<PsiFile> files = viewProvider.getAllFiles();
    sb.append(" language=").append(viewProvider.getBaseLanguage().getID());
    sb.append(" physical=").append(viewProvider.isPhysical());
    sb.append(" rootCount=").append(files.size());
    for (PsiFile o : files) {
      sb.append("\n  root=").append(o.getLanguage().getID()).append("/").append(o.getClass().getName());
    }
  }
  LOG.error("no PSI for file '" + file.getName() + "'", new Attachment(file.getPresentableUrl(), sb.toString()));
  throw new AssertionError();
}
 
Example #20
Source File: LightVirtualFile.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void setLanguage(@Nonnull Language language) {
  myLanguage = language;
  FileType type = language.getAssociatedFileType();
  if (type == null) {
    type = FileTypeRegistry.getInstance().getFileTypeByFileName(getName());
  }
  setFileType(type);
}
 
Example #21
Source File: FileReference.java    From consulo with Apache License 2.0 5 votes vote down vote up
@javax.annotation.Nullable
public String getNewFileTemplateName() {
  FileType fileType = FileTypeRegistry.getInstance().getFileTypeByFileName(myText);
  if (fileType != UnknownFileType.INSTANCE) {
    return fileType.getName() + " File." + fileType.getDefaultExtension();
  }
  return null;
}
 
Example #22
Source File: IdeaLightweightExtension.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeEach(ExtensionContext extensionContext) {
    contextStack.add(0, extensionContext);

    DisposableRegistry parent = new DisposableRegistry();
    getStore(extensionContext).put("parent", parent);

    final FileTypeRegistry fileTypeRegistry = mock(FileTypeRegistry.class);
    getStore(extensionContext).put("fileTypeRegistry", fileTypeRegistry);

    Application original = ApplicationManager.getApplication();
    getStore(extensionContext).put("original-application", original);

    Application application = mock(Application.class);
    ApplicationManager.setApplication(application, () -> fileTypeRegistry, parent);
    getStore(extensionContext).put("application", application);
    initializeApplication(application);

    Project project = mock(Project.class);
    when(project.isInitialized()).thenReturn(true);
    when(project.isDisposed()).thenReturn(false);
    getStore(extensionContext).put("project", project);
    initializeProject(project);

    LocalFileSystem lfs = mock(LocalFileSystem.class);
    getStore(extensionContext).put("local-filesystem", lfs);
    setupLocalFileSystem(lfs);
}
 
Example #23
Source File: AbstractFileViewProvider.java    From consulo with Apache License 2.0 4 votes vote down vote up
protected final boolean isIgnored() {
  final VirtualFile file = getVirtualFile();
  return !(file instanceof LightVirtualFile) && FileTypeRegistry.getInstance().isFileIgnored(file);
}
 
Example #24
Source File: VirtualFile.java    From consulo with Apache License 2.0 4 votes vote down vote up
/**
 * @return the {@link FileType} of this file.
 * When IDEA has no idea what the file type is (i.e. file type is not registered via {@link FileTypeRegistry}),
 * it returns {@link com.intellij.openapi.fileTypes.FileTypes#UNKNOWN}
 */
@SuppressWarnings("JavadocReference")
@Nonnull
public FileType getFileType() {
  return FileTypeRegistry.getInstance().getFileTypeByFile(this);
}
 
Example #25
Source File: ArchiveFileSystem.java    From consulo with Apache License 2.0 4 votes vote down vote up
/**
 * Implementations should return {@code false} if the given file may not host this file system.
 */
protected boolean isCorrectFileType(@Nonnull VirtualFile local) {
  FileType fileType = FileTypeRegistry.getInstance().getFileTypeByFileName(local.getNameSequence());
  return fileType instanceof ArchiveFileType && ((ArchiveFileType)fileType).getFileSystem() == this;
}
 
Example #26
Source File: RootIndex.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static boolean isIgnored(@Nonnull VirtualFile dir) {
  return FileTypeRegistry.getInstance().isFileIgnored(dir);
}
 
Example #27
Source File: CSharpCreateFromTemplateHandler.java    From consulo-csharp with Apache License 2.0 4 votes vote down vote up
@Override
public boolean handlesTemplate(FileTemplate template)
{
	FileType fileTypeByExtension = FileTypeRegistry.getInstance().getFileTypeByExtension(template.getExtension());
	return fileTypeByExtension == CSharpFileType.INSTANCE;
}
 
Example #28
Source File: IdeaLightweightExtension.java    From p4ic4idea with Apache License 2.0 4 votes vote down vote up
private FileTypeRegistry getMockFileTypeRegistry(ExtensionContext topContext) {
    return (FileTypeRegistry) getStore(topContext).get("fileTypeRegistry");
}
 
Example #29
Source File: IdeaLightweightExtension.java    From p4ic4idea with Apache License 2.0 4 votes vote down vote up
public FileTypeRegistry getMockFileTypeRegistry() {
    return getMockFileTypeRegistry(getTopContext());
}