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

The following examples show how to use com.intellij.openapi.util.io.FileUtil#getRelativePath() . 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: FileDirRelativeToProjectRootMacro.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public String expand(final DataContext dataContext) {
  final Project project = dataContext.getData(CommonDataKeys.PROJECT);
  if (project == null) {
    return null;
  }
  VirtualFile file = dataContext.getData(PlatformDataKeys.VIRTUAL_FILE);
  if (file == null) {
    return null;
  }
  if (!file.isDirectory()) {
    file = file.getParent();
    if (file == null) {
      return null;
    }
  }

  final VirtualFile contentRoot = ProjectRootManager.getInstance(project).getFileIndex().getContentRootForFile(file);
  if (contentRoot == null) {
    return null;
  }
  return FileUtil.getRelativePath(getIOFile(contentRoot), getIOFile(file));
}
 
Example 2
Source File: BaseCoverageSuite.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void writeExternal(final Element element) throws WriteExternalException {
  final String fileName =
    FileUtil.getRelativePath(new File(ContainerPathManager.get().getSystemPath()), new File(myCoverageDataFileProvider.getCoverageDataFilePath()));
  element.setAttribute(FILE_PATH, fileName != null ? FileUtil.toSystemIndependentName(fileName) : myCoverageDataFileProvider.getCoverageDataFilePath());
  element.setAttribute(NAME_ATTRIBUTE, myName);
  element.setAttribute(MODIFIED_STAMP, String.valueOf(myLastCoverageTimeStamp));
  element.setAttribute(SOURCE_PROVIDER, myCoverageDataFileProvider instanceof DefaultCoverageFileProvider
                                        ? ((DefaultCoverageFileProvider)myCoverageDataFileProvider).getSourceProvider()
                                        : myCoverageDataFileProvider.getClass().getName());
  // runner
  if (getRunner() != null) {
    element.setAttribute(COVERAGE_RUNNER, myRunner.getId());
  }

  // cover by test
  element.setAttribute(COVERAGE_BY_TEST_ENABLED_ATTRIBUTE_NAME, String.valueOf(myCoverageByTestEnabled));

  // tracing
  element.setAttribute(TRACING_ENABLED_ATTRIBUTE_NAME, String.valueOf(myTracingEnabled));
}
 
Example 3
Source File: HaxeSourceRootDetectionTest.java    From intellij-haxe with Apache License 2.0 6 votes vote down vote up
private void doTest(String... expected) {
  final String dirPath = FileUtil.toSystemDependentName(HaxeTestUtils.BASE_TEST_DATA_PATH + "/rootDetection/") + getTestName(true);
  final File dir = new File(dirPath);
  assertTrue(dir.isDirectory());
  final HaxeProjectStructureDetector haxeProjectStructureDetector = new HaxeProjectStructureDetector();
  final ProjectStructureDetector[] detector = new ProjectStructureDetector[]{haxeProjectStructureDetector};
  final RootDetectionProcessor detectionProcessor = new RootDetectionProcessor(
    dir,detector
  );
  // TODO:
  final List<DetectedProjectRoot> detected;//= detectionProcessor.findRoots().get(haxeProjectStructureDetector);
  Map<ProjectStructureDetector, List<DetectedProjectRoot>> detectorListMap = detectionProcessor.runDetectors();
  detected = detectorListMap.get(haxeProjectStructureDetector);
  assertNotNull(detected);
  final Set<String> actual = new THashSet<String>();
  for (DetectedProjectRoot projectRoot : detected) {
    final String relativePath = FileUtil.getRelativePath(dir, projectRoot.getDirectory());
    assertNotNull(relativePath);
    actual.add(FileUtil.toSystemIndependentName(relativePath));
  }
  assertSameElements(actual, expected);
}
 
Example 4
Source File: FilePathRelativeToSourcepathMacro.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public String expand(final DataContext dataContext) {
  final Project project = dataContext.getData(CommonDataKeys.PROJECT);
  if (project == null) {
    return null;
  }
  VirtualFile file = dataContext.getData(PlatformDataKeys.VIRTUAL_FILE);
  if (file == null) {
    return null;
  }
  final VirtualFile sourceRoot = ProjectRootManager.getInstance(project).getFileIndex().getSourceRootForFile(file);
  if (sourceRoot == null) {
    return null;
  }
  return FileUtil.getRelativePath(getIOFile(sourceRoot), getIOFile(file));
}
 
Example 5
Source File: GaugeWebBrowserPreview.java    From Intellij-Plugin with Apache License 2.0 6 votes vote down vote up
@Nullable
private Url previewUrl(OpenInBrowserRequest request, VirtualFile virtualFile, GaugeSettingsModel settings) throws IOException, InterruptedException {
    ProcessBuilder builder = new ProcessBuilder(settings.getGaugePath(), Constants.DOCS, Spectacle.NAME, virtualFile.getPath());
    String projectName = request.getProject().getName();
    builder.environment().put("spectacle_out_dir", FileUtil.join(createOrGetTempDirectory(projectName).getPath(), "docs"));
    File gaugeModuleDir = GaugeUtil.moduleDir(GaugeUtil.moduleForPsiElement(request.getFile()));
    builder.directory(gaugeModuleDir);
    GaugeUtil.setGaugeEnvironmentsTo(builder, settings);
    Process docsProcess = builder.start();
    int exitCode = docsProcess.waitFor();
    if (exitCode != 0) {
        String docsOutput = String.format("<pre>%s</pre>", GaugeUtil.getOutput(docsProcess.getInputStream(), " ").replace("<", "&lt;").replace(">", "&gt;"));
        Notifications.Bus.notify(new Notification("Specification Preview", "Error: Specification Preview", docsOutput, NotificationType.ERROR));
        return null;
    }
    String relativePath = FileUtil.getRelativePath(gaugeModuleDir, new File(virtualFile.getParent().getPath()));
    return new UrlImpl(FileUtil.join(createOrGetTempDirectory(projectName).getPath(), "docs", "html", relativePath, virtualFile.getNameWithoutExtension() + ".html"));
}
 
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: ScratchFileActions.java    From consulo with Apache License 2.0 6 votes vote down vote up
static PsiFile doCreateNewScratch(@Nonnull Project project, @Nonnull ScratchFileCreationHelper.Context context) {
  FeatureUsageTracker.getInstance().triggerFeatureUsed("scratch");
  Language language = Objects.requireNonNull(context.language);
  if (context.fileExtension == null) {
    LanguageFileType fileType = language.getAssociatedFileType();
    context.fileExtension = fileType == null ? "" : fileType.getDefaultExtension();
  }
  ScratchFileCreationHelper.EXTENSION.forLanguage(language).beforeCreate(project, context);

  VirtualFile dir = context.ideView != null ? PsiUtilCore.getVirtualFile(ArrayUtil.getFirstElement(context.ideView.getDirectories())) : null;
  RootType rootType = dir == null ? null : ScratchFileService.findRootType(dir);
  String relativePath = rootType != ScratchRootType.getInstance() ? "" : FileUtil.getRelativePath(ScratchFileService.getInstance().getRootPath(rootType), dir.getPath(), '/');

  String fileName = (StringUtil.isEmpty(relativePath) ? "" : relativePath + "/") +
                    PathUtil.makeFileName(ObjectUtils.notNull(context.filePrefix, "scratch") + (context.fileCounter != null ? context.fileCounter.create() : ""), context.fileExtension);
  VirtualFile file = ScratchRootType.getInstance().createScratchFile(project, fileName, language, context.text, context.createOption);
  if (file == null) return null;

  PsiNavigationSupport.getInstance().createNavigatable(project, file, context.caretOffset).navigate(true);
  PsiFile psiFile = PsiManager.getInstance(project).findFile(file);
  if (context.ideView != null && psiFile != null) {
    context.ideView.selectElement(psiFile);
  }
  return psiFile;
}
 
Example 8
Source File: QualifiedNameProviders.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
public 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();
}
 
Example 9
Source File: FilePathRelativeToProjectRootMacro.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public String expand(final DataContext dataContext) {
  final Project project = dataContext.getData(CommonDataKeys.PROJECT);
  if (project == null) {
    return null;
  }
  VirtualFile file = dataContext.getData(PlatformDataKeys.VIRTUAL_FILE);
  if (file == null) {
    return null;
  }
  final VirtualFile contentRoot = ProjectRootManager.getInstance(project).getFileIndex().getContentRootForFile(file);
  if (contentRoot == null) {
    return null;
  }
  return FileUtil.getRelativePath(getIOFile(contentRoot), getIOFile(file));
}
 
Example 10
Source File: VcsDirectoryConfigurationPanel.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected void customizeCellRenderer(JTable table, Object value, boolean selected, boolean hasFocus, int row, int column) {
  if (value instanceof MapInfo) {
    MapInfo info = (MapInfo)value;

    if (!selected && (info == MapInfo.SEPARATOR || info.type == MapInfo.Type.UNREGISTERED)) {
      setBackground(getUnregisteredRootBackground());
    }

    if (info == MapInfo.SEPARATOR) {
      append("Unregistered roots:", getAttributes(info));
      return;
    }

    if (info.mapping.isDefaultMapping()) {
      append(VcsDirectoryMapping.PROJECT_CONSTANT, getAttributes(info));
      return;
    }

    String directory = info.mapping.getDirectory();
    VirtualFile baseDir = myProject.getBaseDir();
    if (baseDir != null) {
      final File directoryFile = new File(StringUtil.trimEnd(UriUtil.trimTrailingSlashes(directory), "\\") + "/");
      File ioBase = new File(baseDir.getPath());
      if (directoryFile.isAbsolute() && !FileUtil.isAncestor(ioBase, directoryFile, false)) {
        append(new File(directory).getPath(), getAttributes(info));
        return;
      }
      String relativePath = FileUtil.getRelativePath(ioBase, directoryFile);
      if (".".equals(relativePath) || relativePath == null) {
        append(ioBase.getPath(), getAttributes(info));
      }
      else {
        append(relativePath, getAttributes(info));
        append(" (" + ioBase + ")", SimpleTextAttributes.GRAYED_ATTRIBUTES);
      }
    }
  }
}
 
Example 11
Source File: FileRelativePathMacro.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public String expand(DataContext dataContext) {
  Project project = dataContext.getData(CommonDataKeys.PROJECT);
  final VirtualFile baseDir = project == null ? null : project.getBaseDir();
  if (baseDir == null) {
    return null;
  }

  VirtualFile file = dataContext.getData(PlatformDataKeys.VIRTUAL_FILE);
  if (file == null) return null;
  return FileUtil.getRelativePath(VfsUtil.virtualToIoFile(baseDir), VfsUtil.virtualToIoFile(file));
}
 
Example 12
Source File: TFVCUtil.java    From azure-devops-intellij with MIT License 5 votes vote down vote up
/**
 * Determines if the path has an illegal $ character in any component.
 *
 * @param mapping   root path mapping for the file.
 * @param localPath the file under VCS.
 */
private static boolean hasIllegalDollarInAnyComponent(FilePath mapping, FilePath localPath) {
    String relativePath = FileUtil.getRelativePath(mapping.getIOFile(), localPath.getIOFile());
    if (relativePath == null) {
        return localPath.getName().startsWith("$");
    }

    File file = new File(relativePath);
    while (file != null) {
        if (file.getName().startsWith("$")) return true;
        file = file.getParentFile();
    }

    return false;
}
 
Example 13
Source File: TestFileSystem.java    From intellij with Apache License 2.0 5 votes vote down vote up
/**
 * Absolute file paths are prohibited -- the TempDirTestFixture used in these tests will prepend
 * it's own root to the path.
 */
private String makePathRelativeToTestFixture(String filePath) {
  if (!FileUtil.isAbsolute(filePath)) {
    return filePath;
  }
  String tempDirPath = getRootDir();
  assertWithMessage(
          String.format(
              "Invalid absolute file path. '%s' is not underneath the test file system root '%s'",
              filePath, tempDirPath))
      .that(FileUtil.isAncestor(tempDirPath, filePath, true))
      .isTrue();
  return FileUtil.getRelativePath(tempDirPath, filePath, File.separatorChar);
}
 
Example 14
Source File: Review.java    From Crucible4IDEA with MIT License 5 votes vote down vote up
@Nullable
public String getIdByPath(@NotNull final String path, Project project) {
  final Map<String,VirtualFile> hash = CrucibleManager.getInstance(project).getRepoHash();

  for (ReviewItem item : myItems) {
    final String repo = item.getRepo();
    final String root = hash.containsKey(repo) ? hash.get(repo).getPath() : project.getBasePath();
    String relativePath = FileUtil.getRelativePath(new File(Objects.requireNonNull(root)), new File(path));
    if (FileUtil.pathsEqual(relativePath, item.getPath())) {
      return item.getId();
    }
  }
  return null;
}
 
Example 15
Source File: FileRelativeDirMacro.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public String expand(DataContext dataContext) {
  final VirtualFile baseDir = dataContext.getData(PlatformDataKeys.PROJECT_FILE_DIRECTORY);
  if (baseDir == null) {
    return null;
  }

  VirtualFile dir = getVirtualDirOrParent(dataContext);
  if (dir == null) return null;
  return FileUtil.getRelativePath(VfsUtil.virtualToIoFile(baseDir), VfsUtil.virtualToIoFile(dir));
}
 
Example 16
Source File: TextPatchBuilder.java    From consulo with Apache License 2.0 5 votes vote down vote up
private String getRelativePath(final String basePath, final String secondPath) {
  final String baseModified = FileUtil.toSystemIndependentName(basePath);
  final String secondModified = FileUtil.toSystemIndependentName(secondPath);

  final String relPath = FileUtil.getRelativePath(baseModified, secondModified, '/', myIsCaseSensitive);
  if (relPath == null) return secondModified;
  return relPath;
}
 
Example 17
Source File: ChangesBrowserFilePathNode.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static String getRelativePath(@javax.annotation.Nullable FilePath parent, @Nonnull FilePath child) {
  boolean isLocal = !child.isNonLocal();
  boolean caseSensitive = isLocal && SystemInfoRt.isFileSystemCaseSensitive;
  String result = parent != null ? FileUtil.getRelativePath(parent.getPath(), child.getPath(), '/', caseSensitive) : null;

  result = result == null ? child.getPath() : result;

  return isLocal ? FileUtil.toSystemDependentName(result) : result;
}
 
Example 18
Source File: FileUtils.java    From vue-for-idea with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static String relativePath(Project project, VirtualFile absolutePath) {
    return FileUtil.getRelativePath(new File(project.getBasePath()), new File(absolutePath.getPath()));
}
 
Example 19
Source File: FileUtils.java    From vue-for-idea with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static String makeRelative(File project, File absolutePath) {
    return FileUtil.getRelativePath(project, absolutePath);
}
 
Example 20
Source File: UnifiedDiffWriter.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
private static String getPathRelatedToDir(@Nonnull String newBaseDir, @Nullable String basePath, @Nonnull String path) {
  if (basePath == null) return path;
  String result = FileUtil.getRelativePath(new File(newBaseDir), new File(basePath, path));
  return result == null ? path : result;
}