com.intellij.openapi.vfs.VirtualFile Java Examples

The following examples show how to use com.intellij.openapi.vfs.VirtualFile. 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: RenameResponseRefTest.java    From intellij-swagger with 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 #2
Source File: BuckTargetCompletionContributor.java    From buck with 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 #3
Source File: FilePathRelativeToProjectRootMacro.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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 #4
Source File: IntellijReferencePoint.java    From saros with 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 #5
Source File: ModuleCompilerPathsManagerImpl.java    From consulo with 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 #6
Source File: GradleToolDelegate.java    From intellij-quarkus with Eclipse Public License 2.0 6 votes vote down vote up
@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 #7
Source File: RoboVmSdkType.java    From robovm-idea with 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 #8
Source File: ProjectViewNode.java    From consulo with 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 #9
Source File: FileSystemTreeImpl.java    From consulo with 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 #10
Source File: LSPAnnotator.java    From lsp4intellij with 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 #11
Source File: FileDocumentManagerImplTest.java    From consulo with 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 #12
Source File: RouteHelper.java    From idea-php-symfony2-plugin with 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 #13
Source File: Path.java    From WebStormRequireJsPlugin with 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 #14
Source File: ImportProjectOpenProcessor.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public Image getIcon(@Nonnull VirtualFile file) {
  File ioFile = VfsUtil.virtualToIoFile(file);
  for (ModuleImportProvider provider : myProviders) {
    if (provider.canImport(ioFile)) {
      return provider.getIcon();
    }
  }
  return null;
}
 
Example #15
Source File: JsonSchemaInspection.java    From intellij-swagger with MIT License 5 votes vote down vote up
private PsiElementVisitor createVisitor(
    final String schemaFileName,
    final ProblemsHolder holder,
    final LocalInspectionToolSession session,
    final PsiFile file) {

  JsonValue root =
      file instanceof JsonFile
          ? ObjectUtils.tryCast(file.getFirstChild(), JsonValue.class)
          : null;
  if (root == null) return PsiElementVisitor.EMPTY_VISITOR;

  JsonSchemaService service = JsonSchemaService.Impl.get(file.getProject());

  final URL url = ResourceUtil.getResource(getClass(), "schemas", schemaFileName);
  final VirtualFile virtualFile = VfsUtil.findFileByURL(url);

  final JsonSchemaObject schema = service.getSchemaObjectForSchemaFile(virtualFile);

  return new JsonElementVisitor() {
    @Override
    public void visitElement(PsiElement element) {
      if (element == root) {
        final JsonLikePsiWalker walker = JsonLikePsiWalker.getWalker(element, schema);
        if (walker == null) return;

        JsonComplianceCheckerOptions options = new JsonComplianceCheckerOptions(false);

        new JsonSchemaComplianceChecker(schema, holder, walker, session, options)
            .annotate(element);
      }
    }
  };
}
 
Example #16
Source File: UnusedRefTest.java    From intellij-swagger with MIT License 5 votes vote down vote up
public void testUnusedDefinitionWhereDefinitionsAreInRoot() {
  final VirtualFile virtualFile =
      myFixture.copyFileToProject(
          "validator/field/unused_definition/json/unused_definition_in_root.json",
          "definitions.json");
  final VirtualFile swaggerFile =
      myFixture.copyFileToProject(
          "validator/field/unused_definition/json/unused_definition_in_root_swagger.json",
          "swagger.json");
  myFixture.configureFromExistingVirtualFile(swaggerFile);
  myFixture.testHighlighting(true, false, true, virtualFile);
}
 
Example #17
Source File: TFSCheckinEnvironmentTest.java    From azure-devops-intellij with MIT License 5 votes vote down vote up
private List<VirtualFile> setupAdd() {
    VirtualFile mockVirtualFile1 = mock(VirtualFile.class);
    VirtualFile mockVirtualFile2 = mock(VirtualFile.class);
    when(mockVirtualFile1.getPath()).thenReturn(filePaths.get(0));
    when(mockVirtualFile2.getPath()).thenReturn(filePaths.get(1));
    when(mockVirtualFile1.isValid()).thenReturn(true);
    when(mockVirtualFile2.isValid()).thenReturn(true);

    when(VersionControlPath.getVirtualFile(filePaths.get(0))).thenReturn(mockVirtualFile1);
    when(VersionControlPath.getVirtualFile(filePaths.get(1))).thenReturn(mockVirtualFile2);

    return ImmutableList.of(mockVirtualFile1, mockVirtualFile2);
}
 
Example #18
Source File: UndoManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void addAffectedFiles(@Nonnull VirtualFile... files) {
  if (!isInsideCommand()) {
    LOG.error("Must be called inside command");
    return;
  }
  List<DocumentReference> refs = new ArrayList<>(files.length);
  for (VirtualFile each : files) {
    refs.add(DocumentReferenceManager.getInstance().create(each));
  }
  myCurrentMerger.addAdditionalAffectedDocuments(refs);
}
 
Example #19
Source File: FlutterSdk.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Runs flutter create and waits for it to finish.
 * <p>
 * Shows output in a console unless the module parameter is null.
 * <p>
 * Notifies process listener if one is specified.
 * <p>
 * Returns the PubRoot if successful.
 */
@Nullable
public PubRoot createFiles(@NotNull VirtualFile baseDir, @Nullable Module module, @Nullable ProcessListener listener,
                           @Nullable FlutterCreateAdditionalSettings additionalSettings) {
  final Process process;
  if (module == null) {
    process = flutterCreate(baseDir, additionalSettings).start(null, listener);
  }
  else {
    process = flutterCreate(baseDir, additionalSettings).startInModuleConsole(module, null, listener);
  }
  if (process == null) {
    return null;
  }

  try {
    if (process.waitFor() != 0) {
      return null;
    }
  }
  catch (InterruptedException e) {
    FlutterUtils.warn(LOG, e);
    return null;
  }

  if (EdtInvocationManager.getInstance().isEventDispatchThread()) {
    VfsUtil.markDirtyAndRefresh(false, true, true, baseDir); // Need this for AS.
  }
  else {
    baseDir.refresh(false, true); // The current thread must NOT be in a read action.
  }
  return PubRoot.forDirectory(baseDir);
}
 
Example #20
Source File: ScratchFileServiceImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public VirtualFile findFile(@Nonnull RootType rootType, @Nonnull String pathName, @Nonnull Option option) throws IOException {
  ApplicationManager.getApplication().assertReadAccessAllowed();

  String fullPath = getRootPath(rootType) + "/" + pathName;
  if (option != Option.create_new_always) {
    VirtualFile file = LocalFileSystem.getInstance().findFileByPath(fullPath);
    if (file != null && !file.isDirectory()) return file;
    if (option == Option.existing_only) return null;
  }
  String ext = PathUtil.getFileExtension(pathName);
  String fileNameExt = PathUtil.getFileName(pathName);
  String fileName = StringUtil.trimEnd(fileNameExt, ext == null ? "" : "." + ext);
  AccessToken token = ApplicationManager.getApplication().acquireWriteActionLock(getClass());
  try {
    VirtualFile dir = VfsUtil.createDirectories(PathUtil.getParentPath(fullPath));
    if (option == Option.create_new_always) {
      return VfsUtil.createChildSequent(LocalFileSystem.getInstance(), dir, fileName, StringUtil.notNullize(ext));
    }
    else {
      return dir.createChildData(LocalFileSystem.getInstance(), fileNameExt);
    }
  }
  finally {
    token.finish();
  }
}
 
Example #21
Source File: VcsLogRefresherImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void loadLogAndRefs(@Nonnull Collection<VirtualFile> roots,
                            @Nonnull Map<VirtualFile, CompressedRefs> prevRefs,
                            int commitCount) throws VcsException {
  LogInfo logInfo = loadRecentData(prepareRequirements(roots, commitCount, prevRefs));
  for (VirtualFile root : roots) {
    myLoadedInfo.put(root, logInfo.getCommits(root));
    myLoadedInfo.put(root, logInfo.getRefs().get(root));
  }
}
 
Example #22
Source File: ToggleReadOnlyAttributePanel.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public String getTooltipText() {
  VirtualFile virtualFile = getCurrentFile();
  int writable = virtualFile == null || virtualFile.isWritable() ? 1 : 0;
  int readonly = writable == 1 ? 0 : 1;
  return ActionsBundle.message("action.ToggleReadOnlyAttribute.files", readonly, writable, 1, 0);
}
 
Example #23
Source File: ChangelistBuilderStatusVisitor.java    From azure-devops-intellij with MIT License 5 votes vote down vote up
public void unversioned(final @NotNull FilePath localPath, final boolean localItemExists, final @NotNull ServerStatus serverStatus) {
    if (localItemExists) {
        final VirtualFile filePath = localPath.getVirtualFile();
        if (filePath == null) {
            // for files that were deleted w/o using the VCS
            changelistBuilder.processLocallyDeletedFile(localPath);
        } else {
            changelistBuilder.processUnversionedFile(filePath);
        }
    }
}
 
Example #24
Source File: ExcludeFromCompileAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@javax.annotation.Nullable
private VirtualFile getSelectedFile() {
  final ErrorTreeNodeDescriptor descriptor = myErrorTreeView.getSelectedNodeDescriptor();
  ErrorTreeElement element = descriptor != null? descriptor.getElement() : null;
  if (element != null && !(element instanceof GroupingElement)) {
    NodeDescriptor parent = descriptor.getParentDescriptor();
    if (parent instanceof ErrorTreeNodeDescriptor) {
      element = ((ErrorTreeNodeDescriptor)parent).getElement();
    }
  }
  return element instanceof GroupingElement? ((GroupingElement)element).getFile() : null;
}
 
Example #25
Source File: FileParentDirMacro.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public String expand(DataContext dataContext, String... args) throws ExecutionCancelledException {
  if(args.length == 0 || StringUtil.isEmpty(args[0])) {
    return expand(dataContext);
  }
  String param = args[0];
  VirtualFile vFile = getVirtualDirOrParent(dataContext);
  while (vFile != null && !param.equalsIgnoreCase(vFile.getName())) {
    vFile = vFile.getParent();
  }
  return parentPath(vFile);
}
 
Example #26
Source File: BazelTestFields.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Returns the file or directory containing the tests to run, or null if it doesn't exist.
 */
@Nullable
public VirtualFile getFile() {
  final String path = getEntryFile();
  if (path == null) return null;
  return LocalFileSystem.getInstance().findFileByPath(path);
}
 
Example #27
Source File: VcsLogRefresherImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private Map<VirtualFile, VcsLogProvider.Requirements> prepareRequirements(@Nonnull Collection<VirtualFile> roots,
                                                                          int commitCount,
                                                                          @Nonnull Map<VirtualFile, CompressedRefs> prevRefs) {
  Map<VirtualFile, VcsLogProvider.Requirements> requirements = ContainerUtil.newHashMap();
  for (VirtualFile root : roots) {
    requirements.put(root, new RequirementsImpl(commitCount, true, prevRefs.get(root).getRefs()));
  }
  return requirements;
}
 
Example #28
Source File: AssetDirectoryReader.java    From idea-php-symfony2-plugin with 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);
}
 
Example #29
Source File: FilePathImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static FilePathImpl create(File selectedFile, boolean isDirectory) {
  if (selectedFile == null) {
    return null;
  }

  LocalFileSystem lfs = LocalFileSystem.getInstance();

  VirtualFile virtualFile = lfs.findFileByIoFile(selectedFile);
  if (virtualFile != null) {
    return new FilePathImpl(virtualFile);
  }

  return createForDeletedFile(selectedFile, isDirectory);
}
 
Example #30
Source File: GoToHashOrRefPopup.java    From consulo with Apache License 2.0 5 votes vote down vote up
private VcsRefDescriptor(@Nonnull Project project,
                         @Nonnull VcsLogColorManager manager,
                         @Nonnull Comparator<VcsRef> comparator,
                         @Nonnull Collection<VirtualFile> roots) {
  myProject = project;
  myColorManager = manager;
  myReferenceComparator = comparator;

  for (VirtualFile root : roots) {
    String text = VcsImplUtil.getShortVcsRootName(myProject, root);
    myCachedRootNames.put(root, text);
  }
}