public void testNonCanonicallyNamedFileRoot() throws Exception {
    if (SystemInfo.isFileSystemCaseSensitive) {
      System.err.println("Ignored: case-insensitive FS required");
      return;
    }

    File file = createTestFile("test.txt");
    refresh(file);

    String watchRoot = file.getAbsolutePath().toUpperCase(Locale.US);
    LocalFileSystem.WatchRequest request = watch(new File(watchRoot));
    try {
      myAccept = true;
      FileUtil.writeToFile(file, "new content");
      assertEvent(VFileContentChangeEvent.class, file.getAbsolutePath());

      myAccept = true;
      FileUtil.delete(file);
      assertEvent(VFileDeleteEvent.class, file.getAbsolutePath());

      myAccept = true;
      FileUtil.writeToFile(file, "re-creation");
      assertEvent(VFileCreateEvent.class, file.getAbsolutePath());
    } finally {
      unwatch(request);
      delete(file);
    }
  }
  public void testDirectoryRecursive() throws Exception {
    File topDir = createTestDir("top");
    refresh(topDir);

    LocalFileSystem.WatchRequest request = watch(topDir);
    try {
      myAccept = true;
      File subDir = createTestDir(topDir, "sub");
      assertEvent(VFileCreateEvent.class, subDir.getAbsolutePath());
      refresh(subDir);

      myAccept = true;
      File file = createTestFile(subDir, "test.txt");
      assertEvent(VFileCreateEvent.class, file.getAbsolutePath());

      myAccept = true;
      FileUtil.writeToFile(file, "new content");
      assertEvent(VFileContentChangeEvent.class, file.getAbsolutePath());

      myAccept = true;
      FileUtil.delete(file);
      assertEvent(VFileDeleteEvent.class, file.getAbsolutePath());

      myAccept = true;
      FileUtil.writeToFile(file, "re-creation");
      assertEvent(VFileCreateEvent.class, file.getAbsolutePath());
    } finally {
      unwatch(request);
      delete(topDir);
    }
  }
  private static void processAvailableTraces(RunConfigurationBase configuration) {
    final String tracesDirectory = getTracesDirectory(configuration);
    final TestDiscoveryIndex coverageIndex =
        TestDiscoveryIndex.getInstance(configuration.getProject());
    synchronized (ourTracesLock) {
      final File tracesDirectoryFile = new File(tracesDirectory);
      final File[] testMethodTraces =
          tracesDirectoryFile.listFiles(
              new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                  return name.endsWith(".tr");
                }
              });
      if (testMethodTraces != null) {
        for (File testMethodTrace : testMethodTraces) {
          try {
            coverageIndex.updateFromTestTrace(testMethodTrace);
            FileUtil.delete(testMethodTrace);
          } catch (IOException e) {
            LOG.error("Can not load " + testMethodTrace, e);
          }
        }

        final String[] filesInTracedDirectories = tracesDirectoryFile.list();
        if (filesInTracedDirectories == null || filesInTracedDirectories.length == 0) {
          FileUtil.delete(tracesDirectoryFile);
        }
      }
    }
  }
 public void testSmokeWithCompilerOutput() throws IOException {
   File tempDir = FileUtil.createTempDirectory("compilerTest", "compilerTest");
   try {
     File out = new File(tempDir, "out");
     File stdlib = ForTestCompileRuntime.runtimeJarForTests();
     File jdkAnnotations = ForTestPackJdkAnnotations.jdkAnnotationsForTests();
     ExitCode exitCode =
         new K2JVMCompiler()
             .exec(
                 System.out,
                 "-src",
                 JetParsingTest.getTestDataDir() + "/compiler/smoke/Smoke.kt",
                 "-output",
                 out.getAbsolutePath(),
                 "-noStdlib",
                 "-classpath",
                 stdlib.getAbsolutePath(),
                 "-noJdkAnnotations",
                 "-annotations",
                 jdkAnnotations.getAbsolutePath());
     Assert.assertEquals(ExitCode.OK, exitCode);
     assertEquals(1, out.listFiles().length);
     assertEquals(1, out.listFiles()[0].listFiles().length);
   } finally {
     FileUtil.delete(tempDir);
   }
 }
  private void initTimestampIndex(final boolean needReindex) {
    if (needReindex) {
      FileUtil.delete(IndexInfrastructure.getIndexRootDir(getFileTimestampsIndexId()));
    }
    for (int attempts = 0; attempts < 2; attempts++) {
      try {
        this.fileTimestampsIndex =
            new PersistentHashMap<Integer, Long>(
                IndexInfrastructure.getStorageFile(getFileTimestampsIndexId()),
                EnumeratorIntegerDescriptor.INSTANCE,
                new DataExternalizer<Long>() {
                  @Override
                  public void save(final DataOutput out, final Long value) throws IOException {
                    out.writeLong(value);
                  }

                  @Override
                  public Long read(final DataInput in) throws IOException {
                    return in.readLong();
                  }
                });
      } catch (IOException e) {
        FileUtil.delete(IndexInfrastructure.getIndexRootDir(getFileTimestampsIndexId()));
      }
      if (fileTimestampsIndex != null) {
        return;
      }
    }
    throw new RuntimeException("Timestamps index not initialized");
  }
 protected static void change(String filePath, final @Nullable String newContent) {
   try {
     File file = new File(FileUtil.toSystemDependentName(filePath));
     assertTrue("File " + file.getAbsolutePath() + " doesn't exist", file.exists());
     if (newContent != null) {
       FileUtil.writeToFile(file, newContent);
     }
     long oldTimestamp = FileSystemUtil.lastModified(file);
     long time = System.currentTimeMillis();
     setLastModified(file, time);
     if (FileSystemUtil.lastModified(file) <= oldTimestamp) {
       setLastModified(file, time + 1);
       long newTimeStamp = FileSystemUtil.lastModified(file);
       if (newTimeStamp <= oldTimestamp) {
         // Mac OS and some versions of Linux truncates timestamp to nearest second
         setLastModified(file, time + 1000);
         newTimeStamp = FileSystemUtil.lastModified(file);
         assertTrue(
             "Failed to change timestamp for " + file.getAbsolutePath(),
             newTimeStamp > oldTimestamp);
       }
       sleepUntil(newTimeStamp);
     }
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
  @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 String ensureCorrectOutput(
      ModuleChunk chunk,
      GroovycOutputParser.OutputItem item,
      Map<ModuleBuildTarget, String> generationOutputs,
      String compilerOutput,
      @NotNull ModuleBuildTarget srcTarget)
      throws IOException {
    if (chunk.getModules().size() > 1 && !srcTarget.equals(chunk.representativeTarget())) {
      File output = new File(item.outputPath);

      String srcTargetOutput = generationOutputs.get(srcTarget);
      if (srcTargetOutput == null) {
        LOG.info(
            "No output for "
                + srcTarget
                + "; outputs="
                + generationOutputs
                + "; targets = "
                + chunk.getTargets());
        return item.outputPath;
      }

      // todo honor package prefixes
      File correctRoot = new File(srcTargetOutput);
      File correctOutput =
          new File(correctRoot, FileUtil.getRelativePath(new File(compilerOutput), output));

      FileUtil.rename(output, correctOutput);
      return correctOutput.getPath();
    }
    return item.outputPath;
  }
  public void testFileCaseChange() throws Exception {
    if (SystemInfo.isFileSystemCaseSensitive) {
      System.err.println("Ignored: case-insensitive FS required");
      return;
    }

    File top = createTempDirectory(false);
    File file = IoTestUtil.createTestFile(top, "file.txt", "test");
    File intermediate = new File(top, "_intermediate_");

    LocalFileSystem lfs = LocalFileSystem.getInstance();
    VirtualFile topDir = lfs.refreshAndFindFileByIoFile(top);
    assertNotNull(topDir);
    VirtualFile sourceFile = lfs.refreshAndFindFileByIoFile(file);
    assertNotNull(sourceFile);

    String newName = StringUtil.capitalize(file.getName());
    FileUtil.rename(file, intermediate);
    FileUtil.rename(intermediate, new File(top, newName));
    topDir.refresh(false, true);
    assertFalse(((VirtualDirectoryImpl) topDir).allChildrenLoaded());
    assertTrue(sourceFile.isValid());
    assertEquals(newName, sourceFile.getName());

    topDir.getChildren();
    newName = newName.toLowerCase();
    FileUtil.rename(file, intermediate);
    FileUtil.rename(intermediate, new File(top, newName));
    topDir.refresh(false, true);
    assertTrue(((VirtualDirectoryImpl) topDir).allChildrenLoaded());
    assertTrue(sourceFile.isValid());
    assertEquals(newName, sourceFile.getName());
  }
  private void doTest(String prefix) throws IOException {
    int n = 0;
    int failed = 0;
    for (String name : myMap.keySet()) {
      if (prefix == null && name.contains("/")) {
        continue;
      }
      if (prefix != null && !name.startsWith(prefix)) {
        continue;
      }
      System.out.print("filename = " + name);
      n++;

      final MainParseTest.Test test = myMap.get(name);
      try {
        myFixture.testHighlighting(test.showWarnings, true, test.showInfo, name);

        if (test.expectedResult == Result.ERR) {
          System.out.println(
              "  FAILED. Expression incorrectly parsed OK: "
                  + FileUtil.loadFile(new File(getTestDataPath(), name)));
          failed++;
        } else {
          System.out.println("  OK");
        }
      } catch (Throwable e) {
        if (test.expectedResult == Result.ERR) {
          System.out.println("  OK");
        } else {
          e.printStackTrace();
          System.out.println(
              "  FAILED. Expression = " + FileUtil.loadFile(new File(getTestDataPath(), name)));
          if (myOut.size() > 0) {
            String line;
            final BufferedReader reader = new BufferedReader(new StringReader(myOut.toString()));
            do {
              line = reader.readLine();
            } while (line != null && (line.trim().length() == 0 || line.trim().equals("ERROR:")));
            if (line != null) {
              if (line.matches(".*java.lang.Error: junit.framework.AssertionFailedError:.*")) {
                System.out.println(
                    "ERROR: "
                        + line.replace(
                            "java.lang.Error: junit.framework.AssertionFailedError:", ""));
              }
            } else {
              System.out.println("ERROR: " + myOut.toString());
            }
          }
          failed++;
        }
      }
      myOut.reset();
    }

    System.out.println("");
    System.out.println(n + " Tests executed, " + failed + " failed");

    assertFalse(failed > 0);
  }
  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);
    }
  }
  @NotNull
  private static String getFileFqn(final PsiFile file) {
    final VirtualFile virtualFile = file.getVirtualFile();
    if (virtualFile == null) {
      return file.getName();
    }
    final Project project = file.getProject();
    final LogicalRoot logicalRoot =
        LogicalRootsManager.getLogicalRootsManager(project).findLogicalRoot(virtualFile);
    if (logicalRoot != null) {
      String logical =
          FileUtil.toSystemIndependentName(
              VfsUtil.virtualToIoFile(logicalRoot.getVirtualFile()).getPath());
      String path =
          FileUtil.toSystemIndependentName(VfsUtil.virtualToIoFile(virtualFile).getPath());
      return "/" + FileUtil.getRelativePath(logical, path, '/');
    }

    final VirtualFile contentRoot =
        ProjectRootManager.getInstance(project).getFileIndex().getContentRootForFile(virtualFile);
    if (contentRoot != null) {
      return "/"
          + FileUtil.getRelativePath(
              VfsUtil.virtualToIoFile(contentRoot), VfsUtil.virtualToIoFile(virtualFile));
    }
    return virtualFile.getPath();
  }
Exemple #13
0
  public static void assertEqualsToFile(
      @NotNull File expectedFile,
      @NotNull String actual,
      @NotNull Function1<String, String> sanitizer) {
    try {
      String actualText =
          JetTestUtilsKt.trimTrailingWhitespacesAndAddNewlineAtEOF(
              StringUtil.convertLineSeparators(actual.trim()));

      if (!expectedFile.exists()) {
        FileUtil.writeToFile(expectedFile, actualText);
        Assert.fail("Expected data file did not exist. Generating: " + expectedFile);
      }
      String expected = FileUtil.loadFile(expectedFile, CharsetToolkit.UTF8, true);

      String expectedText =
          JetTestUtilsKt.trimTrailingWhitespacesAndAddNewlineAtEOF(
              StringUtil.convertLineSeparators(expected.trim()));

      if (!Comparing.equal(sanitizer.invoke(expectedText), sanitizer.invoke(actualText))) {
        throw new FileComparisonFailure(
            "Actual data differs from file content: " + expectedFile.getName(),
            expected,
            actual,
            expectedFile.getAbsolutePath());
      }
    } catch (IOException e) {
      throw ExceptionUtilsKt.rethrow(e);
    }
  }
 private void copyFileOrDir(File src, File dst) throws IOException {
   if (src.isDirectory()) {
     FileUtil.copyDir(src, dst);
   } else {
     FileUtil.copy(src, dst);
   }
 }
  private void prepareInnerCopy() throws Exception {
    final SubTree subTree = new SubTree(myWorkingCopyDir);
    checkin();
    clManager.stopEveryThingIfInTestMode();
    sleep(100);
    final File rootFile = new File(subTree.myRootDir.getPath());
    FileUtil.delete(rootFile);
    FileUtil.delete(new File(myWorkingCopyDir.getPath() + File.separator + ".svn"));
    Assert.assertTrue(!rootFile.exists());
    sleep(200);
    myWorkingCopyDir.refresh(false, true);

    verify(runSvn("co", myMainUrl));
    final File sourceDir = new File(myWorkingCopyDir.getPath(), "source");
    final File innerDir = new File(sourceDir, "inner1/inner2/inner");
    verify(runSvn("co", myExternalURL, innerDir.getPath()));
    sleep(100);
    myWorkingCopyDir.refresh(false, true);
    // above is preparation

    // start change list manager again
    clManager.forceGoInTestMode();
    myVcs.invokeRefreshSvnRoots(false);
    clManager.ensureUpToDate(false);
    clManager.ensureUpToDate(false);
  }
  public void removeCoverageSuite(final CoverageSuite suite) {
    final String fileName = suite.getCoverageDataFileName();

    boolean deleteTraces = suite.isTracingEnabled();
    if (!FileUtil.isAncestor(PathManager.getSystemPath(), fileName, false)) {
      String message = "Would you like to delete file \'" + fileName + "\' ";
      if (deleteTraces) {
        message +=
            "and traces directory \'"
                + FileUtil.getNameWithoutExtension(new File(fileName))
                + "\' ";
      }
      message += "on disk?";
      if (Messages.showYesNoDialog(
              myProject, message, CommonBundle.getWarningTitle(), Messages.getWarningIcon())
          == Messages.YES) {
        deleteCachedCoverage(fileName, deleteTraces);
      }
    } else {
      deleteCachedCoverage(fileName, deleteTraces);
    }

    myCoverageSuites.remove(suite);
    if (myCurrentSuitesBundle != null && myCurrentSuitesBundle.contains(suite)) {
      CoverageSuite[] suites = myCurrentSuitesBundle.getSuites();
      suites = ArrayUtil.remove(suites, suite);
      chooseSuitesBundle(suites.length > 0 ? new CoverageSuitesBundle(suites) : null);
    }
  }
  @Override
  public void updateDataModel() {

    myWizardContext.setProjectBuilder(myModuleBuilder);
    myWizardContext.setProjectName(myNamePathComponent.getNameValue());
    myWizardContext.setProjectFileDirectory(myNamePathComponent.getPath());
    myFormatPanel.updateData(myWizardContext);

    if (myModuleBuilder != null) {
      final String moduleName = getModuleName();
      myModuleBuilder.setName(moduleName);
      myModuleBuilder.setModuleFilePath(
          FileUtil.toSystemIndependentName(myModuleFileLocation.getText())
              + "/"
              + moduleName
              + ModuleFileType.DOT_DEFAULT_EXTENSION);
      myModuleBuilder.setContentEntryPath(FileUtil.toSystemIndependentName(getModuleContentRoot()));
      if (myModuleBuilder instanceof TemplateModuleBuilder) {
        myWizardContext.setProjectStorageFormat(StorageScheme.DIRECTORY_BASED);
      }
    }

    if (mySettingsStep != null) {
      mySettingsStep.updateDataModel();
    }
  }
  private void updateData(MavenProgressIndicator progress, File newDataDir, boolean fullUpdate)
      throws MavenIndexException {

    IndexData newData = new IndexData(newDataDir);
    try {
      doUpdateIndexData(newData, progress);
      newData.flush();
    } catch (Throwable e) {
      newData.close(true);
      FileUtil.delete(newDataDir);

      if (e instanceof MavenServerIndexerException) throw new MavenIndexException(e);
      if (e instanceof IOException) throw new MavenIndexException(e);
      throw new RuntimeException(e);
    }

    synchronized (this) {
      IndexData oldData = myData;

      myData = newData;
      myDataDirName = newDataDir.getName();

      if (fullUpdate) {
        myUpdateTimestamp = System.currentTimeMillis();
      }

      oldData.close(true);

      for (File each : FileUtil.notNullize(myDir.listFiles())) {
        if (each.getName().startsWith(DATA_DIR_PREFIX) && !each.getName().equals(myDataDirName)) {
          FileUtil.delete(each);
        }
      }
    }
  }
 public void clean() throws IOException {
   try {
     myArtifactsBuildData.clean();
   } finally {
     try {
       synchronized (mySourceToOutputLock) {
         try {
           closeSourceToOutputStorages();
         } finally {
           FileUtil.delete(getSourceToOutputsRoot());
         }
       }
     } finally {
       try {
         wipeStorage(getSourceToFormsRoot(), mySrcToFormMap);
       } finally {
         final Mappings mappings = myMappings;
         if (mappings != null) {
           synchronized (mappings) {
             mappings.clean();
           }
         } else {
           FileUtil.delete(getMappingsRoot());
         }
       }
     }
   }
 }
  protected void doTest(String xmlPath) throws IOException {
    File txtFile = new File(FileUtil.getNameWithoutExtension(xmlPath) + ".txt");

    ModuleScriptData result =
        ModuleXmlParser.parseModuleScript(
            xmlPath,
            new MessageCollector() {
              @Override
              public void report(
                  @NotNull CompilerMessageSeverity severity,
                  @NotNull String message,
                  @NotNull CompilerMessageLocation location) {
                throw new AssertionError(
                    MessageRenderer.PLAIN_FULL_PATHS.render(severity, message, location));
              }
            });

    StringBuilder sb = new StringBuilder();
    for (Module module : result.getModules()) {
      sb.append(moduleToString(module)).append("\n");
    }

    String actual = sb.toString();

    if (!txtFile.exists()) {
      FileUtil.writeToFile(txtFile, actual);
      fail("Expected data file does not exist. A new file created: " + txtFile);
    }

    JetTestUtils.assertEqualsToFile(txtFile, actual);
  }
  public static void extractEntry(
      ZipEntry entry, final InputStream inputStream, File outputDir, boolean overwrite)
      throws IOException {
    final boolean isDirectory = entry.isDirectory();

    String entryName = entry.getName();
    String relativeName = entryName.substring(JAVASCRIPT_GEN_DIR.length() + 1, entryName.length());

    final File file = new File(outputDir, relativeName);
    if (file.exists() && !overwrite) return;

    FileUtil.createParentDirs(file);
    if (isDirectory) {
      file.mkdir();
    } else {
      final BufferedInputStream is = new BufferedInputStream(inputStream);
      final BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(file));
      try {
        FileUtil.copy(is, os);
      } finally {
        os.close();
        is.close();
      }
    }
  }
  @Nullable
  public static VirtualFile findGitDir(@NotNull VirtualFile rootDir) {
    VirtualFile child = rootDir.findChild(DOT_GIT);
    if (child == null) {
      return null;
    }
    if (child.isDirectory()) {
      return child;
    }

    // this is standard for submodules, although probably it can
    String content;
    try {
      content = readFile(child);
    } catch (IOException e) {
      throw new RuntimeException("Couldn't read " + child, e);
    }
    String pathToDir;
    String prefix = "gitdir:";
    if (content.startsWith(prefix)) {
      pathToDir = content.substring(prefix.length()).trim();
    } else {
      pathToDir = content;
    }

    if (!FileUtil.isAbsolute(pathToDir)) {
      String canonicalPath = FileUtil.toCanonicalPath(FileUtil.join(rootDir.getPath(), pathToDir));
      if (canonicalPath == null) {
        return null;
      }
      pathToDir = FileUtil.toSystemIndependentName(canonicalPath);
    }
    return VcsUtil.getVirtualFileWithRefresh(new File(pathToDir));
  }
  public void testDirectoryMixed() throws Exception {
    File topDir = createTestDir("top");
    File watchedFile1 = createTestFile(topDir, "test.txt");
    File sub1Dir = createTestDir(topDir, "sub1");
    File unwatchedFile = createTestFile(sub1Dir, "test.txt");
    File sub2Dir = createTestDir(topDir, "sub2");
    File sub2subDir = createTestDir(sub2Dir, "sub");
    File watchedFile2 = createTestFile(sub2subDir, "test.txt");
    refresh(topDir);

    LocalFileSystem.WatchRequest topRequest = watch(topDir, false);
    LocalFileSystem.WatchRequest subRequest = watch(sub2Dir);
    try {
      myAccept = true;
      FileUtil.writeToFile(watchedFile1, "new content");
      FileUtil.writeToFile(watchedFile2, "new content");
      FileUtil.writeToFile(unwatchedFile, "new content");
      assertEvent(
          VFileContentChangeEvent.class,
          watchedFile1.getAbsolutePath(),
          watchedFile2.getAbsolutePath());
    } finally {
      unwatch(subRequest, topRequest);
      delete(topDir);
    }
  }
  @Override
  protected void tearDown() throws Exception {
    try {
      Disposer.dispose(myTestRootDisposable);
      cleanupSwingDataStructures();
      cleanupDeleteOnExitHookList();
    } finally {
      if (shouldContainTempFiles()) {
        FileUtil.resetCanonicalTempPathCache(ORIGINAL_TEMP_DIR);
        if (ourPathToKeep != null && FileUtil.isAncestor(myTempDir, ourPathToKeep, false)) {
          File[] files = new File(myTempDir).listFiles();
          if (files != null) {
            for (File file : files) {
              if (!FileUtil.pathsEqual(file.getPath(), ourPathToKeep)) {
                FileUtil.delete(file);
              }
            }
          }
        } else {
          FileUtil.delete(new File(myTempDir));
        }
      }
    }

    UIUtil.removeLeakingAppleListeners();
    super.tearDown();
  }
  @NotNull
  private static File copyJarFileWithoutEntry(
      @NotNull File jarPath, @NotNull String... entriesToDelete) {
    try {
      File outputFile =
          new File(
              jarPath.getParentFile(), FileUtil.getNameWithoutExtension(jarPath) + "-after.jar");
      Set<String> toDelete = SetsKt.setOf(entriesToDelete);

      @SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
      JarFile jar = new JarFile(jarPath);
      ZipOutputStream output =
          new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outputFile)));
      try {
        for (Enumeration<JarEntry> enumeration = jar.entries(); enumeration.hasMoreElements(); ) {
          JarEntry jarEntry = enumeration.nextElement();
          if (toDelete.contains(jarEntry.getName())) {
            continue;
          }
          output.putNextEntry(jarEntry);
          output.write(FileUtil.loadBytes(jar.getInputStream(jarEntry)));
          output.closeEntry();
        }
      } finally {
        output.close();
        jar.close();
      }

      return outputFile;
    } catch (IOException e) {
      throw ExceptionUtilsKt.rethrow(e);
    }
  }
 // TODO: needs to be generalized someday for other profiles
 private static boolean isValidFilename(final String filename) {
   if (filename.contains("/") || filename.contains("\\") || filename.contains(":")) {
     return false;
   }
   final File tempFile = new File(FileUtil.getTempDirectory() + File.separator + filename);
   return FileUtil.ensureCanCreateFile(tempFile);
 }
  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();
  }
  BuildSession(
      UUID sessionId,
      Channel channel,
      CmdlineRemoteProto.Message.ControllerMessage.ParametersMessage params,
      @Nullable CmdlineRemoteProto.Message.ControllerMessage.FSEvent delta) {
    mySessionId = sessionId;
    myChannel = channel;

    // globals
    Map<String, String> pathVars = new HashMap<String, String>();
    final CmdlineRemoteProto.Message.ControllerMessage.GlobalSettings globals =
        params.getGlobalSettings();
    for (CmdlineRemoteProto.Message.KeyValuePair variable : globals.getPathVariableList()) {
      pathVars.put(variable.getKey(), variable.getValue());
    }

    // session params
    myProjectPath = FileUtil.toCanonicalPath(params.getProjectId());
    String globalOptionsPath = FileUtil.toCanonicalPath(globals.getGlobalOptionsPath());
    myBuildType = convertCompileType(params.getBuildType());
    List<CmdlineRemoteProto.Message.ControllerMessage.ParametersMessage.TargetTypeBuildScope>
        scopes = params.getScopeList();
    List<String> filePaths = params.getFilePathList();
    Map<String, String> builderParams = new HashMap<String, String>();
    for (CmdlineRemoteProto.Message.KeyValuePair pair : params.getBuilderParameterList()) {
      builderParams.put(pair.getKey(), pair.getValue());
    }
    myInitialFSDelta = delta;
    JpsModelLoaderImpl loader =
        new JpsModelLoaderImpl(myProjectPath, globalOptionsPath, pathVars, null);
    myBuildRunner = new BuildRunner(loader, scopes, filePaths, builderParams);
  }
  private void checkFsSanity() {
    try {
      String path = myProject.getProjectFilePath();
      if (path == null || FileUtil.isAncestor(PathManager.getConfigPath(), path, true)) {
        return;
      }

      boolean actual = FileUtil.isFileSystemCaseSensitive(path);
      LOG.info(path + " case-sensitivity: " + actual);
      if (actual != SystemInfo.isFileSystemCaseSensitive) {
        int prefix =
            SystemInfo.isFileSystemCaseSensitive ? 1 : 0; // IDE=true -> FS=false -> prefix='in'
        String title = ApplicationBundle.message("fs.case.sensitivity.mismatch.title");
        String text = ApplicationBundle.message("fs.case.sensitivity.mismatch.message", prefix);
        Notifications.Bus.notify(
            new Notification(
                Notifications.SYSTEM_MESSAGES_GROUP_ID,
                title,
                text,
                NotificationType.WARNING,
                NotificationListener.URL_OPENING_LISTENER),
            myProject);
      }
    } catch (FileNotFoundException e) {
      LOG.warn(e);
    }
  }
 public void dispose() {
   if (myToDeleteActualFile) {
     FileUtil.delete(new File(myHyperlink.getActualFilePath()));
   }
   if (myToDeleteExpectedFile) {
     FileUtil.delete(new File(myHyperlink.getFilePath()));
   }
 }