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

The following examples show how to use com.intellij.openapi.util.io.FileUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CreateDesktopEntryAction.java    From consulo with 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 #2
Source File: IoFileBasedStorage.java    From consulo with 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 #3
Source File: CachedProviderTest.java    From EclipseCodeFormatter with 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 #4
Source File: ZipUtil.java    From consulo with 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 #5
Source File: ExternalSystemTestCase.java    From intellij-quarkus with 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 #6
Source File: RunAnythingContext.java    From consulo with 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 #7
Source File: HeavyIdeaTestFixtureImpl.java    From consulo with 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 #8
Source File: AbstractHaxePsiClass.java    From intellij-haxe with 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 #9
Source File: PersistentMapTest.java    From consulo with 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 #10
Source File: FileWatcherTest.java    From consulo with 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 #11
Source File: FileWatcherTest.java    From consulo with 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 #12
Source File: BinaryFilePatchInProgress.java    From consulo with 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 #13
Source File: BlazeJavascriptTestEventsHandler.java    From intellij with 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 #14
Source File: SymlinkHandlingTest.java    From consulo with 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 #15
Source File: FileWatcherTest.java    From consulo with 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 #16
Source File: MatchPatchPaths.java    From consulo with Apache License 2.0 5 votes vote down vote up
private Collection<VirtualFile> findFilesFromIndex(@Nonnull final PatchBaseDirectoryDetector directoryDetector,
                                                   @Nonnull final String fileName) {
  Collection<VirtualFile> files = ApplicationManager.getApplication().runReadAction(new Computable<Collection<VirtualFile>>() {
    public Collection<VirtualFile> compute() {
      return directoryDetector.findFiles(fileName);
    }
  });
  final File shelfResourcesDirectory = ShelveChangesManager.getInstance(myProject).getShelfResourcesDirectory();
  return ContainerUtil.filter(files, new Condition<VirtualFile>() {
    @Override
    public boolean value(VirtualFile file) {
      return !FileUtil.isAncestor(shelfResourcesDirectory, VfsUtilCore.virtualToIoFile(file), false);
    }
  });
}
 
Example #17
Source File: DesktopContainerPathManager.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void loadProperties() {
  List<String> paths = new ArrayList<>();
  paths.add(System.getProperty(PROPERTIES_FILE));
  paths.add(System.getProperty(OLD_PROPERTIES_FILE));
  paths.add(new File(getAppHomeDirectory(), "consulo.properties").getPath());
  paths.add(getUserHome() + "/consulo.properties");

  File propFile = FileUtil.findFirstThatExist(ArrayUtil.toStringArray(paths));

  if (propFile == null) {
    return;
  }

  try (InputStream fis = new BufferedInputStream(new FileInputStream(propFile))) {
    final PropertyResourceBundle bundle = new PropertyResourceBundle(fis);
    final Enumeration keys = bundle.getKeys();
    String home = (String)bundle.handleGetObject("idea.home");
    if (home != null && ourHomePath == null) {
      ourHomePath = getAbsolutePath(substituteVars(home));
    }
    final Properties sysProperties = System.getProperties();
    while (keys.hasMoreElements()) {
      String key = (String)keys.nextElement();
      if (sysProperties.getProperty(key, null) == null) { // load the property from the property file only if it is not defined yet
        final String value = substituteVars(bundle.getString(key));
        sysProperties.setProperty(key, value);
      }
    }
  }
  catch (IOException e) {
    //noinspection HardCodedStringLiteral,UseOfSystemOutOrSystemErr
    System.err.println("Problem reading from property file: " + propFile.getPath());
  }
}
 
Example #18
Source File: CodeInsightTestUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void doActionTest(AnAction action, String file, CodeInsightTestFixture fixture) {
  String extension = FileUtilRt.getExtension(file);
  String name = FileUtil.getNameWithoutExtension(file);
  fixture.configureByFile(file);
  fixture.testAction(action);
  fixture.checkResultByFile(name + "_after." + extension);
}
 
Example #19
Source File: BackgroundTaskByVfsChangePanel.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void reset(@Nonnull BackgroundTaskByVfsParameters parameters) {
  myProgramParametersPanel.reset(parameters);
  myExePath.setText(FileUtil.toSystemDependentName(StringUtil.notNullize(parameters.getExePath())));
  myOutPath.setText(FileUtil.toSystemDependentName(StringUtil.notNullize(parameters.getOutPath())));
  myShowConsoleCheckBox.setSelected(parameters.isShowConsole());
  UIUtil.setEnabled(this, parameters != BackgroundTaskByVfsParametersImpl.EMPTY, true);
}
 
Example #20
Source File: LocalFileSystemTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void testWindowsHiddenDirectory() throws Exception {
  if (!SystemInfo.isWindows) {
    System.err.println(getName() + " skipped: " + SystemInfo.OS_NAME);
    return;
  }

  File file = new File("C:\\Documents and Settings\\desktop.ini");
  if (!file.exists()) {
    System.err.println(getName() + " skipped: missing " + file);
    return;
  }

  String parent = FileUtil.toSystemIndependentName(file.getParent());
  VfsRootAccess.allowRootAccess(parent);
  try {
    VirtualFile virtualFile = myFS.refreshAndFindFileByIoFile(file);
    assertNotNull(virtualFile);

    NewVirtualFileSystem fs = (NewVirtualFileSystem)virtualFile.getFileSystem();
    FileAttributes attributes = fs.getAttributes(virtualFile);
    assertNotNull(attributes);
    assertEquals(FileAttributes.Type.FILE, attributes.type);
    assertEquals(FileAttributes.HIDDEN, attributes.flags);
  }
  finally {
    VfsRootAccess.disallowRootAccess(parent);
  }
}
 
Example #21
Source File: SimpleCoverageAnnotator.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static @Nonnull
String normalizeFilePath(@Nonnull String filePath) {
  if (SystemInfo.isWindows) {
    filePath = filePath.toLowerCase();
  }
  return FileUtil.toSystemIndependentName(filePath);
}
 
Example #22
Source File: BuildTargetFinder.java    From intellij with Apache License 2.0 5 votes vote down vote up
/**
 * Finds a BUILD file to sync for the given file. Returns null if no build file is found, or the
 * build file isn't covered by the .bazelproject directories.
 */
@Nullable
public File findBuildFileForFile(File file) {
  if (fileOperationProvider.isFile(file)) {
    file = file.getParentFile();
    if (file == null) {
      return null;
    }
  }
  WorkspacePath path = workspaceRoot.workspacePathForSafe(file);
  if (path == null || !importRoots.containsWorkspacePath(path)) {
    return null;
  }
  final File directory = file;
  File root =
      importRoots
          .rootDirectories()
          .stream()
          .map(workspaceRoot::fileForPath)
          .filter(potentialRoot -> FileUtil.isAncestor(potentialRoot, directory, false))
          .findFirst()
          .orElse(null);
  if (root == null) {
    return null;
  }

  File currentDirectory = directory;
  do {
    File buildFile = buildSystemProvider.findBuildFileInDirectory(currentDirectory);
    if (buildFile != null) {
      return buildFile;
    }
    currentDirectory = currentDirectory.getParentFile();
  } while (currentDirectory != null && FileUtil.isAncestor(root, currentDirectory, false));

  return null;
}
 
Example #23
Source File: HaxeTestsRunner.java    From intellij-haxe with 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 #24
Source File: LoadAllContentsAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
  final Project project = e.getDataContext().getData(CommonDataKeys.PROJECT);
  String m = "Started loading content";
  LOG.info(m);
  System.out.println(m);
  long start = System.currentTimeMillis();
  count.set(0);
  totalSize.set(0);
  ApplicationManagerEx.getApplicationEx().runProcessWithProgressSynchronously(new Runnable() {
    @Override
    public void run() {
      ProjectRootManager.getInstance(project).getFileIndex().iterateContent(new ContentIterator() {
        @Override
        public boolean processFile(VirtualFile fileOrDir) {
          if (fileOrDir.isDirectory() || fileOrDir.is(VFileProperty.SPECIAL)) return true;
          try {
            count.incrementAndGet();
            byte[] bytes = FileUtil.loadFileBytes(new File(fileOrDir.getPath()));
            totalSize.addAndGet(bytes.length);
            ProgressManager.getInstance().getProgressIndicator().setText(fileOrDir.getPresentableUrl());
          }
          catch (IOException e1) {
            LOG.error(e1);
          }
          return true;
        }
      });
     }
  }, "Loading", false, project);
  long end = System.currentTimeMillis();
  String message = "Finished loading content of " + count + " files. Total size=" + StringUtil.formatFileSize(totalSize.get()) +
                   ". Elapsed=" + ((end - start) / 1000) + "sec.";
  LOG.info(message);
  System.out.println(message);
}
 
Example #25
Source File: ShelveChangesManager.java    From consulo with 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;
  }
}
 
Example #26
Source File: FileAttribute.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
public byte[] readAttributeBytes(VirtualFile file) throws IOException {
  final DataInputStream stream = readAttribute(file);
  if (stream == null) return null;

  try {
    int len = stream.readInt();
    return FileUtil.loadBytes(stream, len);
  }
  finally {
    stream.close();
  }
}
 
Example #27
Source File: PropertiesEncryptionSupport.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public Properties load(@Nonnull File file) throws Exception {
  final byte[] bytes = decrypt(FileUtil.loadFileBytes(file));
  final Properties props = new Properties();
  props.load(new ByteArrayInputStream(bytes));
  return props;
}
 
Example #28
Source File: Executor.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void cp(String fileName, File destinationDir) {
  try {
    FileUtil.copy(child(fileName), new File(destinationDir, fileName));
  }
  catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example #29
Source File: RenameVariableTest.java    From BashSupport with 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 File: VcsLogStructureFilterImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private boolean matches(@Nonnull final String path) {
  return ContainerUtil.find(myFiles, new Condition<VirtualFile>() {
    @Override
    public boolean value(VirtualFile file) {
      return FileUtil.isAncestor(file.getPath(), path, false);
    }
  }) != null;
}