Java Code Examples for com.intellij.openapi.vfs.VirtualFile#getExtension()

The following examples show how to use com.intellij.openapi.vfs.VirtualFile#getExtension() . 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: CsvFileTypeOverrider.java    From intellij-csv-validator with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public FileType getOverriddenFileType(@NotNull VirtualFile file) {
    if (file != null) {
        String extension = file.getExtension();
        if (extension != null) {
            switch (extension.toLowerCase()) {
                case "csv":
                    return CsvFileType.INSTANCE;
                case "tsv":
                case "tab":
                    return TsvFileType.INSTANCE;
                case "psv":
                    return PsvFileType.INSTANCE;
                default:
                    return null;
            }
        }
    }
    return null;
}
 
Example 2
Source File: SaveFileAsTemplateAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredUIAccess
@Override
public void actionPerformed(@Nonnull AnActionEvent e){
  Project project = e.getRequiredData(CommonDataKeys.PROJECT);
  String fileText = e.getData(PlatformDataKeys.FILE_TEXT);
  VirtualFile file = e.getData(PlatformDataKeys.VIRTUAL_FILE);
  String extension = file.getExtension();
  String nameWithoutExtension = file.getNameWithoutExtension();
  AllFileTemplatesConfigurable fileTemplateOptions = new AllFileTemplatesConfigurable(project);
  ConfigureTemplatesDialog dialog = new ConfigureTemplatesDialog(project, fileTemplateOptions);
  PsiFile psiFile = e.getData(LangDataKeys.PSI_FILE);
  for(SaveFileAsTemplateHandler handler: Extensions.getExtensions(SaveFileAsTemplateHandler.EP_NAME)) {
    String textFromHandler = handler.getTemplateText(psiFile, fileText, nameWithoutExtension);
    if (textFromHandler != null) {
      fileText = textFromHandler;
      break;
    }
  }
  fileTemplateOptions.createNewTemplate(nameWithoutExtension, extension, fileText);
  dialog.show();
}
 
Example 3
Source File: BaseBuildHandler.java    From CppTools with Apache License 2.0 6 votes vote down vote up
public static @Nullable BaseBuildHandler getBuildHandler(Project project, VirtualFile file) {
  if (file == null) return null;
  if (file.getName().equalsIgnoreCase(Communicator.MAKEFILE_FILE_NAME)) return new MakeBuildHandler(project, file);
  final String extension = file.getExtension();

  if (Communicator.VCPROJ_EXTENSION.equals(extension) || Communicator.DSP_EXTENSION.equals(extension) ||
      Communicator.DSW_EXTENSION.equals(extension) || Communicator.SLN_EXTENSION.equals(extension)
     ) {
    return new VisualStudioBuildHandler(project, file);
  }

  if (Communicator.MAK_EXTENSION.equals(extension)) {
    return new NMakeBuildHandler(project, file);
  }
  return null;
}
 
Example 4
Source File: BashFileTypeDetector.java    From BashSupport with Apache License 2.0 6 votes vote down vote up
@Nullable
public static FileType detect(@NotNull VirtualFile file, @Nullable CharSequence textContent) {
    if (textContent == null || file.getExtension() != null) {
        return null;
    }

    String content = textContent.toString();

    for (String shebang : VALID_SHEBANGS) {
        // more efficient would be to  check only at the beginning of the sample content,
        // but this would need smart whitespace stripping for now, this is good enough
        if (content.contains(shebang)) {
            return BashFileType.BASH_FILE_TYPE;
        }
    }

    return null;
}
 
Example 5
Source File: RunIdeConsoleAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
  Project project = e.getProject();
  Editor editor = e.getDataContext().getData(CommonDataKeys.EDITOR);
  VirtualFile virtualFile = e.getDataContext().getData(CommonDataKeys.VIRTUAL_FILE);
  if (project == null || editor == null || virtualFile == null) return;
  PsiDocumentManager.getInstance(project).commitAllDocuments();

  String extension = virtualFile.getExtension();
  if (extension != null && (engine == null || !engine.getFileExtensions().contains(extension))) {
    engine = IdeScriptEngineManager.getInstance().getEngineForFileExtension(extension, null);
  }
  if (engine == null) {
    LOG.warn("Script engine not found for: " + virtualFile.getName());
  }
  else {
    executeQuery(project, virtualFile, editor, engine);
  }
}
 
Example 6
Source File: CustomIconLoader.java    From intellij-extra-icons-plugin with MIT License 6 votes vote down vote up
public static ImageWrapper loadFromVirtualFile(VirtualFile virtualFile) throws IllegalArgumentException {
    if (virtualFile.getExtension() != null) {
        Image image;
        IconType iconType;
        byte[] fileContents;
        try {
            fileContents = virtualFile.contentsToByteArray();
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(fileContents);
            if (virtualFile.getExtension().equals("svg") && new String(fileContents).startsWith("<")) {
                iconType = IconType.SVG;
                image = SVGLoader.load(byteArrayInputStream, 1.0f);
            } else {
                iconType = IconType.IMG;
                image = ImageLoader.loadFromStream(byteArrayInputStream);
            }
        } catch (IOException ex) {
            throw new IllegalArgumentException("IOException while trying to load image.");
        }
        if (image == null) {
            throw new IllegalArgumentException("Could not load image properly.");
        }
        return new ImageWrapper(iconType, scaleImage(image), fileContents);
    }
    return null;
}
 
Example 7
Source File: FileStub.java    From Intellij-Plugin with Apache License 2.0 6 votes vote down vote up
@NotNull
@Override
public FileBasedIndex.InputFilter getInputFilter() {
    return new FileBasedIndex.FileTypeSpecificInputFilter() {
        @Override
        public void registerFileTypesUsedForIndexing(@NotNull Consumer<FileType> consumer) {
            consumer.consume(SpecFileType.INSTANCE);
            consumer.consume(ConceptFileType.INSTANCE);
        }

        @Override
        public boolean acceptInput(@NotNull VirtualFile virtualFile) {
            return virtualFile.getExtension() != null && GaugeUtil.isGaugeFile(virtualFile);
        }
    };
}
 
Example 8
Source File: PluginAdvertiserEditorNotificationProvider.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredReadAction
@Nullable
@Override
public EditorNotificationPanel createNotificationPanel(@Nonnull VirtualFile file, @Nonnull FileEditor fileEditor) {
  if (file.getFileType() != PlainTextFileType.INSTANCE && !(file.getFileType() instanceof AbstractFileType)) return null;

  final String extension = file.getExtension();
  if (extension == null) {
    return null;
  }

  if (myEnabledExtensions.contains(extension) || isIgnoredFile(file)) return null;

  UnknownExtension fileFeatureForChecking = new UnknownExtension(FileTypeFactory.FILE_TYPE_FACTORY_EP.getName(), file.getName());

  List<PluginDescriptor> allPlugins = PluginsAdvertiserHolder.getLoadedPluginDescriptors();

  Set<PluginDescriptor> byFeature = PluginsAdvertiser.findByFeature(allPlugins, fileFeatureForChecking);
  if (!byFeature.isEmpty()) {
    return createPanel(file, byFeature);

  }
  return null;
}
 
Example 9
Source File: RootType.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
public Image substituteIcon(@Nonnull Project project, @Nonnull VirtualFile file) {
  if (file.isDirectory()) return null;
  Language language = substituteLanguage(project, file);
  FileType fileType = LanguageUtil.getLanguageFileType(language);
  if (fileType == null) {
    String extension = file.getExtension();
    fileType = extension == null ? null : FileTypeManager.getInstance().getFileTypeByFileName(file.getNameSequence());
  }
  return fileType != null ? fileType.getIcon() : null;
}
 
Example 10
Source File: WeaveEditorProvider.java    From mule-intellij-plugins with Apache License 2.0 5 votes vote down vote up
@Override
public boolean accept(@NotNull Project project, @NotNull VirtualFile virtualFile) {
    boolean isWeaveFile = false;
    PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile);
    if (psiFile != null)
        isWeaveFile = (psiFile instanceof WeaveFile);
    else {
        List<String> extensions = WeaveFileType.getInstance().getExtensions();
        isWeaveFile = (virtualFile.getExtension() != null && extensions.contains(virtualFile.getExtension().toLowerCase()));
    }
    return isWeaveFile;
}
 
Example 11
Source File: PluginAdvertiserEditorNotificationProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
private boolean isIgnoredFile(@Nonnull VirtualFile virtualFile) {
  UnknownExtension extension = new UnknownExtension(FileTypeFactory.FILE_TYPE_FACTORY_EP, "*." + virtualFile.getExtension());

  if(myUnknownFeaturesCollector.isIgnored(extension)) {
    return true;
  }

  extension = new UnknownExtension(FileTypeFactory.FILE_TYPE_FACTORY_EP, virtualFile.getName());
  if(myUnknownFeaturesCollector.isIgnored(extension)) {
    return true;
  }

  return false;
}
 
Example 12
Source File: PluginAdvertiserEditorNotificationProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private EditorNotificationPanel createPanel(VirtualFile virtualFile, Set<PluginDescriptor> plugins) {
  String extension = virtualFile.getExtension();

  final EditorNotificationPanel panel = new EditorNotificationPanel();
  panel.setText(IdeBundle.message("plugin.advestiser.notification.text", plugins.size()));
  final PluginDescriptor disabledPlugin = getDisabledPlugin(plugins.stream().map(x -> x.getPluginId().getIdString()).collect(Collectors.toSet()));
  if (disabledPlugin != null) {
    panel.createActionLabel("Enable " + disabledPlugin.getName() + " plugin", () -> {
      myEnabledExtensions.add(extension);
      consulo.container.plugin.PluginManager.enablePlugin(disabledPlugin.getPluginId().getIdString());
      myNotifications.updateAllNotifications();
      PluginManagerMain.notifyPluginsWereUpdated("Plugin was successfully enabled", null);
    });
  }
  else {
    panel.createActionLabel(IdeBundle.message("plugin.advestiser.notification.install.link", plugins.size()), () -> {
      final PluginsAdvertiserDialog advertiserDialog = new PluginsAdvertiserDialog(null, new ArrayList<>(plugins));
      advertiserDialog.show();
      if (advertiserDialog.isUserInstalledPlugins()) {
        myEnabledExtensions.add(extension);
        myNotifications.updateAllNotifications();
      }
    });
  }

  panel.createActionLabel("Ignore by file name", () -> {
    myUnknownFeaturesCollector.ignoreFeature(new UnknownExtension(FileTypeFactory.FILE_TYPE_FACTORY_EP, virtualFile.getName()));
    myNotifications.updateAllNotifications();
  });

  panel.createActionLabel("Ignore by extension", () -> {
    myUnknownFeaturesCollector.ignoreFeature(new UnknownExtension(FileTypeFactory.FILE_TYPE_FACTORY_EP, "*." + virtualFile.getExtension()));
    myNotifications.updateAllNotifications();
  });

  return panel;
}
 
Example 13
Source File: TemplateUtil.java    From idea-php-shopware-plugin with MIT License 5 votes vote down vote up
/**
 * Find on Theme.php scope: "foo/Theme.php" => "frontend/plugins/payment/sepa"
 * Find on Plugin.php scope: "foo/Plugin.php" => "Resources/views/frontend/plugins/payment/sepa"
 */
@Nullable
public static String getTemplateNameViaPath(@NotNull Project project, @NotNull VirtualFile virtualFile) {
    String fileNamespaceViaPath = SnippetUtil.getFileNamespaceViaPath(project, virtualFile);

    return fileNamespaceViaPath != null
        ? fileNamespaceViaPath + "." + virtualFile.getExtension()
        : null;
}
 
Example 14
Source File: ExternalToolContentExternalizer.java    From consulo with Apache License 2.0 5 votes vote down vote up
private String chooseExtension() {
  DiffContent content = getContent();
  VirtualFile contentFile = content.getFile();
  String extension;
  if (contentFile != null) {
    extension = "." + contentFile.getExtension();
  }
  else {
    FileType contentType = content.getContentType();
    if (contentType == null) contentType = DiffUtil.chooseContentTypes(myRequest.getContents())[myIndex];
    extension = contentType != null ?  "." + contentType.getDefaultExtension() : null;
  }
  return extension;
}
 
Example 15
Source File: ActionVisibilityHelper.java    From android-codegenerator-plugin-intellij with Apache License 2.0 4 votes vote down vote up
private boolean hasCorrectExtension(VirtualFile data) {
    return data.getExtension() != null && data.getExtension().equals(extension);
}
 
Example 16
Source File: Communicator.java    From CppTools with Apache License 2.0 4 votes vote down vote up
public static boolean isCFile(VirtualFile file) {
  final String extension = file.getExtension();
  return "c".equals(extension);
}
 
Example 17
Source File: HaxeModuleBuilder.java    From intellij-haxe with Apache License 2.0 4 votes vote down vote up
private void createHelloWorldIfEligible(Module module) {
  ModuleRootManager rootManager = ModuleRootManager.getInstance(module);
  VirtualFile[] srcDirs = rootManager.getSourceRoots();
  VirtualFile[] rootDirs = rootManager.getContentRoots();
  if(rootDirs.length != 1 || srcDirs.length != 1) {
    return;
  }

  VirtualFile root = rootDirs[0];
  VirtualFile src = srcDirs[0];

  if(src.getChildren().length != 0) {
    return;
  }
  for(VirtualFile item:root.getChildren()) {
    if(item.getExtension() == "hxml") {
      return;
    }
  }


  ApplicationManager.getApplication().runWriteAction(new Runnable() {
    @Override
    public void run() {
      try {
        VirtualFile mainHx = src.createChildData(this, "Main.hx");
        String mainHxSource = "class Main {\n"
          + "    static public function main() {\n"
          + "        trace(\"Hello, world!\");\n"
          + "    }\n"
          + "}\n";
        mainHx.setBinaryContent(mainHxSource.getBytes(StandardCharsets.UTF_8));

        VirtualFile buildHxml = root.createChildData(this, "build.hxml");
        String buildHxmlSource = "-cp src\n"
          + "-D analyzer-optimize\n"
          + "-main Main\n"
          + "--interp";
        buildHxml.setBinaryContent(buildHxmlSource.getBytes(StandardCharsets.UTF_8));

        createDefaultRunConfiguration(module, buildHxml.getPath());

        FileEditorManager editorManager = FileEditorManager.getInstance(module.getProject());
        editorManager.openFile(mainHx, true);

      } catch (IOException e) {
      }
    }
  });
}
 
Example 18
Source File: ScratchUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nullable
public static FileType getFileTypeFromName(@Nonnull VirtualFile file) {
  String extension = file.getExtension();
  return extension == null ? null : FileTypeManager.getInstance().getFileTypeByExtension(extension);
}
 
Example 19
Source File: RTMergerTreeStructureProvider.java    From react-templates-plugin with MIT License 4 votes vote down vote up
private static boolean hasExt(VirtualFile file, String ext) {
    return file != null && file.getExtension() != null && file.getExtension().equals(ext);
}
 
Example 20
Source File: ViewOfflineResultsAction.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent event) {
  final Project project = event.getData(CommonDataKeys.PROJECT);

  LOG.assertTrue(project != null);

  final FileChooserDescriptor descriptor = new FileChooserDescriptor(false, true, false, false, false, false){
    @Override
    public Image getIcon(VirtualFile file) {
      if (file.isDirectory()) {
        if (file.findChild(InspectionApplication.DESCRIPTIONS + ".xml") != null) {
          return AllIcons.Nodes.InspectionResults;
        }
      }
      return super.getIcon(file);
    }
  };
  descriptor.setTitle("Select Path");
  descriptor.setDescription("Select directory which contains exported inspections results");
  final VirtualFile virtualFile = FileChooser.chooseFile(descriptor, project, null);
  if (virtualFile == null || !virtualFile.isDirectory()) return;

  final Map<String, Map<String, Set<OfflineProblemDescriptor>>> resMap =
          new HashMap<String, Map<String, Set<OfflineProblemDescriptor>>>();
  final String [] profileName = new String[1];
  final Runnable process = new Runnable() {
    @Override
    public void run() {
      final VirtualFile[] files = virtualFile.getChildren();
      try {
        for (final VirtualFile inspectionFile : files) {
          if (inspectionFile.isDirectory()) continue;
          final String shortName = inspectionFile.getNameWithoutExtension();
          final String extension = inspectionFile.getExtension();
          if (shortName.equals(InspectionApplication.DESCRIPTIONS)) {
            profileName[0] = ApplicationManager.getApplication().runReadAction(
                    new Computable<String>() {
                      @Override
                      @Nullable
                      public String compute() {
                        return OfflineViewParseUtil.parseProfileName(inspectionFile);
                      }
                    }
            );
          }
          else if (XML_EXTENSION.equals(extension)) {
            resMap.put(shortName, ApplicationManager.getApplication().runReadAction(
                    new Computable<Map<String, Set<OfflineProblemDescriptor>>>() {
                      @Override
                      public Map<String, Set<OfflineProblemDescriptor>> compute() {
                        return OfflineViewParseUtil.parse(inspectionFile);
                      }
                    }
            ));
          }
        }
      }
      catch (final Exception e) {  //all parse exceptions
        SwingUtilities.invokeLater(new Runnable() {
          @Override
          public void run() {
            Messages.showInfoMessage(e.getMessage(), InspectionsBundle.message("offline.view.parse.exception.title"));
          }
        });
        throw new ProcessCanceledException(); //cancel process
      }
    }
  };
  ProgressManager.getInstance().runProcessWithProgressAsynchronously(project, InspectionsBundle.message("parsing.inspections.dump.progress.title"), process, new Runnable() {
    @Override
    public void run() {
      SwingUtilities.invokeLater(new Runnable(){
        @Override
        public void run() {
          final String name = profileName[0];
          showOfflineView(project, name, resMap,
                          InspectionsBundle.message("offline.view.title") +
                          " (" + (name != null ? name : InspectionsBundle.message("offline.view.editor.settings.title")) +")");
        }
      });
    }
  }, null, new PerformAnalysisInBackgroundOption(project));
}