Java Code Examples for com.intellij.openapi.util.io.FileUtil#isAncestor()

The following examples show how to use com.intellij.openapi.util.io.FileUtil#isAncestor() . 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: ContentRootData.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * Ask to remember that directory at the given path contains sources of the given type.
 *
 * @param type           target sources type
 * @param path           target source directory path
 * @param packagePrefix  target source directory package prefix
 * @throws IllegalArgumentException   if given path points to the directory that is not located
 *                                    under the {@link #getRootPath() content root}
 */
public void storePath(@Nonnull ExternalSystemSourceType type, @Nonnull String path, @javax.annotation.Nullable String packagePrefix) throws IllegalArgumentException {
  if (FileUtil.isAncestor(new File(getRootPath()), new File(path), false)) {
    Collection<SourceRoot> paths = myData.get(type);
    if (paths == null) {
      myData.put(type, paths = new TreeSet<SourceRoot>(SourceRootComparator.INSTANCE));
    }
    paths.add(new SourceRoot(
            ExternalSystemApiUtil.toCanonicalPath(path),
            StringUtil.nullize(packagePrefix, true)
    ));
    return;
  }
  if (!ExternalSystemSourceType.EXCLUDED.equals(type)) { // There are external systems which mark output directory as 'excluded' path.
    // We don't need to bother if it's outside a module content root then.
    throw new IllegalArgumentException(String.format(
            "Can't register given path of type '%s' because it's out of content root.%nContent root: '%s'%nGiven path: '%s'",
            type, getRootPath(), new File(path).getAbsolutePath()
    ));
  }
}
 
Example 2
Source File: NonProjectFileWritingAccessProvider.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static boolean isWriteAccessAllowed(@Nonnull VirtualFile file, @Nonnull Project project) {
  if (isAllAccessAllowed()) return true;
  if (file.isDirectory()) return true;

  if (!(file.getFileSystem() instanceof LocalFileSystem)) return true; // do not block e.g., HttpFileSystem, LightFileSystem etc.
  if (file.getFileSystem() instanceof TempFileSystem) return true;

  if (ArrayUtil.contains(file, IdeDocumentHistory.getInstance(project).getChangedFiles())) return true;

  if (!getApp().isUnitTestMode() && FileUtil.isAncestor(new File(FileUtil.getTempDirectory()), VfsUtilCore.virtualToIoFile(file), true)) {
    return true;
  }

  VirtualFile each = file;
  while (each != null) {
    if (ACCESS_ALLOWED.getValue(each).get() > 0) return true;
    each = each.getParent();
  }

  return isProjectFile(file, project);
}
 
Example 3
Source File: StartupManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void checkFsSanity() {
  try {
    String path = myProject.getBasePath();
    if (path == null || FileUtil.isAncestor(ContainerPathManager.get().getConfigPath(), path, true)) {
      return;
    }

    boolean expected = SystemInfo.isFileSystemCaseSensitive;
    boolean actual = FileUtil.isFileSystemCaseSensitive(path);
    LOG.info(path + " case-sensitivity: expected=" + expected + " actual=" + actual);
    if (actual != expected) {
      int prefix = expected ? 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);
    }

    //ProjectFsStatsCollector.caseSensitivity(myProject, actual);
  }
  catch (FileNotFoundException e) {
    LOG.warn(e);
  }
}
 
Example 4
Source File: WorkspacePathUtil.java    From intellij with Apache License 2.0 6 votes vote down vote up
private static boolean includePath(
    Collection<WorkspacePath> workspacePaths,
    Collection<WorkspacePath> excludedPaths,
    WorkspacePath path) {
  for (WorkspacePath excluded : excludedPaths) {
    if (FileUtil.isAncestor(excluded.relativePath(), path.relativePath(), false)) {
      return false;
    }
  }
  for (WorkspacePath otherDirectory : workspacePaths) {
    if (path.equals(otherDirectory)) {
      continue;
    }
    if (FileUtil.isAncestor(otherDirectory.relativePath(), path.relativePath(), true)) {
      return false;
    }
  }
  return true;
}
 
Example 5
Source File: VMOptions.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
public static File getWriteFile() {
  String vmOptionsFile = System.getProperty("jb.vmOptionsFile");
  if (vmOptionsFile == null) {
    // launchers should specify a path to an options file used to configure a JVM
    return null;
  }

  vmOptionsFile = new File(vmOptionsFile).getAbsolutePath();
  if (!FileUtil.isAncestor(ContainerPathManager.get().getHomePath(), vmOptionsFile, true)) {
    // a file is located outside the IDE installation - meaning it is safe to overwrite
    return new File(vmOptionsFile);
  }

  File appHomeDirectory = ContainerPathManager.get().getAppHomeDirectory();

  String fileName = ApplicationNamesInfo.getInstance().getProductName().toLowerCase(Locale.US);
  if (SystemInfo.is64Bit && !SystemInfo.isMac) fileName += "64";
  if (SystemInfo.isWindows) fileName += ".exe";
  fileName += ".vmoptions";
  return new File(appHomeDirectory, fileName);
}
 
Example 6
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 7
Source File: UsefulTestCase.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected void tearDown() throws Exception {
  try {
    Disposer.dispose(myTestRootDisposable);
    cleanupSwingDataStructures();
  }
  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();
}
 
Example 8
Source File: InsightUpdateQueue.java    From reasonml-idea-plugin with MIT License 5 votes vote down vote up
public void initConfig(@NotNull Project project) {
    LOG.debug("Refresh bsconfig");

    BsCompiler bucklescript = ServiceManager.getService(project, BsCompiler.class);

    // Read build.ninja
    m_ninja = bucklescript.readNinjaBuild(m_contentRoot);

    // Read bsConfig to get the jsx value and ppx
    VirtualFile configJson = m_contentRoot == null ? null : m_contentRoot.findFileByRelativePath("bsconfig.json");
    BsConfig config = configJson == null ? null : BsConfigReader.read(configJson);
    if (config == null) {
        LOG.debug("No bsconfig.json found for content root: " + m_contentRoot);
        m_jsxVersion = null;
        m_namespace = "";
    } else {
        m_jsxVersion = config.getJsxVersion();
        m_namespace = config.getNamespace();

        // If a directory is marked as dev-only, it won't be built and exposed to other "dev" directories in the same project
        // https://bucklescript.github.io/docs/en/build-configuration#sources
        for (String devSource : config.getDevSources()) {
            VirtualFile devFile = m_contentRoot.findFileByRelativePath(devSource);
            if (devFile != null && FileUtil.isAncestor(devFile.getPath(), m_sourceFile.getPath(), true)) {
                m_ninja.addInclude(devSource);
            }
        }
    }
}
 
Example 9
Source File: ContentEntryImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void assertFolderUnderMe(@Nonnull String url) {
  final String path = VfsUtilCore.urlToPath(url);
  final String rootPath = VfsUtilCore.urlToPath(getUrl());
  if (!FileUtil.isAncestor(rootPath, path, false)) {
    LOGGER.error("The file '" + path + "' is not under content entry root '" + rootPath + "'");
  }
}
 
Example 10
Source File: CreatePatchConfigurationPanel.java    From consulo with Apache License 2.0 5 votes vote down vote up
@javax.annotation.Nullable
private ValidationInfo verifyBaseDirPath() {
  String baseDirName = getBaseDirName();
  if (StringUtil.isEmptyOrSpaces(baseDirName)) return new ValidationInfo("Base path can't be empty!", myBasePathField);
  File baseFile = new File(baseDirName);
  if (!baseFile.exists()) return new ValidationInfo("Base dir doesn't exist", myBasePathField);
  if (myCommonParentDir != null && !FileUtil.isAncestor(baseFile, myCommonParentDir, false)) {
    return new ValidationInfo(String.format("Base path doesn't contain all selected changes (use %s)", myCommonParentDir.getPath()),
                              myBasePathField);
  }
  return null;
}
 
Example 11
Source File: PantsSourceRootsExtension.java    From intellij-pants-plugin with Apache License 2.0 5 votes vote down vote up
private static boolean hasAnAncestorRoot(@NotNull Collection<String> baseSourceRoots, @NotNull String root) {
  for (String sourceRoot : baseSourceRoots) {
    if (FileUtil.isAncestor(sourceRoot, root, false)) {
      return true;
    }
  }
  return false;
}
 
Example 12
Source File: BlazeTypeScriptConfigTest.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Override
public File getCanonicalFile(File file) throws IOException {
  file = file.getCanonicalFile();
  for (File link : symlinks.keySet()) {
    if (FileUtil.isAncestor(link, file, /* strict= */ false)) {
      return new File(symlinks.get(link), link.toPath().relativize(file.toPath()).toString());
    }
  }
  return file;
}
 
Example 13
Source File: WorkspaceHelper.java    From intellij with Apache License 2.0 5 votes vote down vote up
private static WorkspacePath getPackagePath(
    BuildSystemProvider provider, WorkspaceRoot root, WorkspacePath workspacePath) {
  File file = root.fileForPath(workspacePath).getParentFile();
  while (file != null && FileUtil.isAncestor(root.directory(), file, false)) {
    ProgressManager.checkCanceled();
    if (provider.findBuildFileInDirectory(file) != null) {
      return root.workspacePathFor(file);
    }
    file = file.getParentFile();
  }
  return null;
}
 
Example 14
Source File: FilePathImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isUnder(FilePath parent, boolean strict) {
  if (myVirtualFile != null) {
    final VirtualFile parentFile = parent.getVirtualFile();
    if (parentFile != null) {
      return VfsUtilCore.isAncestor(parentFile, myVirtualFile, strict);
    }
  }
  return FileUtil.isAncestor(parent.getIOFile(), getIOFile(), strict);
}
 
Example 15
Source File: NativeEditorNotificationProvider.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private boolean isValidForFile() {
  if (isVisible) {
    // The menu items are visible for certain elements outside the module directories.
    return FileUtil.isAncestor(myRoot.getPath(), myFile.getPath(), true);
  }
  return false;
}
 
Example 16
Source File: NativeEditorNotificationProvider.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private boolean isValidForFile() {
  if (isVisible) {
    // The menu items are visible for certain elements outside the module directories.
    return FileUtil.isAncestor(myRoot.getPath(), myFile.getPath(), true);
  }
  return false;
}
 
Example 17
Source File: DvcsUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static void addMappingIfSubRoot(@Nonnull Project project, @Nonnull String newRepositoryPath, @Nonnull String vcsName) {
  if (project.getBasePath() != null && FileUtil.isAncestor(project.getBasePath(), newRepositoryPath, true)) {
    ProjectLevelVcsManager manager = ProjectLevelVcsManager.getInstance(project);
    manager.setDirectoryMappings(VcsUtil.addMapping(manager.getDirectoryMappings(), newRepositoryPath, vcsName));
  }
}
 
Example 18
Source File: GitCompatUtil.java    From GitToolBox with Apache License 2.0 4 votes vote down vote up
boolean isFileInRepo(File file) {
  return FileUtil.isAncestor(rootFile, file, false);
}
 
Example 19
Source File: VfsUtilCore.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static boolean isAncestor(@Nonnull File ancestor, @Nonnull File file, boolean strict) {
  return FileUtil.isAncestor(ancestor, file, strict);
}
 
Example 20
Source File: VcsRootProblemNotifier.java    From consulo with Apache License 2.0 4 votes vote down vote up
private boolean isUnderOrAboveProjectDir(@Nonnull String mapping) {
  String projectDir = ObjectUtils.assertNotNull(myProject.getBasePath());
  return mapping.equals(VcsDirectoryMapping.PROJECT_CONSTANT) ||
         FileUtil.isAncestor(projectDir, mapping, false) ||
         FileUtil.isAncestor(mapping, projectDir, false);
}