Java Code Examples for com.intellij.openapi.util.io.FileUtil

The following examples show how to use com.intellij.openapi.util.io.FileUtil. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: intellij-quarkus   Author: redhat-developer   File: ExternalSystemTestCase.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@NotNull
protected VirtualFile createProjectJarSubFile(String relativePath, Pair<ByteArraySequence, String>... contentEntries) throws IOException {
  assertTrue("Use 'jar' extension for JAR files: '" + relativePath + "'", FileUtilRt.extensionEquals(relativePath, "jar"));
  File f = new File(getProjectPath(), relativePath);
  FileUtil.ensureExists(f.getParentFile());
  FileUtil.ensureCanCreateFile(f);
  final boolean created = f.createNewFile();
  if (!created) {
    throw new AssertionError("Unable to create the project sub file: " + f.getAbsolutePath());
  }

  Manifest manifest = new Manifest();
  manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
  JarOutputStream target = new JarOutputStream(new FileOutputStream(f), manifest);
  for (Pair<ByteArraySequence, String> contentEntry : contentEntries) {
    addJarEntry(contentEntry.first.getBytes(), contentEntry.second, target);
  }
  target.close();

  final VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(f);
  assertNotNull(virtualFile);
  final VirtualFile jarFile = JarFileSystem.getInstance().getJarRootForLocalFile(virtualFile);
  assertNotNull(jarFile);
  return jarFile;
}
 
Example #2
Source Project: consulo   Author: consulo   File: RunAnythingContext.java    License: Apache License 2.0 6 votes vote down vote up
@Nonnull
private static String calcDescription(Module module) {
  String basePath = module.getProject().getBasePath();
  if (basePath != null) {
    String modulePath = module.getModuleDirPath();
    if (modulePath == null) {
      VirtualFile[] contentRoots = ModuleRootManager.getInstance(module).getContentRoots();
      if (contentRoots.length == 1) {
        modulePath = contentRoots[0].getPath();
      }
    }

    if (modulePath != null) {
      String relativePath = FileUtil.getRelativePath(basePath, modulePath, '/');
      if (relativePath != null) {
        return relativePath;
      }
    }
  }
  return "undefined";
}
 
Example #3
Source Project: intellij-haxe   Author: HaxeFoundation   File: AbstractHaxePsiClass.java    License: Apache License 2.0 6 votes vote down vote up
@NotNull
@Override
public String getQualifiedName() {
  String name = getName();
  if (getParent() == null) {
    return name == null ? "" : name;
  }

  if (name == null && this instanceof HaxeAnonymousType) {
    // restore name from parent
    final PsiElement typedefDecl = getParent().getParent();
    if (typedefDecl != null && typedefDecl instanceof HaxeTypedefDeclaration) {
      name = ((HaxeTypedefDeclaration)typedefDecl).getName();
    }
  }

  final String fileName = FileUtil.getNameWithoutExtension(getContainingFile().getName());
  String packageName = HaxeResolveUtil.getPackageName(getContainingFile());

  if (name != null && isAncillaryClass(packageName, name, fileName)) {
    packageName = HaxeResolveUtil.joinQName(packageName, fileName);
  }

  return HaxeResolveUtil.joinQName(packageName, name);
}
 
Example #4
Source Project: consulo   Author: consulo   File: BinaryFilePatchInProgress.java    License: Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public DiffRequestProducer getDiffRequestProducers(final Project project, final PatchReader baseContents) {
  final ShelvedBinaryFile file = getPatch().getShelvedBinaryFile();
  return new DiffRequestProducer() {
    @Nonnull
    @Override
    public DiffRequest process(@Nonnull UserDataHolder context, @Nonnull ProgressIndicator indicator)
            throws DiffRequestProducerException, ProcessCanceledException {
      Change change = file.createChange(project);
      return PatchDiffRequestFactory.createDiffRequest(project, change, getName(), context, indicator);
    }

    @Nonnull
    @Override
    public String getName() {
      final File file1 = new File(VfsUtilCore.virtualToIoFile(getBase()),
                                  file.AFTER_PATH == null ? file.BEFORE_PATH : file.AFTER_PATH);
      return FileUtil.toSystemDependentName(file1.getPath());
    }
  };
}
 
Example #5
Source Project: intellij   Author: bazelbuild   File: BlazeJavascriptTestEventsHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public String getTestFilter(Project project, List<Location<?>> testLocations) {
  WorkspaceRoot root = WorkspaceRoot.fromProject(project);
  String rootName = root.directory().getName();
  String filter =
      testLocations.stream()
          .map(Location::getPsiElement)
          .map(PsiElement::getContainingFile)
          .filter(JSFile.class::isInstance)
          .map(PsiFile::getVirtualFile)
          .map(root::workspacePathFor)
          .map(WorkspacePath::relativePath)
          .map(FileUtil::getNameWithoutExtension)
          .distinct()
          .map(name -> '^' + rootName + '/' + name + '$')
          .reduce((a, b) -> a + "|" + b)
          .orElse(null);
  return filter != null
      ? String.format(
          "%s=%s", BlazeFlags.TEST_FILTER, BlazeParametersListUtil.encodeParam(filter))
      : null;
}
 
Example #6
Source Project: consulo   Author: consulo   File: FileWatcherTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testFileRoot() throws Exception {
  File file = createTestFile("test.txt");
  refresh(file);

  LocalFileSystem.WatchRequest request = watch(file);
  try {
    myAccept = true;
    FileUtil.writeToFile(file, "new content");
    assertEvent(VFileContentChangeEvent.class, file.getPath());

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

    myAccept = true;
    FileUtil.writeToFile(file, "re-creation");
    assertEvent(VFileCreateEvent.class, file.getPath());
  }
  finally {
    unwatch(request);
    delete(file);
  }
}
 
Example #7
Source Project: consulo   Author: consulo   File: SymlinkHandlingTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testFileLinkSwitch() throws Exception {
  File target1 = createTestFile(myTempDir, "target1.txt");
  FileUtil.writeToFile(target1, "some text");
  File target2 = createTestFile(myTempDir, "target2.txt");
  FileUtil.writeToFile(target2, "some quite another text");

  File link = createSymLink(target1.getPath(), myTempDir + "/link");
  VirtualFile vLink1 = refreshAndFind(link);
  assertTrue("link=" + link + ", vLink=" + vLink1,
             vLink1 != null && !vLink1.isDirectory() && vLink1.is(VFileProperty.SYMLINK));
  assertEquals(FileUtil.loadFile(target1), VfsUtilCore.loadText(vLink1));

  assertTrue(link.toString(), link.delete());
  createSymLink(target2.getPath(), myTempDir + "/" + link.getName());

  refresh();
  assertFalse(vLink1.isValid());
  VirtualFile vLink2 = myFileSystem.findFileByIoFile(link);
  assertTrue("link=" + link + ", vLink=" + vLink2,
             vLink2 != null && !vLink2.isDirectory() && vLink2.is(VFileProperty.SYMLINK));
  assertEquals(FileUtil.loadFile(target2), VfsUtilCore.loadText(vLink2));
}
 
Example #8
Source Project: consulo   Author: consulo   File: FileWatcherTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testDirectoryRecreation() throws Exception {
  File rootDir = createTestDir("root");
  File topDir = createTestDir(rootDir, "top");
  File file1 = createTestFile(topDir, "file1.txt", "abc");
  File file2 = createTestFile(topDir, "file2.txt", "123");
  refresh(topDir);

  LocalFileSystem.WatchRequest request = watch(rootDir);
  try {
    myAccept = true;
    assertTrue(FileUtil.delete(topDir));
    assertTrue(topDir.mkdir());
    TimeoutUtil.sleep(100);
    assertTrue(file1.createNewFile());
    assertTrue(file2.createNewFile());
    assertEvent(VFileContentChangeEvent.class, file1.getPath(), file2.getPath());
  }
  finally {
    unwatch(request);
    delete(topDir);
  }
}
 
Example #9
Source Project: consulo   Author: consulo   File: FileWatcherTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testIncorrectPath() throws Exception {
  File topDir = createTestDir("top");
  File file = createTestFile(topDir, "file.zip");
  File subDir = new File(file, "sub/zip");
  refresh(topDir);

  LocalFileSystem.WatchRequest request = watch(subDir, false);
  try {
    myTimeout = 10 * INTER_RESPONSE_DELAY;
    myAccept = true;
    FileUtil.writeToFile(file, "new content");
    assertEvent(VFileEvent.class);
    myTimeout = NATIVE_PROCESS_DELAY;
  }
  finally {
    unwatch(request);
    delete(topDir);
  }
}
 
Example #10
Source Project: consulo   Author: consulo   File: PersistentMapTest.java    License: Apache License 2.0 6 votes vote down vote up
public void test2GLimit() throws IOException {
  if (!DO_SLOW_TEST) return;
  File file = FileUtil.createTempFile("persistent", "map");
  FileUtil.createParentDirs(file);
  EnumeratorStringDescriptor stringDescriptor = new EnumeratorStringDescriptor();
  PersistentHashMap<String, String> map = new PersistentHashMap<String, String>(file, stringDescriptor, stringDescriptor);
  for (int i = 0; i < 12000; i++) {
    map.put("abc" + i, StringUtil.repeat("0123456789", 10000));
  }
  map.close();

  map = new PersistentHashMap<String, String>(file,
                                              stringDescriptor, stringDescriptor);
  long len = 0;
  for (String key : map.getAllKeysWithExistingMapping()) {
    len += map.get(key).length();
  }
  map.close();
  assertEquals(1200000000L, len);
}
 
Example #11
Source Project: consulo   Author: consulo   File: HeavyIdeaTestFixtureImpl.java    License: Apache License 2.0 6 votes vote down vote up
private void setUpProject() throws Exception {
  new WriteCommandAction.Simple(null) {
    @Override
    protected void run() throws Throwable {
      File projectDir = FileUtil.createTempDirectory(myName + "_", "project");
      FileUtil.delete(projectDir);
      myFilesToDelete.add(projectDir);

      LocalFileSystem.getInstance().refreshAndFindFileByIoFile(projectDir);
      ByteArrayOutputStream buffer = new ByteArrayOutputStream();
      new Throwable(projectDir.getPath()).printStackTrace(new PrintStream(buffer));
      myProject = PlatformTestCase.createProject(projectDir, buffer.toString());

      for (ModuleFixtureBuilder moduleFixtureBuilder : myModuleFixtureBuilders) {
        moduleFixtureBuilder.getFixture().setUp();
      }

      StartupManagerImpl sm = (StartupManagerImpl)StartupManager.getInstance(myProject);
      sm.runStartupActivities(UIAccess.get());
      sm.runPostStartupActivities(UIAccess.get());

      ProjectManagerEx.getInstanceEx().openTestProject(myProject);
      LightPlatformTestCase.clearUncommittedDocuments(myProject);
    }
  }.execute().throwException();
}
 
Example #12
Source Project: consulo   Author: consulo   File: CreateDesktopEntryAction.java    License: Apache License 2.0 6 votes vote down vote up
private static File prepare() throws IOException {
  File distributionDirectory = ContainerPathManager.get().getAppHomeDirectory();
  String name = ApplicationNamesInfo.getInstance().getFullProductName();

  final String iconPath = AppUIUtil.findIcon(distributionDirectory.getPath());
  if (iconPath == null) {
    throw new RuntimeException(ApplicationBundle.message("desktop.entry.icon.missing", distributionDirectory.getPath()));
  }

  final File execPath = new File(distributionDirectory, "consulo.sh");
  if (!execPath.exists()) {
    throw new RuntimeException(ApplicationBundle.message("desktop.entry.script.missing", distributionDirectory.getPath()));
  }

  final String wmClass = AppUIUtil.getFrameClass();

  final String content = ExecUtil.loadTemplate(CreateDesktopEntryAction.class.getClassLoader(), "entry.desktop", ContainerUtil
          .newHashMap(Arrays.asList("$NAME$", "$SCRIPT$", "$ICON$", "$WM_CLASS$"), Arrays.asList(name, execPath.getPath(), iconPath, wmClass)));

  final String entryName = wmClass + ".desktop";
  final File entryFile = new File(FileUtil.getTempDirectory(), entryName);
  FileUtil.writeToFile(entryFile, content);
  entryFile.deleteOnExit();
  return entryFile;
}
 
Example #13
Source Project: EclipseCodeFormatter   Author: krasa   File: CachedProviderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGet() throws Exception {
	FileUtil.writeToFile(tempFile, "foo");
	tempFile.setLastModified(1000);
	String s = cachedProvider.get();
	Assert.assertEquals("foo", s);

	FileUtil.writeToFile(tempFile, "bar");

	tempFile.setLastModified(1000);
	s = cachedProvider.get();
	Assert.assertEquals("foo", s);

	tempFile.setLastModified(2000);
	s = cachedProvider.get();
	Assert.assertEquals("bar", s);
}
 
Example #14
Source Project: consulo   Author: consulo   File: IoFileBasedStorage.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doSave(@Nullable Element element) throws IOException {
  if (myLineSeparator == null) {
    myLineSeparator = isUseLfLineSeparatorByDefault() ? LineSeparator.LF : LineSeparator.getSystemLineSeparator();
  }

  byte[] content = element == null ? null : StorageUtil.writeToBytes(element, myLineSeparator.getSeparatorString());
  try {
    if (myStreamProvider != null && myStreamProvider.isEnabled()) {
      // stream provider always use LF separator
      saveForProvider(myLineSeparator == LineSeparator.LF ? content : null, element);
    }
  }
  catch (Throwable e) {
    LOG.error(e);
  }

  if (content == null) {
    StorageUtil.deleteFile(myFile);
  }
  else {
    FileUtil.createParentDirs(myFile);

    StorageUtil.writeFile(myFile, content, isUseXmlProlog() ? myLineSeparator : null);
  }
}
 
Example #15
Source Project: consulo   Author: consulo   File: ZipUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static boolean addDirToZipRecursively(@Nonnull ZipOutputStream outputStream,
                                             @Nullable File jarFile,
                                             @Nonnull File dir,
                                             @Nonnull String relativePath,
                                             @Nullable FileFilter fileFilter,
                                             @Nullable Set<String> writtenItemRelativePaths) throws IOException {
  if (jarFile != null && FileUtil.isAncestor(dir, jarFile, false)) {
    return false;
  }
  if (relativePath.length() != 0) {
    addFileToZip(outputStream, dir, relativePath, writtenItemRelativePaths, fileFilter);
  }
  final File[] children = dir.listFiles();
  if (children != null) {
    for (File child : children) {
      final String childRelativePath = (relativePath.length() == 0 ? "" : relativePath + "/") + child.getName();
      addFileOrDirRecursively(outputStream, jarFile, child, childRelativePath, fileFilter, writtenItemRelativePaths);
    }
  }
  return true;
}
 
Example #16
Source Project: intellij-haxe   Author: HaxeFoundation   File: HaxeTestsRunner.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected RunContentDescriptor doExecute(@NotNull final Project project,
                                         @NotNull RunProfileState state,
                                         final RunContentDescriptor descriptor,
                                         @NotNull final ExecutionEnvironment environment) throws ExecutionException {

  final HaxeTestsConfiguration profile = (HaxeTestsConfiguration)environment.getRunProfile();
  final Module module = profile.getConfigurationModule().getModule();

  ModuleRootManager rootManager = ModuleRootManager.getInstance(module);
  VirtualFile[] roots = rootManager.getContentRoots();

  return super.doExecute(project, new CommandLineState(environment) {
    @NotNull
    @Override
    protected ProcessHandler startProcess() throws ExecutionException {
      //actually only neko target is supported for tests
      HaxeTarget currentTarget = HaxeTarget.NEKO;
      final GeneralCommandLine commandLine = new GeneralCommandLine();
      commandLine.setWorkDirectory(PathUtil.getParentPath(module.getModuleFilePath()));
      commandLine.setExePath(currentTarget.getFlag());
      final HaxeModuleSettings settings = HaxeModuleSettings.getInstance(module);
      String folder = settings.getOutputFolder() != null ? (settings.getOutputFolder() + "/release/") : "";
      commandLine.addParameter(getFileNameWithCurrentExtension(currentTarget, folder + settings.getOutputFileName()));

      final TextConsoleBuilder consoleBuilder = TextConsoleBuilderFactory.getInstance().createBuilder(module.getProject());
      consoleBuilder.addFilter(new ErrorFilter(module));
      setConsoleBuilder(consoleBuilder);

      return new OSProcessHandler(commandLine.createProcess(), commandLine.getCommandLineString());
    }

    private String getFileNameWithCurrentExtension(HaxeTarget haxeTarget, String fileName) {
      if (haxeTarget != null) {
        return haxeTarget.getTargetFileNameWithExtension(FileUtil.getNameWithoutExtension(fileName));
      }
      return fileName;
    }
  }, descriptor, environment);
}
 
Example #17
Source Project: consulo   Author: consulo   File: BaseApplication.java    License: Apache License 2.0 5 votes vote down vote up
private static void createLocatorFile() {
  ContainerPathManager containerPathManager = ContainerPathManager.get();
  File locatorFile = new File(containerPathManager.getSystemPath() + "/" + ApplicationEx.LOCATOR_FILE_NAME);
  try {
    byte[] data = containerPathManager.getHomePath().getBytes(CharsetToolkit.UTF8_CHARSET);
    FileUtil.writeToFile(locatorFile, data);
  }
  catch (IOException e) {
    LOG.warn("can't store a location in '" + locatorFile + "'", e);
  }
}
 
Example #18
Source Project: consulo   Author: consulo   File: AbstractStorage.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean deleteFiles(String storageFilePath) {
  final File recordsFile = new File(storageFilePath + INDEX_EXTENSION);
  final File dataFile = new File(storageFilePath + DATA_EXTENSION);

  // ensure both files deleted
  final boolean deletedRecordsFile = FileUtil.delete(recordsFile);
  final boolean deletedDataFile = FileUtil.delete(dataFile);
  return deletedRecordsFile && deletedDataFile;
}
 
Example #19
Source Project: consulo   Author: consulo   File: VfsUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static String getUrlForLibraryRoot(@Nonnull File libraryRoot) {
  String path = FileUtil.toSystemIndependentName(libraryRoot.getAbsolutePath());
  final FileType fileTypeByFileName = FileTypeManager.getInstance().getFileTypeByFileName(libraryRoot.getName());
  if (fileTypeByFileName instanceof ArchiveFileType) {

    final String protocol = ((ArchiveFileType)fileTypeByFileName).getProtocol();

    return VirtualFileManager.constructUrl(protocol, path + ArchiveFileSystem.ARCHIVE_SEPARATOR);
  }
  else {
    return VirtualFileManager.constructUrl(LocalFileSystem.getInstance().getProtocol(), path);
  }
}
 
Example #20
Source Project: BashSupport   Author: BashSupport   File: FileRenameTest.java    License: Apache License 2.0 5 votes vote down vote up
private void doRename(boolean expectFileReference, Runnable renameLogic, String... sourceFiles) {
    myFixture.setTestDataPath(getTestDataPath() + getTestName(true));

    List<String> filenames = Lists.newArrayList(sourceFiles);
    filenames.add("target.bash");
    myFixture.configureByFiles(filenames.toArray(new String[filenames.size()]));

    renameLogic.run();

    for (String filename : sourceFiles) {
        myFixture.checkResultByFile(filename, FileUtil.getNameWithoutExtension(filename) + "_after." + FileUtilRt.getExtension(filename), false);
    }

    PsiElement psiElement;
    if (expectFileReference) {
        psiElement = PsiTreeUtil.getParentOfType(myFixture.getFile().findElementAt(myFixture.getCaretOffset()), BashFileReference.class);
        Assert.assertNotNull("file reference is null. Current: " + myFixture.getFile().findElementAt(myFixture.getCaretOffset()).getText(), psiElement);
        Assert.assertTrue("Filename wasn't changed", psiElement.getText().contains("target_renamed.bash"));
    } else {
        psiElement = myFixture.getFile().findElementAt(myFixture.getCaretOffset());
        Assert.assertNotNull("caret element is null", psiElement);

        while (psiElement.getReference() == null) {
            if (psiElement.getParent() == null) {
                break;
            }

            psiElement = psiElement.getParent();
        }
    }


    PsiReference psiReference = psiElement.getReference();
    Assert.assertNotNull("target file reference wasn't found", psiReference);
    Assert.assertTrue("Renamed reference wasn't found in the canonical text", psiReference.getCanonicalText().contains("target_renamed.bash"));

    PsiElement targetFile = psiReference.resolve();
    Assert.assertNotNull("target file resolve result wasn't found", targetFile);
    Assert.assertTrue("target is not a psi file", targetFile instanceof BashFile);
}
 
Example #21
Source Project: consulo   Author: consulo   File: PsiAwareFileEditorManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public String getFileTooltipText(@Nonnull final VirtualFile file) {
  final StringBuilder tooltipText = new StringBuilder();
  final Module module = ModuleUtilCore.findModuleForFile(file, getProject());
  if (module != null) {
    tooltipText.append("[");
    tooltipText.append(module.getName());
    tooltipText.append("] ");
  }
  tooltipText.append(FileUtil.getLocationRelativeToUserHome(file.getPresentableUrl()));
  return tooltipText.toString();
}
 
Example #22
Source Project: intellij-pants-plugin   Author: pantsbuild   File: IJRCTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testRcPickup() throws IOException {
  File temp = new File(getHomePath(), IJRC.IMPORT_RC_FILENAME);
  FileUtil.writeToFile(temp, "123");
  Optional<String> rc = IJRC.getImportPantsRc(temp.getParent());
  assertTrue(rc.isPresent());
  assertEquals(String.format("--pantsrc-files=%s", temp.getPath()), rc.get());
  temp.delete();
}
 
Example #23
Source Project: consulo   Author: consulo   File: LogConfigurationPanel.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void resetEditorFrom(final RunConfigurationBase configuration) {
  ArrayList<LogFileOptions> list = new ArrayList<LogFileOptions>();
  final ArrayList<LogFileOptions> logFiles = configuration.getLogFiles();
  for (LogFileOptions setting : logFiles) {
    list.add(
      new LogFileOptions(setting.getName(), setting.getPathPattern(), setting.isEnabled(), setting.isSkipContent(), setting.isShowAll()));
  }
  myLog2Predefined.clear();
  myUnresolvedPredefined.clear();
  final ArrayList<PredefinedLogFile> predefinedLogFiles = configuration.getPredefinedLogFiles();
  for (PredefinedLogFile predefinedLogFile : predefinedLogFiles) {
    PredefinedLogFile logFile = new PredefinedLogFile(predefinedLogFile);
    final LogFileOptions options = configuration.getOptionsForPredefinedLogFile(logFile);
    if (options != null) {
      myLog2Predefined.put(options, logFile);
      list.add(options);
    }
    else {
      myUnresolvedPredefined.add(logFile);
    }
  }
  myModel.setItems(list);
  final boolean redirectOutputToFile = configuration.isSaveOutputToFile();
  myRedirectOutputCb.setSelected(redirectOutputToFile);
  final String fileOutputPath = configuration.getOutputFilePath();
  myOutputFile.setText(fileOutputPath != null ? FileUtil.toSystemDependentName(fileOutputPath) : "");
  myOutputFile.setEnabled(redirectOutputToFile);
  myShowConsoleOnStdOutCb.setSelected(configuration.isShowConsoleOnStdOut());
  myShowConsoleOnStdErrCb.setSelected(configuration.isShowConsoleOnStdErr());
}
 
Example #24
Source Project: consulo   Author: consulo   File: CompilerCacheManager.java    License: Apache License 2.0 5 votes vote down vote up
public void clearCaches(final CompileContext context) {
  flushCaches();
  final File[] children = myCachesRoot.listFiles();
  if (children != null) {
    for (final File child : children) {
      final boolean deleteOk = FileUtil.delete(child);
      if (!deleteOk) {
        context.addMessage(CompilerMessageCategory.ERROR, CompilerBundle.message("compiler.error.failed.to.delete", child.getPath()), null, -1, -1);
      }
    }
  }
}
 
Example #25
Source Project: consulo   Author: consulo   File: LocalFileSystemTest.java    License: Apache License 2.0 5 votes vote down vote up
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_");

  VirtualFile topDir = myFS.refreshAndFindFileByIoFile(top);
  assertNotNull(topDir);
  VirtualFile sourceFile = myFS.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(Locale.ENGLISH);
  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());
}
 
Example #26
Source Project: consulo   Author: consulo   File: UniqueVFilePathBuilderImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
private static UniqueNameBuilder<VirtualFile> filesWithTheSameName(String fileName, Project project,
                                                                   boolean skipNonOpenedFiles,
                                                                   GlobalSearchScope scope) {
  Collection<VirtualFile> filesWithSameName = skipNonOpenedFiles ? Collections.emptySet() :
                                              FilenameIndex.getVirtualFilesByName(project, fileName,
                                                                                  scope);
  THashSet<VirtualFile> setOfFilesWithTheSameName = new THashSet<>(filesWithSameName);
  // add open files out of project scope
  for(VirtualFile openFile: FileEditorManager.getInstance(project).getOpenFiles()) {
    if (openFile.getName().equals(fileName)) {
      setOfFilesWithTheSameName.add(openFile);
    }
  }
  if (!skipNonOpenedFiles) {
    for (VirtualFile recentlyEditedFile : EditorHistoryManager.getInstance(project).getFiles()) {
      if (recentlyEditedFile.getName().equals(fileName)) {
        setOfFilesWithTheSameName.add(recentlyEditedFile);
      }
    }
  }

  filesWithSameName = setOfFilesWithTheSameName;

  if (filesWithSameName.size() > 1) {
    String path = project.getBasePath();
    path = path == null ? "" : FileUtil.toSystemIndependentName(path);
    UniqueNameBuilder<VirtualFile> builder = new UniqueNameBuilder<>(path, File.separator, 25);
    for (VirtualFile virtualFile: filesWithSameName) {
      builder.addPath(virtualFile, virtualFile.getPath());
    }
    return builder;
  }
  return null;
}
 
Example #27
Source Project: intellij-pants-plugin   Author: pantsbuild   File: PantsSystemProjectResolver.java    License: Apache License 2.0 5 votes vote down vote up
private boolean containsContentRoot(@NotNull DataNode<ProjectData> projectDataNode, @NotNull String path) {
  for (DataNode<ModuleData> moduleDataNode : ExternalSystemApiUtil.findAll(projectDataNode, ProjectKeys.MODULE)) {
    for (DataNode<ContentRootData> contentRootDataNode : ExternalSystemApiUtil.findAll(moduleDataNode, ProjectKeys.CONTENT_ROOT)) {
      final ContentRootData contentRootData = contentRootDataNode.getData();
      if (FileUtil.isAncestor(contentRootData.getRootPath(), path, false)) {
        return true;
      }
    }
  }

  return false;
}
 
Example #28
Source Project: consulo   Author: consulo   File: TempFiles.java    License: Apache License 2.0 5 votes vote down vote up
private File createTempDir(@Nonnull String prefix) {
  try {
    File dir = FileUtil.createTempDirectory(prefix, "test",false);
    tempFileCreated(dir);
    getVFileByFile(dir);
    return dir;
  }
  catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example #29
Source Project: BashSupport   Author: BashSupport   File: RenameVariableTest.java    License: Apache License 2.0 5 votes vote down vote up
private void doRename(Runnable renameLogic, String... sourceFiles) {
    myFixture.setTestDataPath(getTestDataPath() + getTestName(true));

    List<String> filenames = Lists.newArrayList(sourceFiles);
    myFixture.configureByFiles(filenames.toArray(new String[filenames.size()]));

    renameLogic.run();

    for (String filename : filenames) {
        myFixture.checkResultByFile(filename, FileUtil.getNameWithoutExtension(filename) + "_after." + FileUtilRt.getExtension(filename), false);
    }

    PsiElement psiElement = myFixture.getFile().findElementAt(myFixture.getCaretOffset());
    Assert.assertNotNull("caret element is null", psiElement);

    while (psiElement.getReference() == null) {
        if (psiElement.getParent() == null) {
            break;
        }

        psiElement = psiElement.getParent();
    }

    PsiReference psiReference = psiElement.getReference();
    Assert.assertNotNull("target reference wasn't found", psiReference);
    Assert.assertTrue("Renamed reference wasn't found in the canonical text", psiReference.getCanonicalText().contains("a_renamed"));

    PsiElement targetVariable = psiReference.resolve();
    if (!(psiElement instanceof BashVarDef)) {
        Assert.assertNotNull("target resolve result wasn't found", targetVariable);
        Assert.assertTrue("target is not a psi function definition", targetVariable instanceof BashVarDef);
    }
}
 
Example #30
Source Project: consulo   Author: consulo   File: ShelveChangesManager.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
// for create patch only
public static File suggestPatchName(Project project, @Nonnull final String commitMessage, final File file, String extension) {
  @NonNls String defaultPath = shortenAndSanitize(commitMessage);
  while (true) {
    final File nonexistentFile = FileUtil.findSequentNonexistentFile(file, defaultPath, extension == null
                                                                                        ? VcsConfiguration.getInstance(project).getPatchFileExtension()
                                                                                        : extension);
    if (nonexistentFile.getName().length() >= PatchNameChecker.MAX) {
      defaultPath = defaultPath.substring(0, defaultPath.length() - 1);
      continue;
    }
    return nonexistentFile;
  }
}