Java Code Examples for com.intellij.openapi.vfs.VirtualFile

The following examples show how to use com.intellij.openapi.vfs.VirtualFile. 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
@Override
public void processImport(Module module) {
    Project project = module.getProject();
    File gradleFile = null;

    for(VirtualFile virtualFile : ModuleRootManager.getInstance(module).getContentRoots()) {
        File baseDir = VfsUtilCore.virtualToIoFile(virtualFile);
        File file = new File(baseDir, "build.gradle");
        if (file.exists()) {
            gradleFile = file;
            break;
        }
    }

    if (gradleFile != null) {
        ProjectImportProvider gradleProjectImportProvider = getGradleProjectImportProvider();
        ProjectImportBuilder gradleProjectImportBuilder = gradleProjectImportProvider.getBuilder();
        AddModuleWizard wizard = new AddModuleWizard(project, gradleFile.getPath(), new ProjectImportProvider[]{gradleProjectImportProvider});
        if (wizard.getStepCount() == 0 || wizard.showAndGet()) {
            gradleProjectImportBuilder.commit(project, (ModifiableModuleModel)null, (ModulesProvider)null);
        }
    }
}
 
Example 2
Source Project: consulo   Source File: FileSystemTreeImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
private static FileElement getFileElementFor(@Nonnull VirtualFile file) {
  VirtualFile selectFile;

  if ((file.getFileSystem() instanceof ArchiveFileSystem) && file.getParent() == null) {
    selectFile = ArchiveVfsUtil.getVirtualFileForJar(file);
    if (selectFile == null) {
      return null;
    }
  }
  else {
    selectFile = file;
  }

  return new FileElement(selectFile, selectFile.getName());
}
 
Example 3
Source Project: consulo   Source File: FileDocumentManagerImplTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testUnsavedDocument_DoNotGC() throws Exception {
  final VirtualFile file = createFile();
  Document document = myDocumentManager.getDocument(file);
  int idCode = System.identityHashCode(document);
  assertNotNull(file.toString(), document);
  WriteCommandAction.runWriteCommandAction(myProject, new Runnable() {
    @Override
    public void run() {
      myDocumentManager.getDocument(file).insertString(0, "xxx");
    }
  });

  //noinspection UnusedAssignment
  document = null;

  System.gc();
  System.gc();

  document = myDocumentManager.getDocument(file);
  assertEquals(idCode, System.identityHashCode(document));
}
 
Example 4
Source Project: idea-php-symfony2-plugin   Source File: RouteHelper.java    License: MIT License 6 votes vote down vote up
@NotNull
public static Collection<Route> getRoute(@NotNull Project project, @NotNull String routeName) {
    Map<String, Route> compiledRoutes = RouteHelper.getCompiledRoutes(project);
    if(compiledRoutes.containsKey(routeName)) {
        return Collections.singletonList(compiledRoutes.get(routeName));
    }

    Collection<Route> routes = new ArrayList<>();

    Collection<VirtualFile> routeFiles = FileBasedIndex.getInstance().getContainingFiles(RoutesStubIndex.KEY, routeName, GlobalSearchScope.allScope(project));
    for(StubIndexedRoute route: FileBasedIndex.getInstance().getValues(RoutesStubIndex.KEY, routeName, GlobalSearchScope.filesScope(project, routeFiles))) {
        routes.add(new Route(route));
    }

    return routes;
}
 
Example 5
Source Project: WebStormRequireJsPlugin   Source File: Path.java    License: MIT License 6 votes vote down vote up
@Nullable
protected PsiElement probeResolvePackage() {
    for (Package pkg : component.packageConfig.packages) {
        if (this.getPath().startsWith(pkg.name)) {
            VirtualFile targetFile;
            String moduleFilePath;
            if (this.getPath().equals(pkg.name)) {
                moduleFilePath = pkg.main;
            } else {
                moduleFilePath = this.getPath().replace(pkg.name, "");
            }

            targetFile = component.getBaseUrlPath(false)
                    .findFileByRelativePath(pkg.location + "/" + moduleFilePath + ".js");
            if (null != targetFile) {
                return getPsiManager().findFile(targetFile);
            }
        }
    }

    return null;
}
 
Example 6
Source Project: lsp4intellij   Source File: LSPAnnotator.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public Object collectInformation(@NotNull PsiFile file, @NotNull Editor editor, boolean hasErrors) {

    try {
        VirtualFile virtualFile = file.getVirtualFile();

        // If the file is not supported, we skips the annotation by returning null.
        if (!FileUtils.isFileSupported(virtualFile) || !IntellijLanguageClient.isExtensionSupported(virtualFile)) {
            return null;
        }
        String uri = FileUtils.VFSToURI(virtualFile);
        EditorEventManager eventManager = EditorEventManagerBase.forUri(uri);

        // If the diagnostics list is locked, we need to skip annotating the file.
        if (eventManager == null || !(eventManager.isDiagnosticSyncRequired() || eventManager.isCodeActionSyncRequired())) {
            return null;
        }
        return RESULT;
    } catch (Exception e) {
        return null;
    }
}
 
Example 7
Source Project: consulo   Source File: ProjectViewNode.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Collection<VirtualFile> getRoots() {
  Value value = getValue();

  if (value instanceof RootsProvider) {
    return ((RootsProvider)value).getRoots();
  }
  else if (value instanceof PsiFile) {
    PsiFile vFile = ((PsiFile)value).getContainingFile();
    if (vFile != null && vFile.getVirtualFile() != null) {
      return Collections.singleton(vFile.getVirtualFile());
    }
  }
  else if (value instanceof VirtualFile) {
    return Collections.singleton(((VirtualFile)value));
  }
  else if (value instanceof PsiFileSystemItem) {
    return Collections.singleton(((PsiFileSystemItem)value).getVirtualFile());
  }

  return Collections.emptyList();
}
 
Example 8
Source Project: robovm-idea   Source File: RoboVmSdkType.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void setupSdkRoots(Sdk sdk, Sdk jdk) {
    SdkModificator sdkModificator = sdk.getSdkModificator();
    sdkModificator.removeAllRoots();

    // add all class and source jars from the SDK lib/ folder
    for(File file: RoboVmPlugin.getSdkLibraries()) {
        VirtualFile virtualFile = JarFileSystem.getInstance().findLocalVirtualFileByPath(file.getAbsolutePath());
        sdkModificator.addRoot(virtualFile, file.getName().endsWith("-sources.jar")?  OrderRootType.SOURCES: OrderRootType.CLASSES);
    }

    // set the JDK version as the version string, otherwise
    // IDEA gets angry
    sdkModificator.setVersionString(jdk.getVersionString());

    // set the home path, we check this in createSdkIfNotExists
    sdkModificator.setHomePath(RoboVmPlugin.getSdkHome().getAbsolutePath());

    // commit changes and let IDEA handle the rest
    sdkModificator.commitChanges();
}
 
Example 9
@Override
public String expand(final DataContext dataContext) {
  final Project project = dataContext.getData(CommonDataKeys.PROJECT);
  if (project == null) {
    return null;
  }
  VirtualFile file = dataContext.getData(PlatformDataKeys.VIRTUAL_FILE);
  if (file == null) {
    return null;
  }
  final VirtualFile contentRoot = ProjectRootManager.getInstance(project).getFileIndex().getContentRootForFile(file);
  if (contentRoot == null) {
    return null;
  }
  return FileUtil.getRelativePath(getIOFile(contentRoot), getIOFile(file));
}
 
Example 10
Source Project: intellij-swagger   Source File: RenameResponseRefTest.java    License: MIT License 6 votes vote down vote up
public void
    testRenameExternalResponseDefinitionDeclarationWhereResponseDefinitionsAreNotInRoot() {
  final VirtualFile definitionsFile =
      myFixture.copyFileToProject(
          FILES_PATH + "response_definitions_not_in_root_with_caret.yaml", "responses.yaml");
  myFixture.copyFileToProject(
      FILES_PATH + "external_definition_response_definitions_not_in_root.yaml", "swagger.yaml");
  myFixture.configureFromExistingVirtualFile(definitionsFile);
  myFixture.renameElementAtCaret("newName");
  myFixture.checkResultByFile(
      "swagger.yaml",
      FILES_PATH + "external_definition_response_definitions_not_in_root_after.yaml",
      true);
  myFixture.checkResultByFile(
      "responses.yaml",
      FILES_PATH + "response_definitions_not_in_root_with_caret_after.yaml",
      true);
}
 
Example 11
Source Project: buck   Source File: BuckTargetCompletionContributor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Autocomplete when inside the target part of a relative-qualified extension file, e.g. {@code
 * ":ex" => ":ext.bzl"}.
 */
private void doTargetsForRelativeExtensionFile(
    VirtualFile virtualFile, String prefixToAutocomplete, CompletionResultSet result) {
  if (!prefixToAutocomplete.startsWith(":")) {
    return;
  }
  Matcher matcher = RELATIVE_TARGET_TO_EXTENSION_FILE_PATTERN.matcher(prefixToAutocomplete);
  if (!matcher.matches()) {
    return;
  }
  String path = matcher.group("path");
  VirtualFile dir = virtualFile.findFileByRelativePath("../" + path);
  if (dir == null || !dir.isDirectory()) {
    return;
  }
  String partial = matcher.group("partial");
  for (VirtualFile child : dir.getChildren()) {
    String name = child.getName();
    if (!name.startsWith(partial)) {
      continue;
    }
    if (child.isDirectory() || name.endsWith(".bzl")) {
      addResultForFile(result, child, path + name);
    }
  }
}
 
Example 12
Source Project: saros   Source File: IntellijReferencePoint.java    License: GNU General Public License v2.0 6 votes vote down vote up
public IntellijReferencePoint(@NotNull Project project, @NotNull VirtualFile virtualFile) {

    if (!project.isInitialized()) {
      throw new IllegalArgumentException("The given project must be initialized - " + project);
    }

    if (!virtualFile.exists()) {
      throw new IllegalArgumentException("The given virtual file must exist - " + virtualFile);

    } else if (!virtualFile.isDirectory()) {
      throw new IllegalArgumentException(
          "The given virtual file must be a directory - " + virtualFile);
    }

    this.project = project;
    this.virtualFile = virtualFile;
  }
 
Example 13
Source Project: consulo   Source File: ModuleCompilerPathsManagerImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
@Nullable
public String getCompilerOutputUrl(@Nonnull ContentFolderTypeProvider contentFolderType) {
  if (!myInheritOutput) {
    VirtualFilePointer virtualFilePointer = myVirtualFilePointers.get(contentFolderType.getId());
    if (virtualFilePointer != null) {
      return virtualFilePointer.getUrl();
    }
  }

  String backUrl = myCompilerConfiguration.getCompilerOutputUrl() + "/" + contentFolderType.getId().toLowerCase() + "/" + myModule.getName();

  VirtualFile compilerOutput = myCompilerConfiguration.getCompilerOutput();
  if (compilerOutput == null) {
    return backUrl;
  }
  VirtualFile outDir = compilerOutput.findFileByRelativePath(contentFolderType.getId().toLowerCase() + "/" + myModule.getName());
  return outDir != null ? outDir.getUrl() : backUrl;
}
 
Example 14
public void contentsChanged(@NotNull VirtualFileEvent event) {
            VirtualFile confFile = findPathInWebDir(settings.configFilePath);
            if (confFile == null || !confFile.exists() || !event.getFile().equals(confFile)) {
                return;
            }
            LOG.debug("RequireConfigVfsListener contentsChanged");
//            RequirejsProjectComponent.this.project.getComponent(RequirejsProjectComponent.class).parseRequirejsConfig();
            RequirejsProjectComponent.this.parseRequirejsConfig();
        }
 
Example 15
Source Project: p4ic4idea   Source File: FileConfigPart.java    License: Apache License 2.0 5 votes vote down vote up
private static Properties loadProps(@Nullable VirtualFile filePath) throws IOException {
    Properties props = new Properties();
    if (filePath != null) {
        try (InputStreamReader reader = new InputStreamReader(filePath.getInputStream(), filePath.getCharset())) {
            // The Perforce config file is NOT the same as a Java
            // config file.  Java config files will read the "\" as
            // an escape character, whereas the Perforce config file
            // will keep it.

            try (BufferedReader inp = new BufferedReader(reader)) {
                String line;
                while ((line = inp.readLine()) != null) {
                    int pos = line.indexOf('=');
                    if (pos > 0) {
                        final String key = line.substring(0, pos).trim();
                        final String value = line.substring(pos + 1).trim();
                        // NOTE: an empty value is a set value!
                        if (key.length() > 0) {
                            props.setProperty(key, value);
                        }
                    }
                }
            }
        }
    }
    LOG.debug("Loaded property file " + filePath + " keys " + props.keySet());
    return props;
}
 
Example 16
Source Project: consulo   Source File: AbstractFilePatchInProgress.java    License: Apache License 2.0 5 votes vote down vote up
public void setAutoBases(@Nonnull final Collection<VirtualFile> autoBases) {
  final String path = myPatch.getBeforeName() == null ? myPatch.getAfterName() : myPatch.getBeforeName();
  for (VirtualFile autoBase : autoBases) {
    final VirtualFile willBeBase = PathMerger.getBase(autoBase, path);
    if (willBeBase != null) {
      myAutoBases.add(willBeBase);
    }
  }
}
 
Example 17
private static boolean isProjectDirectory(@NotNull VirtualFile file, @Nullable Project project) {
  if (!file.isDirectory() || project == null) {
    return false;
  }

  final VirtualFile baseDir = project.getBaseDir();
  return baseDir != null && baseDir.getPath().equals(file.getPath());
}
 
Example 18
Source Project: intellij   Source File: CopyExternalProjectViewOption.java    License: Apache License 2.0 5 votes vote down vote up
private void chooseWorkspacePath() {
  FileChooserDescriptor descriptor =
      new FileChooserDescriptor(true, false, false, false, false, false)
          .withShowHiddenFiles(true) // Show root project view file
          .withHideIgnored(false)
          .withTitle("Select Project View File")
          .withDescription("Select a project view file to import.")
          .withFileFilter(
              virtualFile ->
                  ProjectViewStorageManager.isProjectViewFile(new File(virtualFile.getPath())));
  // File filters are broken for the native Mac file chooser.
  descriptor.setForcedToUseIdeaFileChooser(true);
  FileChooserDialog chooser =
      FileChooserFactory.getInstance().createFileChooser(descriptor, null, null);

  File startingLocation = null;
  String projectViewPath = getProjectViewPath();
  if (!projectViewPath.isEmpty()) {
    File fileLocation = new File(projectViewPath);
    if (fileLocation.exists()) {
      startingLocation = fileLocation;
    }
  }
  final VirtualFile[] files;
  if (startingLocation != null) {
    VirtualFile toSelect =
        LocalFileSystem.getInstance().refreshAndFindFileByPath(startingLocation.getPath());
    files = chooser.choose(null, toSelect);
  } else {
    files = chooser.choose(null);
  }
  if (files.length == 0) {
    return;
  }
  VirtualFile file = files[0];
  projectViewPathField.setText(file.getPath());
}
 
Example 19
Source Project: intellij-demandware   Source File: ISMLFileType.java    License: MIT License 5 votes vote down vote up
@Override
public String getCharset(@NotNull final VirtualFile file, @NotNull final byte[] content) {
    String charset = XmlCharsetDetector.extractXmlEncodingFromProlog(content);
    if (charset != null) return charset;
    @NonNls String strContent;
    try {
        strContent = new String(content, "ISO-8859-1");
    }
    catch (UnsupportedEncodingException e) {
        return null;
    }
    Charset c = HtmlUtil.detectCharsetFromMetaTag(strContent);
    return c == null ? null : c.name();
}
 
Example 20
Source Project: reasonml-idea-plugin   Source File: InferredTypesService.java    License: MIT License 5 votes vote down vote up
public static void queryForSelectedTextEditor(@NotNull Project project) {
    try {
        Editor selectedTextEditor = FileEditorManager.getInstance(project).getSelectedTextEditor();
        if (selectedTextEditor != null) {
            Document document = selectedTextEditor.getDocument();
            PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);
            if (psiFile instanceof FileBase && !FileHelper.isInterface(psiFile.getFileType())) {
                // Try to get the inferred types cached at the psi file user data
                VirtualFile sourceFile = psiFile.getVirtualFile();
                Application application = ApplicationManager.getApplication();

                SignatureProvider.InferredTypesWithLines sigContext = psiFile.getUserData(SignatureProvider.SIGNATURE_CONTEXT);
                InferredTypes signatures = sigContext == null ? null : sigContext.getTypes();
                if (signatures == null) {
                    FileType fileType = sourceFile.getFileType();
                    if (FileHelper.isCompilable(fileType)) {
                        InsightManager insightManager = ServiceManager.getService(project, InsightManager.class);

                        if (!DumbService.isDumb(project)) {
                            LOG.debug("Reading types from file", psiFile);
                            PsiFile cmtFile = findCmtFileFromSource(project, sourceFile.getNameWithoutExtension());
                            if (cmtFile != null) {
                                Path cmtPath = FileSystems.getDefault().getPath(cmtFile.getVirtualFile().getPath());
                                insightManager.queryTypes(sourceFile, cmtPath, types -> application
                                        .runReadAction(() -> annotatePsiFile(project, psiFile.getLanguage(), sourceFile, types)));
                            }
                        }
                    }
                } else {
                    LOG.debug("Signatures found in user data cache");
                    application.runReadAction(() -> annotatePsiFile(project, psiFile.getLanguage(), sourceFile, signatures));
                }
            }
        }
    } catch (Error e) {
        // might produce an AssertionError when project is being disposed, but the invokeLater still process that code
    }
}
 
Example 21
private InputStream getContents(Project project, Editor editor, VirtualFile file) throws IOException {
    editor = getEditor(project, editor, file);
    if (editor != null) {
        return new ByteArrayInputStream(getText(editor).getBytes());
    } else {
        return file.getInputStream();
    }
}
 
Example 22
Source Project: p4ic4idea   Source File: ConfigPartStack.java    License: Apache License 2.0 5 votes vote down vote up
ConfigPartStack(VirtualFile vcsRoot, ConfigConnectionController connectionController) {
    $$$setupUI$$$();
    this.vcsRoot = vcsRoot;
    this.connectionController = connectionController;
    SwingUtil.iconOnlyButton(myAddItemButton, ADD_ITEM, SwingUtil.ButtonType.MINOR);
    myAddItemButton.addActionListener(e -> showAddItemPopup());
}
 
Example 23
Source Project: consulo   Source File: ChangesViewManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void selectFile(@Nullable VirtualFile vFile) {
  if (vFile == null) return;
  Change change = ChangeListManager.getInstance(myProject).getChange(vFile);
  Object objectToFind = change != null ? change : vFile;

  DefaultMutableTreeNode root = (DefaultMutableTreeNode)myView.getModel().getRoot();
  DefaultMutableTreeNode node = TreeUtil.findNodeWithObject(root, objectToFind);
  if (node != null) {
    TreeUtil.selectNode(myView, node);
  }
}
 
Example 24
Source Project: intellij-haxe   Source File: HaxeImportOptimizer.java    License: Apache License 2.0 5 votes vote down vote up
@NotNull
@Override
public Runnable processFile(final PsiFile file) {
  VirtualFile vFile = file.getVirtualFile();
  if (vFile instanceof VirtualFileWindow) vFile = ((VirtualFileWindow)vFile).getDelegate();
  if (vFile == null || !ProjectRootManager.getInstance(file.getProject()).getFileIndex().isInSourceContent(vFile)) {
    return EmptyRunnable.INSTANCE;
  }

  return () -> optimizeImports(file);
}
 
Example 25
Source Project: CppTools   Source File: BasicFormatFilter.java    License: Apache License 2.0 5 votes vote down vote up
public BasicFormatResult(VirtualFile _file, int start, int end, int _line, int _column, boolean error) {
  super(start, end, createHyperLink(_file, _line, _column));
  file = _file;
  line = _line;
  column = _column;
  isError = error;
}
 
Example 26
Source Project: consulo   Source File: FileTypeManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
protected byte readFlagsFromCache(@Nonnull VirtualFile file) {
  boolean wasAutoDetectRun = false;
  byte status = 0;
  try (DataInputStream stream = autoDetectedAttribute.readAttribute(file)) {
    status = stream == null ? 0 : stream.readByte();
    wasAutoDetectRun = stream != null;
  }
  catch (IOException ignored) {

  }
  status = BitUtil.set(status, AUTO_DETECT_WAS_RUN_MASK, wasAutoDetectRun);

  return (byte)(status & (AUTO_DETECTED_AS_TEXT_MASK | AUTO_DETECTED_AS_BINARY_MASK | AUTO_DETECT_WAS_RUN_MASK));
}
 
Example 27
Source Project: consulo   Source File: IdeaGatewayTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testCreatingDirectory() throws Exception {
  String subSubDirPath = myRoot.getPath() + "/subDir/subSubDir";

  assertFalse(new File(subSubDirPath).exists());
  VirtualFile subDir = myGateway.findOrCreateFileSafely(subSubDirPath, true);

  assertNotNull(subDir);
  assertEquals(subSubDirPath, subDir.getPath());

  assertTrue(new File(subSubDirPath).exists());
}
 
Example 28
Source Project: consulo   Source File: IndividualPiecesStrategy.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void acceptPatch(TextFilePatch patch, Collection<VirtualFile> foundByName) {
  if (! mySucceeded) return;

  final Collection<VirtualFile> variants = filterVariants(patch, foundByName);

  if ((variants != null) && (! variants.isEmpty())) {
    final TextFilePatchInProgress textFilePatchInProgress = new TextFilePatchInProgress(patch, variants, myBaseDir);
    myResult.add(textFilePatchInProgress);
    registerFolderDecision(patch.getBeforeName(), textFilePatchInProgress.getBase());
  } else {
    mySucceeded = false;
  }
}
 
Example 29
Source Project: consulo   Source File: CompilerMessageImpl.java    License: Apache License 2.0 5 votes vote down vote up
public CompilerMessageImpl(Project project,
                           CompilerMessageCategory category,
                           String message,
                           @Nullable final VirtualFile file,
                           int row,
                           int column,
                           @Nullable final Navigatable navigatable) {
  myProject = project;
  myCategory = category;
  myNavigatable = navigatable;
  myMessage = message == null ? "" : message;
  myRow = row;
  myColumn = column;
  myFile = file;
}
 
Example 30
Source Project: idea-php-symfony2-plugin   Source File: AssetDirectoryReader.java    License: MIT License 5 votes vote down vote up
private boolean isValidFile(@NotNull VirtualFile virtualFile) {
    if (virtualFile.isDirectory()) {
        return false;
    }

    if(filterExtension.size() == 0) {
        return true;
    }

    String extension = virtualFile.getExtension();
    return extension != null && this.filterExtension.contains(extension);
}