com.intellij.util.PathUtil Java Examples

The following examples show how to use com.intellij.util.PathUtil. 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: DirectoryElementType.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public CompositePackagingElement<?> createComposite(CompositePackagingElement<?> parent,
                                                    String baseName,
                                                    @Nonnull ArtifactEditorContext context) {
  final String initialValue = PackagingElementFactoryImpl.suggestFileName(parent, baseName != null ? baseName : "folder", "");
  String path = Messages
    .showInputDialog(context.getProject(), "Enter directory name: ", "New Directory", null, initialValue, new FilePathValidator());
  if (path == null) {
    return null;
  }
  path = FileUtil.toSystemIndependentName(path);
  final String parentPath = PathUtil.getParentPath(path);
  final String fileName = PathUtil.getFileName(path);
  final PackagingElement<?> element = new DirectoryPackagingElement(fileName);
  return (CompositePackagingElement<?>)PackagingElementFactoryImpl.getInstance(context.getProject()).createParentDirectories(parentPath, element);

}
 
Example #2
Source File: PsiDirectoryNode.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public boolean contains(@Nonnull VirtualFile file) {
  final PsiDirectory value = getValue();
  if (value == null) {
    return false;
  }

  VirtualFile directory = value.getVirtualFile();
  if (directory.getFileSystem() instanceof LocalFileSystem) {
    file = PathUtil.getLocalFile(file);
  }

  if (!VfsUtilCore.isAncestor(directory, file, false)) {
    return false;
  }

  return !FileTypeRegistry.getInstance().isFileIgnored(file);
}
 
Example #3
Source File: RemoteOutputsCache.java    From intellij with Apache License 2.0 6 votes vote down vote up
/**
 * The cache key used to disambiguate output artifacts. This is also the file name in the local
 * cache.
 */
@VisibleForTesting
static String getCacheKey(RemoteOutputArtifact output) {
  String key = output.getKey();
  String fileName = PathUtil.getFileName(key);
  List<String> components = Splitter.on('.').limit(2).splitToList(fileName);
  StringBuilder builder =
      new StringBuilder(components.get(0))
          .append('_')
          .append(Integer.toHexString(key.hashCode()));
  if (components.size() > 1) {
    // file extension(s)
    builder.append('.').append(components.get(1));
  }
  return builder.toString();
}
 
Example #4
Source File: DirectorySection.java    From intellij with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
protected DirectoryEntry parseItem(ProjectViewParser parser, ParseContext parseContext) {
  String text = parseContext.current().text;
  boolean excluded = text.startsWith("-");
  text = excluded ? text.substring(1) : text;

  // removes '.' path sections, traverses ".." without handling symlinks
  text = PathUtil.getCanonicalPath(text);

  String error = WorkspacePath.validate(text);
  if (error != null) {
    parseContext.addError(error);
    return null;
  }
  WorkspacePath directory = new WorkspacePath(text);
  return excluded ? DirectoryEntry.exclude(directory) : DirectoryEntry.include(directory);
}
 
Example #5
Source File: HaxeCommonCompilerUtil.java    From intellij-haxe with Apache License 2.0 6 votes vote down vote up
@NotNull
private static String calculateWorkingPath(CompilationContext context) {
  HaxeModuleSettingsBase settings = context.getModuleSettings();

  // TODO: Add a setting for the working directory to the project/module settings dialog.  Then use that here.

  String workingPath = null;

  if (settings.isUseOpenFLToBuild()) {
    // Use the module directory...
    workingPath = context.getModuleDirPath();
  } else if (settings.isUseNmmlToBuild()) {
    String nmmlPath = settings.getNmmlPath();
    workingPath = PathUtil.getParentPath(nmmlPath);
  } else if (settings.isUseHxmlToBuild()) {
    String hxmlPath = settings.getHxmlPath();
    workingPath = PathUtil.getParentPath(hxmlPath);
  } else if (settings.isUseUserPropertiesToBuild()) {
    workingPath = findCwdInCommandLineArguments(settings);
  }

  if (null  == workingPath || workingPath.isEmpty()) {
     workingPath = context.getModuleDirPath();  // Last ditch effort. Location of the .iml
  }
  return null == workingPath ? "" : workingPath;
}
 
Example #6
Source File: OrderEntryAppearanceServiceImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public CellAppearanceEx forLibrary(Project project, @Nonnull final Library library, final boolean hasInvalidRoots) {
  final StructureConfigurableContext context = ProjectStructureConfigurable.getInstance(project).getContext();
  final Image icon = LibraryPresentationManager.getInstance().getCustomIcon(library, context);

  final String name = library.getName();
  if (name != null) {
    return normalOrRedWaved(name, (icon != null ? icon :  AllIcons.Nodes.PpLib), hasInvalidRoots);
  }

  final String[] files = library.getUrls(BinariesOrderRootType.getInstance());
  if (files.length == 0) {
    return SimpleTextCellAppearance.invalid(ProjectBundle.message("library.empty.library.item"),  AllIcons.Nodes.PpLib);
  }
  else if (files.length == 1) {
    return forVirtualFilePointer(new LightFilePointer(files[0]));
  }

  final String url = StringUtil.trimEnd(files[0], URLUtil.ARCHIVE_SEPARATOR);
  return SimpleTextCellAppearance.regular(PathUtil.getFileName(url),  AllIcons.Nodes.PpLib);
}
 
Example #7
Source File: PantsCompileOptionsExecutor.java    From intellij-pants-plugin with Apache License 2.0 6 votes vote down vote up
@NotNull
private static String loadProjectStructureFromScript(
  @NotNull String scriptPath,
  @NotNull Consumer<String> statusConsumer,
  @Nullable ProcessAdapter processAdapter
) throws IOException, ExecutionException {
  final GeneralCommandLine commandLine = PantsUtil.defaultCommandLine(scriptPath);
  commandLine.setExePath(scriptPath);
  statusConsumer.consume("Executing " + PathUtil.getFileName(scriptPath));
  final ProcessOutput processOutput = PantsUtil.getCmdOutput(commandLine, processAdapter);
  if (processOutput.checkSuccess(LOG)) {
    return processOutput.getStdout();
  }
  else {
    throw new PantsExecutionException("Failed to update the project!", scriptPath, processOutput);
  }
}
 
Example #8
Source File: FileCopyPresentation.java    From consulo with Apache License 2.0 6 votes vote down vote up
public FileCopyPresentation(String filePath, String outputFileName) {
  myOutputFileName = outputFileName;

  String parentPath;
  myFile = LocalFileSystem.getInstance().findFileByPath(filePath);
  if (myFile != null) {
    final VirtualFile parent = myFile.getParent();
    parentPath = parent != null ? FileUtil.toSystemDependentName(parent.getPath()) : "";
  }
  else {
    parentPath = FileUtil.toSystemDependentName(PathUtil.getParentPath(filePath));
  }

  String sourceFileName = PathUtil.getFileName(filePath);
  if (!sourceFileName.equals(myOutputFileName)) {
    mySourcePath = parentPath + "/" + sourceFileName;
  }
  else {
    mySourcePath = parentPath;
  }
}
 
Example #9
Source File: LabelUtils.java    From intellij with Apache License 2.0 6 votes vote down vote up
/**
 * Return a map from a base label string -> variants of the label string that share the common
 * base.
 */
public static Multimap<String, String> getAllValidLabelStringsPartitioned(
    Label label, boolean includePackageLocalLabels) {
  Multimap<String, String> stringToVariant = ArrayListMultimap.create();
  String fullLabelString = label.toString();
  List<String> fullVariants = new ArrayList<>();
  fullVariants.add(fullLabelString);
  String packagePath = label.blazePackage().relativePath();
  String ruleName = label.targetName().toString();
  if (!packagePath.isEmpty()) {
    if (PathUtil.getFileName(packagePath).equals(ruleName)) {
      String implicitRuleName = "//" + packagePath;
      fullVariants.add(implicitRuleName);
      fullLabelString = implicitRuleName;
    }
  }
  stringToVariant.putAll(fullLabelString, fullVariants);
  if (!includePackageLocalLabels) {
    return stringToVariant;
  }
  List<String> localVariants = new ArrayList<>();
  localVariants.add(":" + ruleName);
  localVariants.add(ruleName);
  stringToVariant.putAll(ruleName, localVariants);
  return stringToVariant;
}
 
Example #10
Source File: FlutterTestUtils.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static String findTestDataPath() {
  if (new File(PathManager.getHomePath() + "/contrib").isDirectory()) {
    // started from IntelliJ IDEA Ultimate project
    return FileUtil.toSystemIndependentName(PathManager.getHomePath() + "/contrib/flutter-intellij/testData");
  }

  final File f = new File("testData");
  if (f.isDirectory()) {
    // started from flutter plugin project
    return FileUtil.toSystemIndependentName(f.getAbsolutePath());
  }

  final String parentPath = PathUtil.getParentPath(PathManager.getHomePath());

  if (new File(parentPath + "/intellij-plugins").isDirectory()) {
    // started from IntelliJ IDEA Community Edition + flutter plugin project
    return FileUtil.toSystemIndependentName(parentPath + "/intellij-plugins/flutter-intellij/testData");
  }

  if (new File(parentPath + "/contrib").isDirectory()) {
    // started from IntelliJ IDEA Community + flutter plugin project
    return FileUtil.toSystemIndependentName(parentPath + "/contrib/flutter-intellij/testData");
  }

  return "";
}
 
Example #11
Source File: DiffContentFactoryImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private static VirtualFile createTemporalFile(@javax.annotation.Nullable Project project,
                                              @Nonnull String prefix,
                                              @Nonnull String suffix,
                                              @Nonnull byte[] content) throws IOException {
  File tempFile = FileUtil.createTempFile(PathUtil.suggestFileName(prefix + "_", true, false),
                                          PathUtil.suggestFileName("_" + suffix, true, false), true);
  if (content.length != 0) {
    FileUtil.writeToFile(tempFile, content);
  }
  if (!tempFile.setWritable(false, false)) LOG.warn("Can't set writable attribute of temporal file");

  VirtualFile file = VfsUtil.findFileByIoFile(tempFile, true);
  if (file == null) {
    throw new IOException("Can't create temp file for revision content");
  }
  VfsUtil.markDirtyAndRefresh(true, true, true, file);
  return file;
}
 
Example #12
Source File: ScratchUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void updateFileExtension(@Nonnull Project project, @Nullable VirtualFile file) throws IOException {
  ApplicationManager.getApplication().assertWriteAccessAllowed();
  if (CommandProcessor.getInstance().getCurrentCommand() == null) {
    throw new AssertionError("command required");
  }

  if (file == null) return;
  Language language = LanguageUtil.getLanguageForPsi(project, file);
  FileType expected = getFileTypeFromName(file);
  FileType actual = language == null ? null : language.getAssociatedFileType();
  if (expected == actual || actual == null) return;
  String ext = actual.getDefaultExtension();
  if (StringUtil.isEmpty(ext)) return;

  String newName = PathUtil.makeFileName(file.getNameWithoutExtension(), ext);
  VirtualFile parent = file.getParent();
  newName = parent != null && parent.findChild(newName) != null ? PathUtil.makeFileName(file.getName(), ext) : newName;
  file.rename(ScratchUtil.class, newName);
}
 
Example #13
Source File: LocalFileStorage.java    From consulo with Apache License 2.0 6 votes vote down vote up
public File createLocalFile(@Nonnull String url) throws IOException {
  int ast = url.indexOf('?');
  if (ast != -1) {
    url = url.substring(0, ast);
  }
  int last = url.lastIndexOf('/');
  String baseName;
  if (last == url.length() - 1) {
    baseName = url.substring(url.lastIndexOf('/', last-1) + 1, last);
  }
  else {
    baseName = url.substring(last + 1);
  }

  int index = baseName.lastIndexOf('.');
  String prefix = index == -1 ? baseName : baseName.substring(0, index);
  String suffix = index == -1 ? "" : baseName.substring(index+1);
  prefix = PathUtil.suggestFileName(prefix);
  suffix = PathUtil.suggestFileName(suffix);
  File file = FileUtil.findSequentNonexistentFile(myStorageIODirectory, prefix, suffix);
  FileUtil.createIfDoesntExist(file);
  return file;
}
 
Example #14
Source File: ZipArchiveElementType.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public CompositePackagingElement<?> createComposite(CompositePackagingElement<?> parent,
                                                    @Nullable String baseName,
                                                    @Nonnull ArtifactEditorContext context) {
  final String initialValue = PackagingElementFactoryImpl.suggestFileName(parent, baseName != null ? baseName : "archive", ".zip");
  String path =
    Messages.showInputDialog(context.getProject(), "Enter archive name: ", "New Archive", null, initialValue, new FilePathValidator());
  if (path == null) {
    return null;
  }
  path = FileUtil.toSystemIndependentName(path);
  final String parentPath = PathUtil.getParentPath(path);
  final String fileName = PathUtil.getFileName(path);
  final PackagingElement<?> element = new ZipArchivePackagingElement(fileName);
  return (CompositePackagingElement<?>)PackagingElementFactory.getInstance(context.getProject()).createParentDirectories(parentPath, element);
}
 
Example #15
Source File: BrowserLauncherAppless.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public boolean browseUsingPath(@Nullable final String url,
                               @Nullable String browserPath,
                               @Nullable final WebBrowser browser,
                               @Nullable final Project project,
                               @Nonnull final String[] additionalParameters) {
  Runnable launchTask = null;
  if (browserPath == null && browser != null) {
    browserPath = PathUtil.toSystemDependentName(browser.getPath());
    launchTask = new Runnable() {
      @Override
      public void run() {
        browseUsingPath(url, null, browser, project, additionalParameters);
      }
    };
  }
  return doLaunch(url, browserPath, browser, project, additionalParameters, launchTask);
}
 
Example #16
Source File: LibraryRootsComponent.java    From consulo with Apache License 2.0 6 votes vote down vote up
private Set<VirtualFile> getNotExcludedRoots() {
  Set<VirtualFile> roots = new LinkedHashSet<VirtualFile>();
  String[] excludedRootUrls = getLibraryEditor().getExcludedRootUrls();
  Set<VirtualFile> excludedRoots = new HashSet<VirtualFile>();
  for (String url : excludedRootUrls) {
    ContainerUtil.addIfNotNull(excludedRoots, VirtualFileManager.getInstance().findFileByUrl(url));
  }
  for (OrderRootType type : OrderRootType.getAllTypes()) {
    VirtualFile[] files = getLibraryEditor().getFiles(type);
    for (VirtualFile file : files) {
      if (!VfsUtilCore.isUnder(file, excludedRoots)) {
        roots.add(PathUtil.getLocalFile(file));
      }
    }
  }
  return roots;
}
 
Example #17
Source File: ArtifactVirtualFileListener.java    From consulo with Apache License 2.0 6 votes vote down vote up
private MultiValuesMap<String, Artifact> computeParentPathToArtifactMap() {
  final MultiValuesMap<String, Artifact> result = new MultiValuesMap<String, Artifact>();
  for (final Artifact artifact : myArtifactManager.getArtifacts()) {
    ArtifactUtil.processFileOrDirectoryCopyElements(artifact, new PackagingElementProcessor<FileOrDirectoryCopyPackagingElement<?>>() {
      @Override
      public boolean process(@Nonnull FileOrDirectoryCopyPackagingElement<?> element, @Nonnull PackagingElementPath pathToElement) {
        String path = element.getFilePath();
        while (path.length() > 0) {
          result.put(path, artifact);
          path = PathUtil.getParentPath(path);
        }
        return true;
      }
    }, myArtifactManager.getResolvingContext(), false);
  }
  return result;
}
 
Example #18
Source File: HeavyIdeaTestFixtureImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public PsiFile addFileToProject(@NonNls String rootPath, @NonNls final String relativePath, @NonNls final String fileText) throws IOException {
  final VirtualFile dir = VfsUtil.createDirectories(rootPath + "/" + PathUtil.getParentPath(relativePath));

  final VirtualFile[] virtualFile = new VirtualFile[1];
  new WriteCommandAction.Simple(getProject()) {
    @Override
    protected void run() throws Throwable {
      virtualFile[0] = dir.createChildData(this, StringUtil.getShortName(relativePath, '/'));
      VfsUtil.saveText(virtualFile[0], fileText);
    }
  }.execute();
  return ApplicationManager.getApplication().runReadAction(new Computable<PsiFile>() {
          public PsiFile compute() {
            return PsiManager.getInstance(getProject()).findFile(virtualFile[0]);
          }
        });
}
 
Example #19
Source File: LightTempDirTestFixtureImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
@Nonnull
public VirtualFile createFile(String targetPath) {
  final String path = PathUtil.getParentPath(targetPath);
  final String name = PathUtil.getFileName(targetPath);
  return ApplicationManager.getApplication().runWriteAction(new Computable<VirtualFile>() {
    @Override
    public VirtualFile compute() {
      try {
        VirtualFile targetDir = findOrCreateDir(path);
        return targetDir.createChildData(this, name);
      }
      catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
  });
}
 
Example #20
Source File: FlutterTestUtils.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static String findTestDataPath() {
  if (new File(PathManager.getHomePath() + "/contrib").isDirectory()) {
    // started from IntelliJ IDEA Ultimate project
    return FileUtil.toSystemIndependentName(PathManager.getHomePath() + "/contrib/flutter-intellij/testData");
  }

  final File f = new File("testData");
  if (f.isDirectory()) {
    // started from flutter plugin project
    return FileUtil.toSystemIndependentName(f.getAbsolutePath());
  }

  final String parentPath = PathUtil.getParentPath(PathManager.getHomePath());

  if (new File(parentPath + "/intellij-plugins").isDirectory()) {
    // started from IntelliJ IDEA Community Edition + flutter plugin project
    return FileUtil.toSystemIndependentName(parentPath + "/intellij-plugins/flutter-intellij/testData");
  }

  if (new File(parentPath + "/contrib").isDirectory()) {
    // started from IntelliJ IDEA Community + flutter plugin project
    return FileUtil.toSystemIndependentName(parentPath + "/contrib/flutter-intellij/testData");
  }

  return "";
}
 
Example #21
Source File: SmartBashFileReference.java    From BashSupport with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public PsiElement resolveInner() {
    final String referencedName = cmd.getReferencedCommandName();
    if (referencedName == null) {
        return null;
    }

    String fileName = PathUtil.getFileName(referencedName);
    GlobalSearchScope scope = BashSearchScopes.moduleScope(cmd.getContainingFile());

    PsiFileSystemItem[] files = FilenameIndex.getFilesByName(cmd.getProject(), fileName, scope, false);
    if (files.length == 0) {
        return null;
    }

    PsiFile currentFile = cmd.getContainingFile();
    return BashPsiFileUtils.findRelativeFile(currentFile, referencedName);
}
 
Example #22
Source File: ScratchFileServiceImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public VirtualFile findFile(@Nonnull RootType rootType, @Nonnull String pathName, @Nonnull Option option) throws IOException {
  ApplicationManager.getApplication().assertReadAccessAllowed();

  String fullPath = getRootPath(rootType) + "/" + pathName;
  if (option != Option.create_new_always) {
    VirtualFile file = LocalFileSystem.getInstance().findFileByPath(fullPath);
    if (file != null && !file.isDirectory()) return file;
    if (option == Option.existing_only) return null;
  }
  String ext = PathUtil.getFileExtension(pathName);
  String fileNameExt = PathUtil.getFileName(pathName);
  String fileName = StringUtil.trimEnd(fileNameExt, ext == null ? "" : "." + ext);
  AccessToken token = ApplicationManager.getApplication().acquireWriteActionLock(getClass());
  try {
    VirtualFile dir = VfsUtil.createDirectories(PathUtil.getParentPath(fullPath));
    if (option == Option.create_new_always) {
      return VfsUtil.createChildSequent(LocalFileSystem.getInstance(), dir, fileName, StringUtil.notNullize(ext));
    }
    else {
      return dir.createChildData(LocalFileSystem.getInstance(), fileNameExt);
    }
  }
  finally {
    token.finish();
  }
}
 
Example #23
Source File: LibraryUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static String getPresentableName(@Nonnull Library library) {
  final String name = library.getName();
  if (name != null) {
    return name;
  }
  if (library instanceof LibraryEx && ((LibraryEx)library).isDisposed()) {
    return "Disposed Library";
  }
  String[] urls = library.getUrls(BinariesOrderRootType.getInstance());
  if (urls.length > 0) {
    return PathUtil.getFileName(VfsUtilCore.urlToPath(urls[0]));
  }
  return "Empty Library";
}
 
Example #24
Source File: RoboVmBuildProcessParametersProvider.java    From robovm-idea with GNU General Public License v2.0 5 votes vote down vote up
@Override
@NotNull
public List<String> getClassPath() {
    List<String> classpath = new ArrayList<>();
    classpath.add(PathUtil.getJarPathForClass(Ant.class));
    classpath.add(PathUtil.getJarPathForClass(GroovyObject.class));
    classpath.add(PathUtil.getJarPathForClass(Gson.class));
    classpath.add(PathUtil.getJarPathForClass(Logger.class));
    classpath.add(PathUtil.getJarPathForClass(Log4jLoggerFactory.class));
    return classpath;
}
 
Example #25
Source File: AnalyzeDependenciesComponent.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public CellAppearanceEx getAppearance(boolean selected, final boolean isBold) {
  return new CellAppearanceEx() {
    @Override
    public void customize(@Nonnull SimpleColoredComponent component) {
      component.setIcon(getIcon());
      final Font font = UIUtil.getTreeFont();
      if (isBold) {
        component.setFont(font.deriveFont(Font.BOLD));
      }
      else {
        component.setFont(font.deriveFont(Font.PLAIN));
      }
      final String p = PathUtil.toPresentableUrl(getEditableObject().url());
      component.append(PathUtil.getFileName(p),
                       isBold ? SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES : SimpleTextAttributes.REGULAR_ATTRIBUTES);
      component.append(" (" + PathUtil.getParentPath(p) + ")", SimpleTextAttributes.GRAYED_ATTRIBUTES);
    }

    @Nonnull
    @Override
    public String getText() {
      return getDisplayName();
    }
  };
}
 
Example #26
Source File: ProgramParametersConfigurator.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
protected String getDefaultWorkingDir(@Nonnull Module module) {
  for (WorkingDirectoryProvider provider : WORKING_DIRECTORY_PROVIDER_EP_NAME.getExtensions()) {
    @SystemIndependent String path = provider.getWorkingDirectoryPath(module);
    if (path != null) return path;
  }
  VirtualFile[] roots = ModuleRootManager.getInstance(module).getContentRoots();
  if (roots.length > 0) {
    return PathUtil.getLocalPath(roots[0]);
  }
  return null;
}
 
Example #27
Source File: VcsLogPathsIndex.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private Collection<String> getParentPaths(@Nonnull Collection<String> paths) {
  Set<String> result = ContainerUtil.newHashSet();
  for (String path : paths) {
    while (!path.isEmpty() && !result.contains(path)) {
      result.add(path);
      if (myRoots.contains(path)) break;

      path = PathUtil.getParentPath(path);
    }
  }
  return result;
}
 
Example #28
Source File: DirectoryCopyPresentation.java    From consulo with Apache License 2.0 5 votes vote down vote up
public DirectoryCopyPresentation(String filePath) {
  mySourceFileName = PathUtil.getFileName(filePath);

  String parentPath;
  myFile = LocalFileSystem.getInstance().findFileByPath(filePath);
  if (myFile != null) {
    final VirtualFile parent = myFile.getParent();
    parentPath = parent != null ? FileUtil.toSystemDependentName(parent.getPath()) : "";
  }
  else {
    parentPath = FileUtil.toSystemDependentName(PathUtil.getParentPath(filePath));
  }

  mySourcePath = parentPath;
}
 
Example #29
Source File: LibraryPackagingElement.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public List<? extends PackagingElement<?>> getSubstitution(@Nonnull PackagingElementResolvingContext context, @Nonnull ArtifactType artifactType) {
  final Library library = findLibrary(context);
  if (library != null) {
    final VirtualFile[] files = library.getFiles(BinariesOrderRootType.getInstance());
    final List<PackagingElement<?>> elements = new ArrayList<PackagingElement<?>>();
    for (VirtualFile file : files) {
      final String path = FileUtil.toSystemIndependentName(PathUtil.getLocalPath(file));
      elements.add(file.isDirectory() && file.isInLocalFileSystem() ? new DirectoryCopyPackagingElement(path) : new FileCopyPackagingElement(path));
    }
    return elements;
  }
  return null;
}
 
Example #30
Source File: VfsTestUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static VirtualFile createFileOrDir(final VirtualFile root, final String relativePath, final String text, final boolean dir) {
  try {
    return Application.get().runWriteAction((ThrowableComputable<VirtualFile, IOException>)() -> {
      VirtualFile parent = root;
      Assert.assertNotNull(parent);
      StringTokenizer parents = new StringTokenizer(PathUtil.getParentPath(relativePath), "/");
      while (parents.hasMoreTokens()) {
        final String name = parents.nextToken();
        VirtualFile child = parent.findChild(name);
        if (child == null || !child.isValid()) {
          child = parent.createChildDirectory(VfsTestUtil.class, name);
        }
        parent = child;
      }
      final VirtualFile file;
      parent.getChildren();//need this to ensure that fileCreated event is fired
      if (dir) {
        file = parent.createChildDirectory(VfsTestUtil.class, PathUtil.getFileName(relativePath));
      }
      else {
        file = parent.createChildData(VfsTestUtil.class, PathUtil.getFileName(relativePath));
        if (!text.isEmpty()) {
          VfsUtil.saveText(file, text);
        }
      }
      return file;
    });
  }
  catch (IOException e) {
    throw new RuntimeException(e);
  }
}