public void testHardLinks() throws Exception {
    if (!SystemInfo.isWindows && !SystemInfo.isUnix) {
      System.err.println(getName() + " skipped: " + SystemInfo.OS_NAME);
      return;
    }

    final boolean safeWrite = GeneralSettings.getInstance().isUseSafeWrite();
    final File dir = FileUtil.createTempDirectory("hardlinks.", ".dir", false);
    final SafeWriteRequestor requestor = new SafeWriteRequestor() {};
    try {
      GeneralSettings.getInstance().setUseSafeWrite(false);

      final File targetFile = new File(dir, "targetFile");
      assertTrue(targetFile.createNewFile());
      final File hardLinkFile =
          IoTestUtil.createHardLink(targetFile.getAbsolutePath(), "hardLinkFile");

      final VirtualFile file = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(targetFile);
      assertNotNull(file);
      file.setBinaryContent("hello".getBytes("UTF-8"), 0, 0, requestor);
      assertTrue(file.getLength() > 0);

      final VirtualFile check =
          LocalFileSystem.getInstance().refreshAndFindFileByIoFile(hardLinkFile);
      assertNotNull(check);
      assertEquals(file.getLength(), check.getLength());
      assertEquals("hello", VfsUtilCore.loadText(check));
    } finally {
      GeneralSettings.getInstance().setUseSafeWrite(safeWrite);
      FileUtil.delete(dir);
    }
  }
Example #2
0
  private void doStuff(String rootDir, String itemRepr, String itemName)
      throws FileNotFoundException {
    String patternName =
        getTestDataPath() + getTestRoot() + getTestName(true) + "/after/" + itemName;

    File patternFile = new File(patternName);

    PrintWriter writer;
    if (!patternFile.exists()) {
      writer = new PrintWriter(new FileOutputStream(patternFile));
      try {
        writer.print(itemRepr);
      } finally {
        writer.close();
      }

      System.out.println("Pattern not found, file " + patternName + " created.");

      LocalFileSystem.getInstance().refreshAndFindFileByIoFile(patternFile);
    }

    File graFile =
        new File(
            FileUtil.getTempDirectory() + File.separator + rootDir + File.separator + itemName);

    writer = new PrintWriter(new FileOutputStream(graFile));
    try {
      writer.print(itemRepr);
    } finally {
      writer.close();
    }

    LocalFileSystem.getInstance().refreshAndFindFileByIoFile(graFile);
    FileDocumentManager.getInstance().saveAllDocuments();
  }
  protected void setupRootModel(
      final String testDir, final VirtualFile[] sourceDir, final String sdkName) {
    VirtualFile projectDir =
        LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(testDir));
    assertNotNull("could not find project dir " + testDir, projectDir);
    sourceDir[0] = projectDir.findChild("src");
    if (sourceDir[0] == null) {
      sourceDir[0] = projectDir;
    }
    final ModuleRootManager rootManager = ModuleRootManager.getInstance(myModule);
    final ModifiableRootModel rootModel = rootManager.getModifiableModel();
    rootModel.clear();
    // configure source and output path
    final ContentEntry contentEntry = rootModel.addContentEntry(projectDir);
    contentEntry.addSourceFolder(sourceDir[0], false);
    ext_src =
        LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(testDir + "/ext_src"));
    if (ext_src != null) {
      contentEntry.addSourceFolder(ext_src, false);
    }

    // IMPORTANT! The jdk must be obtained in a way it is obtained in the normal program!
    // ProjectJdkEx jdk = ProjectJdkTable.getInstance().getInternalJdk();

    rootModel.setSdk(getTestProjectSdk());

    rootModel.commit();
  }
Example #4
0
 @Nullable
 public static VirtualFile findRefreshFileOrLog(@NotNull String absolutePath) {
   VirtualFile file = LocalFileSystem.getInstance().findFileByPath(absolutePath);
   if (file == null) {
     file = LocalFileSystem.getInstance().refreshAndFindFileByPath(absolutePath);
   }
   if (file == null) {
     LOG.warn("VirtualFile not found for " + absolutePath);
   }
   return file;
 }
  public void testChildrenAccessedButNotCached() throws Exception {
    File dir = createTempDirectory(false);
    ManagingFS managingFS = ManagingFS.getInstance();

    VirtualFile vFile =
        LocalFileSystem.getInstance()
            .refreshAndFindFileByPath(dir.getPath().replace(File.separatorChar, '/'));
    assertNotNull(vFile);
    assertFalse(managingFS.areChildrenLoaded(vFile));
    assertFalse(managingFS.wereChildrenAccessed(vFile));

    File child = new File(dir, "child");
    boolean created = child.createNewFile();
    assertTrue(created);

    File subdir = new File(dir, "subdir");
    boolean subdirCreated = subdir.mkdir();
    assertTrue(subdirCreated);

    File subChild = new File(subdir, "subdir");
    boolean subChildCreated = subChild.createNewFile();
    assertTrue(subChildCreated);

    VirtualFile childVFile =
        LocalFileSystem.getInstance()
            .refreshAndFindFileByPath(child.getPath().replace(File.separatorChar, '/'));
    assertNotNull(childVFile);
    assertFalse(managingFS.areChildrenLoaded(vFile));
    assertTrue(managingFS.wereChildrenAccessed(vFile));

    VirtualFile subdirVFile =
        LocalFileSystem.getInstance()
            .refreshAndFindFileByPath(subdir.getPath().replace(File.separatorChar, '/'));
    assertNotNull(subdirVFile);
    assertFalse(managingFS.areChildrenLoaded(subdirVFile));
    assertFalse(managingFS.wereChildrenAccessed(subdirVFile));
    assertFalse(managingFS.areChildrenLoaded(vFile));
    assertTrue(managingFS.wereChildrenAccessed(vFile));

    vFile.getChildren();
    assertTrue(managingFS.areChildrenLoaded(vFile));
    assertTrue(managingFS.wereChildrenAccessed(vFile));
    assertFalse(managingFS.areChildrenLoaded(subdirVFile));
    assertFalse(managingFS.wereChildrenAccessed(subdirVFile));

    VirtualFile subChildVFile =
        LocalFileSystem.getInstance()
            .refreshAndFindFileByPath(subChild.getPath().replace(File.separatorChar, '/'));
    assertNotNull(subChildVFile);
    assertTrue(managingFS.areChildrenLoaded(vFile));
    assertTrue(managingFS.wereChildrenAccessed(vFile));
    assertFalse(managingFS.areChildrenLoaded(subdirVFile));
    assertTrue(managingFS.wereChildrenAccessed(subdirVFile));
  }
  @Nullable
  public VirtualFile findFileByDartUrl(final @NotNull String url) {
    if (url.startsWith(DART_PREFIX)) {
      return findFileInDartSdkLibFolder(myProject, myDartSdk, url);
    }

    if (url.startsWith(PACKAGE_PREFIX)) {
      final String packageRelPath = url.substring(PACKAGE_PREFIX.length());

      final int slashIndex = packageRelPath.indexOf('/');
      final String packageName =
          slashIndex > 0 ? packageRelPath.substring(0, slashIndex) : packageRelPath;
      final String pathRelToPackageDir =
          slashIndex > 0 ? packageRelPath.substring(slashIndex + 1) : "";

      final VirtualFile packageDir =
          StringUtil.isEmpty(packageName) ? null : myLivePackageNameToDirMap.get(packageName);
      if (packageDir != null) {
        return packageDir.findFileByRelativePath(pathRelToPackageDir);
      }

      for (final VirtualFile packageRoot : myPackageRoots) {
        final VirtualFile file = packageRoot.findFileByRelativePath(packageRelPath);
        if (file != null) {
          return file;
        }
      }

      final Set<String> packageDirs = myPubListPackageDirsMap.get(packageName);
      if (packageDirs != null) {
        for (String packageDirPath : packageDirs) {
          final VirtualFile file =
              LocalFileSystem.getInstance()
                  .findFileByPath(packageDirPath + "/" + pathRelToPackageDir);
          if (file != null) {
            return file;
          }
        }
      }
    }

    if (url.startsWith(FILE_PREFIX)) {
      final String path = StringUtil.trimLeading(url.substring(FILE_PREFIX.length()), '/');
      return LocalFileSystem.getInstance()
          .findFileByPath(SystemInfo.isWindows ? path : ("/" + path));
    }

    if (ApplicationManager.getApplication().isUnitTestMode() && url.startsWith(TEMP_PREFIX)) {
      return TempFileSystem.getInstance().findFileByPath(url.substring((TEMP_PREFIX).length()));
    }

    return null;
  }
 @NotNull
 private VirtualFile getOrCreateExtractDirVirtualFile() {
   File extractDir = new File(myDirectoryTextField.getText());
   VirtualFile vFile = LocalFileSystem.getInstance().findFileByIoFile(extractDir);
   if (vFile == null || !vFile.isValid()) {
     vFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(extractDir);
     if (vFile == null || !vFile.isValid()) {
       throw new RuntimeException(
           "Can't find valid VirtualFile for " + extractDir.getAbsolutePath());
     }
   }
   return vFile;
 }
    @Override
    public void run() {
      Project project = myModule.getProject();
      if (GoSdkService.getInstance(project).isGoModule(myModule)) {
        synchronized (myLastHandledGoPathSourcesRoots) {
          Collection<VirtualFile> goPathSourcesRoots =
              GoSdkUtil.getGoPathSources(project, myModule);
          Set<VirtualFile> excludeRoots =
              ContainerUtil.newHashSet(ProjectRootManager.getInstance(project).getContentRoots());
          ProgressIndicatorProvider.checkCanceled();
          if (!myLastHandledGoPathSourcesRoots.equals(goPathSourcesRoots)
              || !myLastHandledExclusions.equals(excludeRoots)) {
            Collection<VirtualFile> includeRoots =
                gatherIncludeRoots(goPathSourcesRoots, excludeRoots);
            ApplicationManager.getApplication()
                .invokeLater(
                    () -> {
                      if (!myModule.isDisposed()
                          && GoSdkService.getInstance(project).isGoModule(myModule)) {
                        attachLibraries(includeRoots, excludeRoots);
                      }
                    });

            myLastHandledGoPathSourcesRoots.clear();
            myLastHandledGoPathSourcesRoots.addAll(goPathSourcesRoots);

            myLastHandledExclusions.clear();
            myLastHandledExclusions.addAll(excludeRoots);

            List<String> paths = ContainerUtil.map(goPathSourcesRoots, VirtualFile::getPath);
            myWatchedRequests.clear();
            myWatchedRequests.addAll(LocalFileSystem.getInstance().addRootsToWatch(paths, true));
          }
        }
      } else {
        synchronized (myLastHandledGoPathSourcesRoots) {
          LocalFileSystem.getInstance().removeWatchedRoots(myWatchedRequests);
          myLastHandledGoPathSourcesRoots.clear();
          myLastHandledExclusions.clear();
          ApplicationManager.getApplication()
              .invokeLater(
                  () -> {
                    if (!myModule.isDisposed()
                        && GoSdkService.getInstance(project).isGoModule(myModule)) {
                      removeLibraryIfNeeded();
                    }
                  });
        }
      }
    }
  public void testUnicodeNames() throws Exception {
    final File dirFile = createTempDirectory();
    final String name = "te\u00dft123123123.txt";
    final File childFile = new File(dirFile, name);
    boolean created = childFile.createNewFile();
    assert created || childFile.exists() : childFile;

    final VirtualFile dir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(dirFile);
    assertNotNull(dir);

    final VirtualFile child = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(childFile);
    assertNotNull(child);

    assertTrue(childFile.delete());
  }
  public void scan() {
    List<VirtualFile> workQueue = myWorkQueue;
    myWorkQueue = new ArrayList<VirtualFile>();
    boolean hasEventsToFire = myFinishRunnable != null || !myEvents.isEmpty();

    if (!workQueue.isEmpty()) {
      LocalFileSystemImpl fs = (LocalFileSystemImpl) LocalFileSystem.getInstance();
      fs.markSuspiciousFilesDirty(workQueue);
      FileWatcher watcher = fs.getFileWatcher();

      for (VirtualFile file : workQueue) {
        NewVirtualFile nvf = (NewVirtualFile) file;
        if (!myIsRecursive
            && (!myIsAsync
                || !watcher.isWatched(
                    nvf))) { // We're unable to definitely refresh synchronously by means of file
                             // watcher.
          nvf.markDirty();
        }

        RefreshWorker worker = new RefreshWorker(file, myIsRecursive);
        long t = LOG.isDebugEnabled() ? System.currentTimeMillis() : 0;
        worker.scan();
        List<VFileEvent> events = worker.getEvents();
        if (t != 0) {
          t = System.currentTimeMillis() - t;
          LOG.debug(file + " scanned in " + t + " ms, events: " + events);
        }
        myEvents.addAll(events);
        if (!events.isEmpty()) hasEventsToFire = true;
      }
    }
    iHaveEventsToFire = hasEventsToFire;
  }
  @Nullable
  public VirtualFile getPackageDirIfLivePackageOrFromPubListPackageDirs(
      @NotNull final String packageName, @Nullable final String pathRelToPackageDir) {
    final VirtualFile dir = myLivePackageNameToDirMap.get(packageName);
    if (dir != null) return dir;

    final Set<String> dirPaths = myPubListPackageDirsMap.get(packageName);
    if (dirPaths != null) {
      VirtualFile notNullPackageDir = null;

      for (String dirPath : dirPaths) {
        final VirtualFile packageDir =
            ApplicationManager.getApplication().isUnitTestMode()
                ? TempFileSystem.getInstance().findFileByPath(dirPath)
                : LocalFileSystem.getInstance().findFileByPath(dirPath);
        if (notNullPackageDir == null && packageDir != null) {
          notNullPackageDir = packageDir;
        }

        if (packageDir != null
            && (StringUtil.isEmpty(pathRelToPackageDir)
                || packageDir.findFileByRelativePath(pathRelToPackageDir) != null)) {
          return packageDir;
        }
      }

      return notNullPackageDir; // file by pathRelToPackageDir was not found, but not-null
                                // packageDir still may be useful
    }

    return null;
  }
  @Override
  public void setupRootModel(final ModifiableRootModel modifiableRootModel)
      throws ConfigurationException {
    String contentEntryPath = getContentEntryPath();
    if (StringUtil.isEmpty(contentEntryPath)) {
      return;
    }
    File contentRootDir = new File(contentEntryPath);
    FileUtilRt.createDirectory(contentRootDir);
    LocalFileSystem fileSystem = LocalFileSystem.getInstance();
    VirtualFile modelContentRootDir = fileSystem.refreshAndFindFileByIoFile(contentRootDir);
    if (modelContentRootDir == null) {
      return;
    }

    modifiableRootModel.addContentEntry(modelContentRootDir);
    modifiableRootModel.inheritSdk();

    final Project project = modifiableRootModel.getProject();

    setupGradleBuildFile(modelContentRootDir);
    setupGradleSettingsFile(modelContentRootDir, modifiableRootModel);

    if (myWizardContext.isCreatingNewProject()) {
      String externalProjectPath = FileUtil.toCanonicalPath(project.getBasePath());
      getExternalProjectSettings().setExternalProjectPath(externalProjectPath);
      AbstractExternalSystemSettings settings =
          ExternalSystemApiUtil.getSettings(project, GradleConstants.SYSTEM_ID);
      //noinspection unchecked
      settings.linkProject(getExternalProjectSettings());
    } else {
      FileDocumentManager.getInstance().saveAllDocuments();
      ExternalSystemUtil.refreshProjects(project, GradleConstants.SYSTEM_ID, false);
    }
  }
  protected void doTest(final PerformAction performAction, final String testName) throws Exception {
    String path = getTestDataPath() + getTestRoot() + testName;

    String pathBefore = path + "/before";
    final VirtualFile rootDir =
        PsiTestUtil.createTestProjectStructure(
            myProject, myModule, pathBefore, myFilesToDelete, false);
    prepareProject(rootDir);
    PsiDocumentManager.getInstance(myProject).commitAllDocuments();

    String pathAfter = path + "/after";
    final VirtualFile rootAfter =
        LocalFileSystem.getInstance().findFileByPath(pathAfter.replace(File.separatorChar, '/'));

    performAction.performAction(rootDir, rootAfter);
    ApplicationManager.getApplication()
        .runWriteAction(
            new Runnable() {
              public void run() {
                myProject.getComponent(PostprocessReformattingAspect.class).doPostponedFormatting();
              }
            });

    FileDocumentManager.getInstance().saveAllDocuments();

    if (myDoCompare) {
      PlatformTestUtil.assertDirectoriesEqual(rootAfter, rootDir);
    }
  }
  /** call in setUp */
  public DuringChangeListManagerUpdateTestScheme(final Project project, final String tmpDirPath) {
    final MockAbstractVcs vcs = new MockAbstractVcs(project);
    myChangeProvider = new MockDelayingChangeProvider();
    vcs.setChangeProvider(myChangeProvider);

    final File mockVcsRoot = new File(tmpDirPath, "mock");
    mockVcsRoot.mkdir();
    final VirtualFile vRoot = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(mockVcsRoot);

    final ProjectLevelVcsManagerImpl projectLevelVcsManager =
        (ProjectLevelVcsManagerImpl) ProjectLevelVcsManager.getInstance(project);
    projectLevelVcsManager.registerVcs(vcs);
    // projectLevelVcsManager.setDirectoryMapping(mockVcsRoot.getAbsolutePath(), vcs.getName());
    final ArrayList<VcsDirectoryMapping> list =
        new ArrayList<VcsDirectoryMapping>(projectLevelVcsManager.getDirectoryMappings());
    list.add(new VcsDirectoryMapping(vRoot.getPath(), vcs.getName()));
    projectLevelVcsManager.setDirectoryMappings(list);

    AbstractVcs vcsFound = projectLevelVcsManager.findVcsByName(vcs.getName());
    final VirtualFile[] roots = projectLevelVcsManager.getRootsUnderVcs(vcsFound);
    assert roots.length == 1
        : Arrays.asList(roots)
            + "; "
            + vcs.getName()
            + "; "
            + Arrays.toString(AllVcses.getInstance(project).getAll());

    myDirtyScopeManager = VcsDirtyScopeManager.getInstance(project);
    myClManager = ChangeListManager.getInstance(project);
  }
  @Nullable
  public static VirtualFile getDirectory(@NotNull final FindModel findModel) {
    String directoryName = findModel.getDirectoryName();
    if (findModel.isProjectScope() || StringUtil.isEmpty(directoryName)) {
      return null;
    }

    String path = directoryName.replace(File.separatorChar, '/');
    VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(path);
    if (virtualFile == null || !virtualFile.isDirectory()) {
      virtualFile = null;
      for (LocalFileProvider provider :
          ((VirtualFileManagerEx) VirtualFileManager.getInstance()).getLocalFileProviders()) {
        VirtualFile file = provider.findLocalVirtualFileByPath(path);
        if (file != null && file.isDirectory()) {
          if (file.getChildren().length > 0) {
            virtualFile = file;
            break;
          }
          if (virtualFile == null) {
            virtualFile = file;
          }
        }
      }
    }
    return virtualFile;
  }
  public void doCheckout(@NotNull final Project project, @Nullable final Listener listener) {
    ApplicationManager.getApplication()
        .runWriteAction(
            new Runnable() {
              public void run() {
                FileDocumentManager.getInstance().saveAllDocuments();
              }
            });

    final HgCloneDialog dialog = new HgCloneDialog(project);
    dialog.show();
    if (!dialog.isOK()) {
      return;
    }
    dialog.rememberSettings();
    final VirtualFile destinationParent =
        LocalFileSystem.getInstance().findFileByIoFile(new File(dialog.getParentDirectory()));
    if (destinationParent == null) {
      return;
    }
    final String targetDir =
        destinationParent.getPath() + File.separator + dialog.getDirectoryName();

    final String sourceRepositoryURL = dialog.getSourceRepositoryURL();
    new Task.Backgroundable(
        project, HgVcsMessages.message("hg4idea.clone.progress", sourceRepositoryURL), true) {
      @Override
      public void run(@NotNull ProgressIndicator indicator) {
        // clone
        HgCloneCommand clone = new HgCloneCommand(project);
        clone.setRepositoryURL(sourceRepositoryURL);
        clone.setDirectory(targetDir);

        // handle result
        HgCommandResult myCloneResult = clone.execute();
        if (myCloneResult == null) {
          new HgCommandResultNotifier(project)
              .notifyError(null, "Clone failed", "Clone failed due to unknown error");
        } else if (HgErrorUtil.hasErrorsInCommandExecution(myCloneResult)) {
          new HgCommandResultNotifier(project)
              .notifyError(
                  myCloneResult, "Clone failed", "Clone from " + sourceRepositoryURL + " failed.");
        } else {
          ApplicationManager.getApplication()
              .invokeLater(
                  new Runnable() {
                    @Override
                    public void run() {
                      if (listener != null) {
                        listener.directoryCheckedOut(
                            new File(dialog.getParentDirectory(), dialog.getDirectoryName()),
                            HgVcs.getKey());
                        listener.checkoutCompleted();
                      }
                    }
                  });
        }
      }
    }.queue();
  }
  @WrapInCommand
  public void testReimportConflictingClasses() throws Exception {
    configureByFile(BASE_PATH + "/x/Usage.java", BASE_PATH);
    assertEmpty(highlightErrors());

    CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(getProject()).clone();
    settings.CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND = 2;
    CodeStyleSettingsManager.getInstance(getProject()).setTemporarySettings(settings);
    try {
      new WriteCommandAction.Simple(getProject()) {
        @Override
        protected void run() throws Throwable {
          JavaCodeStyleManager.getInstance(getProject()).optimizeImports(getFile());
        }
      }.execute().throwException();
    } finally {
      CodeStyleSettingsManager.getInstance(getProject()).dropTemporarySettings();
    }

    @NonNls String fullPath = getTestDataPath() + BASE_PATH + "/x/Usage_afterOptimize.txt";
    final VirtualFile vFile =
        LocalFileSystem.getInstance().findFileByPath(fullPath.replace(File.separatorChar, '/'));
    String text = LoadTextUtil.loadText(vFile).toString();
    assertEquals(text, getFile().getText());
  }
    public void actionPerformed(final ActionEvent e) {
      final FileChooserDescriptor descriptor =
          new FilterFileChooserDescriptor(
              "Select",
              "Select a file to import",
              new FileFilter() {
                @Override
                public boolean accept(final File f) {
                  return f.isDirectory()
                      || "xml".equalsIgnoreCase(FileUtilRt.getExtension(f.getAbsolutePath()));
                }

                @Override
                public String getDescription() {
                  return "*.xml";
                }
              });

      final Component parent = SwingUtilities.getRoot(_importFile);
      final VirtualFile toSelect = LocalFileSystem.getInstance().findFileByPath(_importDir);
      final VirtualFile chosen = FileChooser.chooseFile(descriptor, parent, null, toSelect);
      if (chosen != null) {
        _selectedFile = VfsUtilCore.virtualToIoFile(chosen);
        final String newLocation = _selectedFile.getPath();
        _importFile.setText(newLocation);
        _dialogBuilder.setOkActionEnabled(true);
      }
    }
  private void waitForFileWatcher(@NotNull Project project) {
    LocalFileSystem fs = LocalFileSystem.getInstance();
    if (!(fs instanceof LocalFileSystemImpl)) return;

    final FileWatcher watcher = ((LocalFileSystemImpl) fs).getFileWatcher();
    if (!watcher.isOperational() || !watcher.isSettingRoots()) return;

    LOG.info("FW/roots waiting started");
    Task.Modal task =
        new Task.Modal(project, ProjectBundle.message("project.load.progress"), true) {
          @Override
          public void run(@NotNull ProgressIndicator indicator) {
            indicator.setIndeterminate(true);
            indicator.setText(ProjectBundle.message("project.load.waiting.watcher"));
            if (indicator instanceof ProgressWindow) {
              ((ProgressWindow) indicator).setCancelButtonText(CommonBundle.message("button.skip"));
            }
            while (watcher.isSettingRoots() && !indicator.isCanceled()) {
              TimeoutUtil.sleep(10);
            }
            LOG.info("FW/roots waiting finished");
          }
        };
    myProgressManager.run(task);
  }
Example #20
0
  /** @return true if keymap was installed or was successfully installed */
  public static boolean installKeyBoardBindings() {
    LOG.debug("Check for keyboard bindings");
    final LocalFileSystem localFileSystem = LocalFileSystem.getInstance();
    if (localFileSystem.refreshAndFindFileByPath(KEYMAPS_PATH) == null) {
      reportError("Failed to install vim keymap. Empty keymaps folder");
      return false;
    }

    LOG.debug("No vim keyboard installed found. Installing");
    try {
      final byte[] bytes = toByteArray(retrieveSourceKeymapStream());
      Files.write(bytes, new File(INSTALLED_VIM_KEYMAP_PATH));
      final Document document = StorageUtil.loadDocument(bytes);
      if (document != null && !ApplicationManager.getApplication().isUnitTestMode()) {
        // Prompt user to select the parent for the Vim keyboard
        if (!configureVimParentKeymap(INSTALLED_VIM_KEYMAP_PATH, document, true)) {
          return false;
        }
      }
      installKeymap(document);
    } catch (IOException e) {
      reportError("Source keymap not found", e);
      return false;
    } catch (InvalidDataException e) {
      reportError("Failed to install vim keymap. Vim.xml file is corrupted", e);
      return false;
    } catch (Exception e) {
      reportError("Failed to install vim keymap.\n", e);
      return false;
    }

    return true;
  }
Example #21
0
  private void updateWatchedRoots() {
    Set<String> pathsToRemove = new HashSet<String>(myWatchedOutputs.keySet());
    Set<String> toAdd = new HashSet<String>();
    for (Artifact artifact : getArtifacts()) {
      final String path = artifact.getOutputPath();
      if (path != null && path.length() > 0) {
        pathsToRemove.remove(path);
        if (!myWatchedOutputs.containsKey(path)) {
          toAdd.add(path);
        }
      }
    }

    List<LocalFileSystem.WatchRequest> requestsToRemove =
        new ArrayList<LocalFileSystem.WatchRequest>();
    for (String path : pathsToRemove) {
      final LocalFileSystem.WatchRequest request = myWatchedOutputs.remove(path);
      ContainerUtil.addIfNotNull(request, requestsToRemove);
    }

    Set<LocalFileSystem.WatchRequest> newRequests =
        LocalFileSystem.getInstance().replaceWatchedRoots(requestsToRemove, toAdd, null);
    for (LocalFileSystem.WatchRequest request : newRequests) {
      myWatchedOutputs.put(request.getRootPath(), request);
    }
  }
  @Test
  public void testSimpleExternalsStatus() throws Exception {
    prepareExternal();
    final File sourceFile =
        new File(myWorkingCopyDir.getPath(), "source" + File.separator + "s1.txt");
    final File externalFile =
        new File(
            myWorkingCopyDir.getPath(),
            "source" + File.separator + "external" + File.separator + "t12.txt");

    final LocalFileSystem lfs = LocalFileSystem.getInstance();
    final VirtualFile vf1 = lfs.refreshAndFindFileByIoFile(sourceFile);
    final VirtualFile vf2 = lfs.refreshAndFindFileByIoFile(externalFile);

    Assert.assertNotNull(vf1);
    Assert.assertNotNull(vf2);

    editFileInCommand(myProject, vf1, "test externals 123" + System.currentTimeMillis());
    editFileInCommand(myProject, vf2, "test externals 123" + System.currentTimeMillis());

    VcsDirtyScopeManager.getInstance(myProject).markEverythingDirty();
    clManager.ensureUpToDate(false);

    final Change change1 = clManager.getChange(vf1);
    final Change change2 = clManager.getChange(vf2);

    Assert.assertNotNull(change1);
    Assert.assertNotNull(change2);

    Assert.assertNotNull(change1.getBeforeRevision());
    Assert.assertNotNull(change2.getBeforeRevision());

    Assert.assertNotNull(change1.getAfterRevision());
    Assert.assertNotNull(change2.getAfterRevision());
  }
  @Override
  public SourceScope getSourceScope() {
    final String dirName = myConfiguration.getPersistentData().getDirName();
    final VirtualFile file =
        LocalFileSystem.getInstance().findFileByPath(FileUtil.toSystemIndependentName(dirName));
    final GlobalSearchScope globalSearchScope =
        file == null
            ? GlobalSearchScope.EMPTY_SCOPE
            : GlobalSearchScopes.directoryScope(myProject, file, true);
    return new SourceScope() {
      @Override
      public GlobalSearchScope getGlobalSearchScope() {
        return globalSearchScope;
      }

      @Override
      public Project getProject() {
        return myProject;
      }

      @Override
      public GlobalSearchScope getLibrariesScope() {
        final Module module = myConfiguration.getConfigurationModule().getModule();
        LOG.assertTrue(module != null);
        return GlobalSearchScope.moduleWithLibrariesScope(module);
      }

      @Override
      public Module[] getModulesToCompile() {
        final Collection<Module> validModules = myConfiguration.getValidModules();
        return validModules.toArray(new Module[validModules.size()]);
      }
    };
  }
  public void testAddSourceRoot() throws Exception {
    File dir = createTempDirectory();

    final VirtualFile root =
        LocalFileSystem.getInstance()
            .refreshAndFindFileByPath(dir.getCanonicalPath().replace(File.separatorChar, '/'));

    new WriteCommandAction.Simple(getProject()) {
      @Override
      protected void run() throws Throwable {
        PsiTestUtil.addContentRoot(myModule, root);

        VirtualFile newFile = createChildData(root, "New.java");
        setFileText(newFile, "class A{ Exception e;} //todo");
      }
    }.execute().throwException();

    PsiDocumentManager.getInstance(myProject).commitAllDocuments();

    PsiTodoSearchHelper.SERVICE
        .getInstance(myProject)
        .findFilesWithTodoItems(); // to initialize caches

    PsiTestUtil.addSourceRoot(myModule, root);

    PsiClass exceptionClass =
        myJavaFacade.findClass("java.lang.Exception", GlobalSearchScope.allScope(getProject()));
    assertNotNull(exceptionClass);
    checkUsages(exceptionClass, new String[] {"1.java", "2.java", "New.java"});
    checkTodos(new String[] {"2.java", "New.java"});
  }
  private static void attachJdkAnnotations(Sdk jdk) {
    LocalFileSystem lfs = LocalFileSystem.getInstance();
    VirtualFile root = null;
    if (root == null) { // community idea under idea
      root =
          lfs.findFileByPath(
              FileUtil.toSystemIndependentName(PathManager.getHomePath()) + "/java/jdkAnnotations");
    }
    if (root == null) { // idea under idea
      root =
          lfs.findFileByPath(
              FileUtil.toSystemIndependentName(PathManager.getHomePath())
                  + "/community/java/jdkAnnotations");
    }
    if (root == null) { // build
      root =
          VirtualFileManager.getInstance()
              .findFileByUrl(
                  "jar://"
                      + FileUtil.toSystemIndependentName(PathManager.getHomePath())
                      + "/lib/jdkAnnotations.jar!/");
    }
    if (root == null) {
      LOG.error(
          "jdk annotations not found in: "
              + FileUtil.toSystemIndependentName(PathManager.getHomePath())
              + "/lib/jdkAnnotations.jar!/");
      return;
    }

    SdkModificator modificator = jdk.getSdkModificator();
    modificator.removeRoot(root, AnnotationOrderRootType.getInstance());
    modificator.addRoot(root, AnnotationOrderRootType.getInstance());
    modificator.commitChanges();
  }
  @Override
  protected void setUp() throws Exception {
    if (ourOutputRoot == null) {
      ourOutputRoot = FileUtil.createTempDirectory("ExecutionTestCase", null, true);
    }
    myModuleOutputDir = new File(ourOutputRoot, PathUtil.getFileName(getTestAppPath()));
    myChecker = initOutputChecker();
    EdtTestUtil.runInEdtAndWait(
        new ThrowableRunnable<Throwable>() {
          @Override
          public void run() throws Throwable {
            ExecutionTestCase.super.setUp();
          }
        });
    if (!myModuleOutputDir.exists()) {
      VirtualFile vDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(ourOutputRoot);
      assertNotNull(ourOutputRoot.getAbsolutePath(), vDir);
      vDir
          .getChildren(); // we need this to load children to VFS to fire VFileCreatedEvent for the
                          // output directory

      myCompilerTester =
          new CompilerTester(
              myProject, Arrays.asList(ModuleManager.getInstance(myProject).getModules()));
      List<CompilerMessage> messages = myCompilerTester.rebuild();
      for (CompilerMessage message : messages) {
        if (message.getCategory() == CompilerMessageCategory.ERROR) {
          FileUtil.delete(myModuleOutputDir);
          fail("Compilation failed: " + message);
        }
      }
    }
  }
  private static Set<VirtualFile> getFilteredResourcesRoots(@NotNull MavenProject mavenProject) {
    Pair<Long, Set<VirtualFile>> cachedValue =
        mavenProject.getCachedValue(FILTERED_RESOURCES_ROOTS_KEY);

    if (cachedValue == null
        || cachedValue.first != VirtualFileManager.getInstance().getModificationCount()) {
      Set<VirtualFile> set = null;

      for (MavenResource resource :
          ContainerUtil.concat(mavenProject.getResources(), mavenProject.getTestResources())) {
        if (!resource.isFiltered()) continue;

        VirtualFile resourceDir =
            LocalFileSystem.getInstance().findFileByPath(resource.getDirectory());
        if (resourceDir == null) continue;

        if (set == null) {
          set = new HashSet<VirtualFile>();
        }

        set.add(resourceDir);
      }

      if (set == null) {
        set = Collections.emptySet();
      }

      cachedValue = Pair.create(VirtualFileManager.getInstance().getModificationCount(), set);
      mavenProject.putCachedValue(FILTERED_RESOURCES_ROOTS_KEY, cachedValue);
    }

    return cachedValue.second;
  }
  private void checkProjectRoots() {
    LocalFileSystem fs = LocalFileSystem.getInstance();
    if (!(fs instanceof LocalFileSystemImpl)) return;
    FileWatcher watcher = ((LocalFileSystemImpl) fs).getFileWatcher();
    if (!watcher.isOperational()) return;
    Collection<String> manualWatchRoots = watcher.getManualWatchRoots();
    if (manualWatchRoots.isEmpty()) return;
    VirtualFile[] roots = ProjectRootManager.getInstance(myProject).getContentRoots();
    if (roots.length == 0) return;

    List<String> nonWatched = new SmartList<String>();
    for (VirtualFile root : roots) {
      if (!(root.getFileSystem() instanceof LocalFileSystem)) continue;
      String rootPath = root.getPath();
      for (String manualWatchRoot : manualWatchRoots) {
        if (FileUtil.isAncestor(manualWatchRoot, rootPath, false)) {
          nonWatched.add(rootPath);
        }
      }
    }

    if (!nonWatched.isEmpty()) {
      String message = ApplicationBundle.message("watcher.non.watchable.project");
      watcher.notifyOnFailure(message, null);
      LOG.info("unwatched roots: " + nonWatched);
      LOG.info("manual watches: " + manualWatchRoots);
    }
  }
  @Override
  protected void setUp() throws Exception {
    LOG.debug("================== setting up " + getName() + " ==================");

    super.setUp();

    myFileSystem = LocalFileSystem.getInstance();
    assertNotNull(myFileSystem);

    myWatcher = ((LocalFileSystemImpl) myFileSystem).getFileWatcher();
    assertNotNull(myWatcher);
    assertFalse(myWatcher.isOperational());
    myWatcher.startup(myNotifier);
    assertTrue(myWatcher.isOperational());

    myAlarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, getProject());
    myTimeout = NATIVE_PROCESS_DELAY;

    myConnection = ApplicationManager.getApplication().getMessageBus().connect();
    myConnection.subscribe(
        VirtualFileManager.VFS_CHANGES,
        new BulkFileListener.Adapter() {
          @Override
          public void after(@NotNull List<? extends VFileEvent> events) {
            synchronized (myEvents) {
              myEvents.addAll(events);
            }
          }
        });

    ((LocalFileSystemImpl) myFileSystem).cleanupForNextTest();

    LOG = FileWatcher.getLog();
    LOG.debug("================== setting up " + getName() + " ==================");
  }
 @Override
 public IFile createFile(String path) {
   File file = new File(context.absPath(path));
   String name = file.getName();
   String parentPath = file.getParent();
   try {
     VfsUtil.createDirectories(parentPath);
   } catch (IOException e) {
     Flog.error("Create directories error %s", e);
     context.errorMessage("The Floobits plugin was unable to create directories for file.");
     return null;
   }
   VirtualFile parent = LocalFileSystem.getInstance().findFileByPath(parentPath);
   if (parent == null) {
     Flog.error("Virtual file is null? %s", parentPath);
     return null;
   }
   VirtualFile newFile;
   try {
     newFile = parent.findOrCreateChildData(context, name);
   } catch (Throwable e) {
     Flog.error("Create file error %s", e);
     context.errorMessage(
         String.format("The Floobits plugin was unable to create a file: %s.", path));
     return null;
   }
   return new FileImpl(newFile);
 }