Java Code Examples for com.intellij.openapi.vfs.VfsUtil#findFileByIoFile()

The following examples show how to use com.intellij.openapi.vfs.VfsUtil#findFileByIoFile() . 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: ImportFlutterModuleStep.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@NotNull
private static Validator.Result validateFlutterModuleLocation(String path) {
  VirtualFile file = VfsUtil.findFileByIoFile(new File(path), true);
  if (file == null) {
    return Validator.Result.fromNullableMessage("File not found");
  }
  if (!file.isDirectory()) {
    return Validator.Result.fromNullableMessage("Please select a " + DIRECTORY_NOUN + " containing a Flutter module");
  }
  PubRoot root = PubRoot.forDirectory(file);
  if (root == null || !root.isFlutterModule()) {
    return Validator.Result.fromNullableMessage("The selected " + DIRECTORY_NOUN + " is not a Flutter module");
  }
  // TODO(messick): Check for equivalent Android releases in both module and project.
  return Validator.Result.OK;
}
 
Example 2
Source File: FlutterModuleModel.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void linkNewModule() {
  Project hostProject = model.project().getValue();
  String hostPath = model.projectLocation().get();
  // If the module is not a direct child of the project root then this File() instance needs to be changed.
  // TODO(messick) Extend the new module wizard to allow nested directories, as Android Studio does using Gradle syntax.
  File flutterProject = new File(hostPath, model.projectName().get());
  VirtualFile flutterModuleDir = VfsUtil.findFileByIoFile(flutterProject, true);
  if (flutterModuleDir == null) {
    return; // Module creation failed; it was reported elsewhere.
  }
  addGradleToModule(flutterModuleDir);

  // Ensure Gradle sync runs to link in the new add-to-app module.
  AndroidUtils.scheduleGradleSync(hostProject);
  // TODO(messick) Generate run configs for release and debug. (If needed.)
}
 
Example 3
Source File: ImportFlutterModuleStep.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@NotNull
private static Validator.Result validateFlutterModuleLocation(String path) {
  VirtualFile file = VfsUtil.findFileByIoFile(new File(path), true);
  if (file == null) {
    return Validator.Result.fromNullableMessage("File not found");
  }
  if (!file.isDirectory()) {
    return Validator.Result.fromNullableMessage("Please select a " + DIRECTORY_NOUN + " containing a Flutter module");
  }
  PubRoot root = PubRoot.forDirectory(file);
  if (root == null || !root.isFlutterModule()) {
    return Validator.Result.fromNullableMessage("The selected " + DIRECTORY_NOUN + " is not a Flutter module");
  }
  // TODO(messick): Check for equivalent Android releases in both module and project.
  return Validator.Result.OK;
}
 
Example 4
Source File: TwigUtil.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@NotNull
public static Collection<VirtualFile> resolveAssetsFiles(@NotNull Project project, @NotNull String assetName, @NotNull String... fileTypes) {
    Collection<VirtualFile> virtualFiles = new HashSet<>();

    // {% javascripts [...] @jquery_js2'%}
    if(assetName.startsWith("@") && assetName.length() > 1) {
        TwigNamedAssetsServiceParser twigPathServiceParser = ServiceXmlParserFactory.getInstance(project, TwigNamedAssetsServiceParser.class);
        String assetNameShortcut = assetName.substring(1);
        if(twigPathServiceParser.getNamedAssets().containsKey(assetNameShortcut)) {
            for (String s : twigPathServiceParser.getNamedAssets().get(assetNameShortcut)) {
                VirtualFile fileByURL = VfsUtil.findFileByIoFile(new File(s), false);
                if(fileByURL != null) {
                    virtualFiles.add(fileByURL);
                }
            }
        }

    }

    virtualFiles.addAll(new AssetDirectoryReader(fileTypes, true).resolveAssetFile(project, assetName));

    return virtualFiles;
}
 
Example 5
Source File: ApplyPatchAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredUIAccess
public static Boolean showAndGetApplyPatch(@Nonnull final Project project, @Nonnull final File file) {
  VirtualFile vFile = VfsUtil.findFileByIoFile(file, true);
  String patchPath = file.getPath();
  if (vFile == null) {
    VcsNotifier.getInstance(project).notifyWeakError("Can't find patch file " + patchPath);
    return false;
  }
  if (!isPatchFile(file)) {
    VcsNotifier.getInstance(project).notifyWeakError("Selected file " + patchPath + " is not patch type file ");
    return false;
  }
  final ApplyPatchDifferentiatedDialog dialog = new ApplyPatchDifferentiatedDialog(project, new ApplyPatchDefaultExecutor(project),
                                                                                   Collections.emptyList(),
                                                                                   ApplyPatchMode.APPLY_PATCH_IN_MEMORY, vFile);
  dialog.setModal(true);
  return dialog.showAndGet();
}
 
Example 6
Source File: FileCopyPasteUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
public static List<VirtualFile> getVirtualFileListFromAttachedObject(Object attached) {
  List<VirtualFile> result;
  List<File> fileList = getFileListFromAttachedObject(attached);
  if (fileList.isEmpty()) {
    result = Collections.emptyList();
  }
  else {
    result = new ArrayList<>(fileList.size());
    for (File file : fileList) {
      VirtualFile virtualFile = VfsUtil.findFileByIoFile(file, true);
      if (virtualFile == null) continue;
      result.add(virtualFile);
      // detect and store file type for Finder-2-IDEA drag-n-drop
      virtualFile.getFileType();
    }
  }
  return result;
}
 
Example 7
Source File: DiffContentFactoryImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private static VirtualFile createTemporalFile(@javax.annotation.Nullable Project project,
                                              @Nonnull String prefix,
                                              @Nonnull String suffix,
                                              @Nonnull byte[] content) throws IOException {
  File tempFile = FileUtil.createTempFile(PathUtil.suggestFileName(prefix + "_", true, false),
                                          PathUtil.suggestFileName("_" + suffix, true, false), true);
  if (content.length != 0) {
    FileUtil.writeToFile(tempFile, content);
  }
  if (!tempFile.setWritable(false, false)) LOG.warn("Can't set writable attribute of temporal file");

  VirtualFile file = VfsUtil.findFileByIoFile(tempFile, true);
  if (file == null) {
    throw new IOException("Can't create temp file for revision content");
  }
  VfsUtil.markDirtyAndRefresh(true, true, true, file);
  return file;
}
 
Example 8
Source File: SwitchToHeaderOrSourceSearch.java    From intellij with Apache License 2.0 6 votes vote down vote up
@Nullable
private static OCFile correlateTestToHeader(OCFile file) {
  // Quickly check foo_test.cc -> foo.h as well. "getAssociatedFileWithSameName" only does
  // foo.cc <-> foo.h. However, if you do goto-related-symbol again, it will go from
  // foo.h -> foo.cc instead of back to foo_test.cc.
  PsiManager psiManager = PsiManager.getInstance(file.getProject());
  String pathWithoutExtension = FileUtil.getNameWithoutExtension(file.getVirtualFile().getPath());
  for (String testSuffix : PartnerFilePatterns.DEFAULT_PARTNER_SUFFIXES) {
    if (pathWithoutExtension.endsWith(testSuffix)) {
      String possibleHeaderName = StringUtil.trimEnd(pathWithoutExtension, testSuffix) + ".h";
      VirtualFile virtualFile = VfsUtil.findFileByIoFile(new File(possibleHeaderName), false);
      if (virtualFile != null) {
        PsiFile psiFile = psiManager.findFile(virtualFile);
        if (psiFile instanceof OCFile) {
          return (OCFile) psiFile;
        }
      }
    }
  }
  return null;
}
 
Example 9
Source File: ProjectUtil.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
@Nullable
public static VirtualFile findProjectBaseDir(@NotNull Project project) {
    String projectDir = project.getBasePath();
    if (projectDir == null) {
        projectDir = SystemProperties.getUserHome();
        if (projectDir == null) {
            projectDir = "/";
        }
    }
    return VfsUtil.findFileByIoFile(new File(projectDir), false);
}
 
Example 10
Source File: TwigPath.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
@Nullable
public VirtualFile getDirectory(@NotNull Project project) {
    if(!FileUtil.isAbsolute(path)) {
        return VfsUtil.findRelativeFile(path, ProjectUtil.getProjectDir(project));
    } else {
        VirtualFile fileByIoFile = VfsUtil.findFileByIoFile(new File(path), true);
        if(fileByIoFile != null) {
            return fileByIoFile;
        }
    }

    return null;
}
 
Example 11
Source File: MindMapDocumentEditor.java    From netbeans-mmd-plugin with Apache License 2.0 5 votes vote down vote up
private void addFileToElement(final File file, final AbstractElement element) {
  if (element != null) {
    final Topic topic = element.getModel();

    final VirtualFile theFile = VfsUtil.findFileByIoFile(file, true);
    if (theFile != null) {
      final File rootFolder = IdeaUtils.vfile2iofile(findRootFolderForEditedFile());
      final File theFileIo = IdeaUtils.vfile2iofile(theFile);

      final MMapURI theURI = isMakeRelativePath() ?
          new MMapURI(rootFolder, theFileIo, null) :
          new MMapURI(null, theFileIo, null); //NOI18N

      if (topic.getExtras().containsKey(ExtraType.FILE)) {
        if (!getDialogProvider()
            .msgConfirmOkCancel(null, BUNDLE.getString("MMDGraphEditor.addDataObjectToElement.confirmTitle"), BUNDLE.getString("MMDGraphEditor.addDataObjectToElement.confirmMsg"))) {
          return;
        }
      }

      topic.setExtra(new ExtraFile(theURI));
      this.mindMapPanel.doLayout();
      onMindMapModelChanged(this.mindMapPanel, true);
    } else {
      LOGGER.warn("Can't find VirtualFile for " + file);
    }
  }
}
 
Example 12
Source File: MindMapPanelControllerImpl.java    From netbeans-mmd-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public void openFile(@Nonnull final File file, final boolean preferSystemBrowser) {
  final VirtualFile virtualFile = VfsUtil.findFileByIoFile(file, true);
  if (preferSystemBrowser) {
    IdeaUtils.openInSystemViewer(this.dialogProvider, virtualFile);
  } else {
    final Document document = FileDocumentManager.getInstance().getDocument(virtualFile);
    if (document == null) {
      IdeaUtils.openInSystemViewer(this.dialogProvider, virtualFile);
    }
  }
}
 
Example 13
Source File: FilesystemUtil.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
/**
 * Try to find an "app" directory on configuration or on project directory in root
 * We also support absolute path in configuration
 */
@NotNull
public static Collection<VirtualFile> getAppDirectories(@NotNull Project project) {
    Collection<VirtualFile> virtualFiles = new HashSet<>();

    // find "app" folder on user settings
    String directoryToApp = Settings.getInstance(project).directoryToApp;

    if(FileUtil.isAbsolute(directoryToApp)) {
        // absolute dir given
        VirtualFile fileByIoFile = VfsUtil.findFileByIoFile(new File(directoryToApp), true);
        if(fileByIoFile != null) {
            virtualFiles.add(fileByIoFile);
        }
    } else {
        // relative path resolve
        VirtualFile globalDirectory = VfsUtil.findRelativeFile(
            ProjectUtil.getProjectDir(project),
            directoryToApp.replace("\\", "/").split("/")
        );

        if(globalDirectory != null) {
            virtualFiles.add(globalDirectory);
        }
    }

    // global "app" in root
    VirtualFile templates = VfsUtil.findRelativeFile(ProjectUtil.getProjectDir(project), "app");
    if(templates != null) {
        virtualFiles.add(templates);
    }

    return virtualFiles;
}
 
Example 14
Source File: DomainFileMap.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
@Nullable
public VirtualFile getFile() {
    File file = new File(this.getPath());

    if(!file.exists()) {
          return null;
    }

    return VfsUtil.findFileByIoFile(file, true);
}
 
Example 15
Source File: OpenProjectViewAction.java    From intellij with Apache License 2.0 5 votes vote down vote up
private static Optional<VirtualFile> getLocalProjectViewFile(Project project) {
  BlazeImportSettings importSettings =
      BlazeImportSettingsManager.getInstance(project).getImportSettings();
  File projectViewFile = new File(importSettings.getProjectViewFile());
  VirtualFile virtualFile = VfsUtil.findFileByIoFile(projectViewFile, true);
  return Optional.ofNullable(virtualFile);
}
 
Example 16
Source File: TranslationPsiParser.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
public void parse(File file) {
    VirtualFile virtualFile = VfsUtil.findFileByIoFile(file, true);
    if(virtualFile == null) {
        Symfony2ProjectComponent.getLogger().info("VfsUtil missing translation: " + file.getPath());
        return;
    }

    PsiFile psiFile;
    try {
        psiFile = PhpPsiElementFactory.createPsiFileFromText(this.project, StreamUtil.readText(virtualFile.getInputStream(), "UTF-8"));
    } catch (IOException e) {
        return;
    }

    if(psiFile == null) {
        return;
    }

    Symfony2ProjectComponent.getLogger().info("update translations: " + file.getPath());

    Collection<NewExpression> messageCatalogues = PsiTreeUtil.collectElementsOfType(psiFile, NewExpression.class);
    for(NewExpression newExpression: messageCatalogues) {
        ClassReference classReference = newExpression.getClassReference();
        if(classReference != null) {
            PsiElement constructorMethod = classReference.resolve();
            if(constructorMethod instanceof Method) {
                PhpClass phpClass = ((Method) constructorMethod).getContainingClass();
                if(phpClass != null && PhpElementsUtil.isInstanceOf(phpClass, "\\Symfony\\Component\\Translation\\MessageCatalogueInterface")) {
                    this.getTranslationMessages(newExpression);
                }
            }
        }
    }
}
 
Example 17
Source File: GitExcludesOutputParser.java    From idea-gitignore with MIT License 5 votes vote down vote up
/**
 * Parses output and returns {@link VirtualFile} instance of the GitFileType.
 *
 * @param text input data
 * @return excludes ignore file instance
 */
@Nullable
@Override
protected VirtualFile parseOutput(@NotNull final String text) {
    final String path = Utils.resolveUserDir(text);
    return StringUtil.isNotEmpty(path) ? VfsUtil.findFileByIoFile(new File(path), true) : null;
}
 
Example 18
Source File: PluginGeneratorUtil.java    From idea-php-shopware-plugin with MIT License 4 votes vote down vote up
public static void installPlugin(@NotNull Project project, @NotNull PluginGeneratorSettings settings) {

        // download cli tools, if not existing locally
        VirtualFile cliFile = getCliToolsPharFile(project);
        if (cliFile == null) {
            showErrorNotification(project, "No CLI-Tools phar found");
            return;
        }

        List<String> commands = generateCommand(settings);

        String[] myCommand = ArrayUtil.toStringArray(commands);

        final StringBuilder outputBuilder = new StringBuilder();
        try {
            OSProcessHandler processHandler = ScriptRunnerUtil.execute(myCommand[0], project.getBaseDir().getPath(), null, Arrays.copyOfRange(myCommand, 1, myCommand.length));

            processHandler.addProcessListener(new ProcessAdapter() {
                @Override
                public void onTextAvailable(@NotNull ProcessEvent event, @NotNull com.intellij.openapi.util.Key outputType) {
                    String text = event.getText();
                    outputBuilder.append(text);
                }
            });

            processHandler.startNotify();
            for (;;){
                boolean finished = processHandler.waitFor(CHECKING_TIMEOUT_IN_MILLISECONDS);
                if (finished) {
                    break;
                }
            }
        }
        catch (ExecutionException e) {
            showErrorNotification(project, e.getMessage());
            return;
        }

        String output = outputBuilder.toString();
        if (output.toLowerCase().contains("exception")) {

            String message = SymfonyInstallerUtil.formatExceptionMessage(output);
            if(message == null) {
                message = "The unexpected happens...";
            }

            showErrorNotification(project, message);
            return;
        }

        // delete cli tools
        FileUtil.delete(VfsUtil.virtualToIoFile(cliFile));

        // move into correct plugin folder
        String newDir = project.getBasePath() + "/engine/Shopware/Plugins/Local/" + settings.getNamespace() + "/" + settings.getPluginName();
        if (FileUtil.canWrite(newDir)) {
            return;
        }

        FileUtil.createDirectory(new File(newDir));
        FileUtil.moveDirWithContent(new File(project.getBasePath() + "/" + settings.getPluginName()), new File(newDir));

        // open bootstrap file
        VirtualFile fileByIoFile = VfsUtil.findFileByIoFile(new File(newDir + "/Bootstrap.php"), true);
        if(fileByIoFile == null) {
            return;
        }
        final PsiFile file = PsiManager.getInstance(project).findFile(fileByIoFile);
        if (file == null) {
            return;
        }
        IdeHelper.navigateToPsiElement(file);
    }
 
Example 19
Source File: TemplatePath.java    From idea-php-laravel-plugin with MIT License 3 votes vote down vote up
public VirtualFile getDirectory() {

        File file = new File(this.getPath());

        if(!file.exists()) {
            return null;
        }

        return VfsUtil.findFileByIoFile(file, true);
    }
 
Example 20
Source File: TemplatePath.java    From Thinkphp5-Plugin with MIT License 3 votes vote down vote up
public VirtualFile getDirectory() {

        File file = new File(this.getPath());

        if(!file.exists()) {
            return null;
        }

        return VfsUtil.findFileByIoFile(file, true);
    }