Java Code Examples for com.intellij.openapi.vfs.VirtualFile#getPath()

The following examples show how to use com.intellij.openapi.vfs.VirtualFile#getPath() . 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: ArmaPlugin.java    From arma-intellij-plugin with MIT License 6 votes vote down vote up
/**
 * @return the path to Arma IntelliJ Plugin's temp directory for the given module,
 * or null if the .iml directory couldn't be located
 */
@Nullable
public static String getPathToTempDirectory(@NotNull Module module) {
	final String tempFolder = "/armaplugin-temp";

	//find a place to save parse data
	VirtualFile imlVirtFile = module.getModuleFile();
	if (imlVirtFile == null) {
		String projectBasePath = module.getProject().getBasePath();
		if (projectBasePath == null) {
			return null;
		}
		return projectBasePath + tempFolder;
	}
	VirtualFile imlDir = imlVirtFile.getParent();
	if (imlDir == null) {
		return null;
	}
	return imlDir.getPath() + tempFolder;
}
 
Example 2
Source File: BazelTestRunner.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@NotNull
public Collection<String> getBreakpointUris(@NotNull final VirtualFile file) {
  // Get the results from superclass
  final Collection<String> results = super.getBreakpointUris(file);

  // Get the workspace directory name provided by the test harness.
  final String workspaceDirName = connector.getWorkspaceDirName();

  // Verify the returned workspace directory name
  if (StringUtils.isEmpty(workspaceDirName)) return results;

  final String filePath = file.getPath();
  int workspaceEndOffset = filePath.lastIndexOf(workspaceDirName + "/");
  if (workspaceEndOffset != -1) {
    workspaceEndOffset += workspaceDirName.length();
    results.add(workspaceDirName + "://" + filePath.substring(workspaceEndOffset));
  }
  return results;
}
 
Example 3
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 4
Source File: DartTestEventsConverterZ.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void addLocationHint(ServiceMessageBuilder messageBuilder, Item item) {
  String location = "unknown";
  String loc;

  final VirtualFile file = item.getUrl() == null ? null : myUrlResolver.findFileByDartUrl(item.getUrl());
  if (file != null) {
    loc = FILE_URL_PREFIX + file.getPath();
  }
  else if (item.hasSuite()) {
    loc = FILE_URL_PREFIX + item.getSuite().getPath();
  }
  else {
    loc = myLocation;
  }

  if (loc != null) {
    String nameList = GSON.toJson(item.nameList(), DartTestLocationProvider.STRING_LIST_TYPE);
    location = loc + "," + item.getLine() + "," + item.getColumn() + "," + nameList;
  }

  messageBuilder.addAttribute("locationHint", location);
}
 
Example 5
Source File: RouteUtil.java    From Thinkphp5-Plugin with MIT License 6 votes vote down vote up
public static ControllerFileMatchResult matchControllerFile(Project project, VirtualFile virtualFile) {
    String path = virtualFile.getPath();
    String projectPath = project.getBasePath();
    if (projectPath != null) {
        path = path.substring(projectPath.length());
    }
    Matcher matcher = controllerFilePattern.matcher(path);
    if (matcher.matches()) {
        String prefix1 = matcher.group(1);
        String prefix2 = matcher.group(2);
        String prefix = prefix1 + "/" + prefix2;
        return new ControllerFileMatchResult(true, prefix);
    } else {
        return new ControllerFileMatchResult(false, "");
    }
}
 
Example 6
Source File: BuckDeps.java    From buck with Apache License 2.0 6 votes vote down vote up
/**
 * In the given {@code buckFile}, modify the given {@code target} to include {@code dependency} in
 * its deps.
 *
 * @param buckFile Home for the given {@code target}.
 * @param target The fully qualified target to be modified.
 * @param dependency The fully qualified dependency required by the target.
 */
static boolean modifyTargetToAddDependency(
    VirtualFile buckFile, String target, String dependency) {
  try {
    File file = new File(buckFile.getPath());
    String oldContents = FileUtil.loadFile(file);
    String newContents = tryToAddDepsToTarget(oldContents, dependency, target);
    if (oldContents.equals(newContents)) {
      return false;
    }
    LOG.info("Updating " + file.getPath());
    FileUtil.writeToFile(file, newContents);
    buckFile.refresh(false, false);
    return true;
  } catch (IOException e) {
    LOG.error(
        "Failed to update "
            + buckFile.getPath()
            + " target "
            + target
            + " to include "
            + dependency,
        e);
    return false;
  }
}
 
Example 7
Source File: JavaCodeFormatterFacade.java    From EclipseCodeFormatter with Apache License 2.0 6 votes vote down vote up
private Map<String, String> getEclipseProfileOptions(VirtualFile configFile, ClassLoader classLoader) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
	Class<?> aClass1 = Class.forName("org.eclipse.jdt.internal.formatter.DefaultCodeFormatterOptions", true, classLoader);
	Method getMap = aClass1.getMethod("getMap");
	Properties options;

	switch (settings.getProfileScheme()) {

		case PROJECT_SPECIFIC:
			javaPropertiesProvider = new JavaPropertiesProvider(configFile.getPath(), null);
			options = javaPropertiesProvider.get();
			return toMap(options);
		case ECLIPSE:
			return (Map<String, String>) getMap.invoke(aClass1.getDeclaredMethod("getEclipseDefaultSettings").invoke(null));
		case ECLIPSE_2_1:
			return (Map<String, String>) getMap.invoke(aClass1.getDeclaredMethod("getDefaultSettings").invoke(null));
		case JAVA_CONVENTIONS:
			return (Map<String, String>) getMap.invoke(aClass1.getDeclaredMethod("getJavaConventionsSettings").invoke(null));
		case FILE:
			javaPropertiesProvider = settings.getJavaProperties();
			options = javaPropertiesProvider.get();
			return toMap(options);
	}
	throw new IllegalStateException();
}
 
Example 8
Source File: PersistentFSTest.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void testDeleteSubstRoots() throws IOException, InterruptedException {
  if (!SystemInfo.isWindows) return;

  File tempDirectory = FileUtil.createTempDirectory(getTestName(false), null);
  File substRoot = IoTestUtil.createSubst(tempDirectory.getPath());
  VirtualFile subst = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(substRoot);
  assertNotNull(subst);
  try {
    final File[] children = substRoot.listFiles();
    assertNotNull(children);
  }
  finally {
    IoTestUtil.deleteSubst(substRoot.getPath());
  }
  subst.refresh(false, true);
  PersistentFS fs = PersistentFS.getInstance();

  VirtualFile[] roots = fs.getRoots(LocalFileSystem.getInstance());
  for (VirtualFile root : roots) {
    String rootPath = root.getPath();
    String prefix = StringUtil.commonPrefix(rootPath, substRoot.getPath());
    assertEmpty(prefix);
  }
}
 
Example 9
Source File: FlutterSdk.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public FlutterCommand flutterAttach(@NotNull PubRoot root, @NotNull VirtualFile main, @Nullable FlutterDevice device,
                                    @NotNull FlutterLaunchMode flutterLaunchMode, String... additionalArgs) {
  final List<String> args = new ArrayList<>();
  args.add("--machine");
  if (FlutterSettings.getInstance().isVerboseLogging()) {
    args.add("--verbose");
  }

  // TODO(messick): Check that 'flutter attach' supports these arguments.
  if (flutterLaunchMode == FlutterLaunchMode.PROFILE) {
    args.add("--profile");
  }
  else if (flutterLaunchMode == FlutterLaunchMode.RELEASE) {
    args.add("--release");
  }

  if (device != null) {
    args.add("--device-id=" + device.deviceId());
  }

  // TODO(messick): Add others (target, debug-port).
  args.addAll(asList(additionalArgs));

  // Make the path to main relative (to make the command line prettier).
  final String mainPath = root.getRelativePath(main);
  if (mainPath == null) {
    throw new IllegalArgumentException("main isn't within the pub root: " + main.getPath());
  }
  args.add(FileUtil.toSystemDependentName(mainPath));

  return new FlutterCommand(this, root.getRoot(), FlutterCommand.Type.ATTACH, args.toArray(new String[]{ }));
}
 
Example 10
Source File: ErrorViewStructure.java    From consulo with Apache License 2.0 5 votes vote down vote up
private MyNavigatableWithDataElement(final Project project,
                                     @Nonnull ErrorTreeElementKind kind,
                                     GroupingElement parent,
                                     String[] message,
                                     @Nonnull final VirtualFile vf,
                                     String exportText,
                                     String rendererTextPrefix) {
  super(kind, parent, message, new OpenFileDescriptor(project, vf, -1, -1), exportText, rendererTextPrefix);
  myVf = vf;
  myCustomizeColoredTreeCellRenderer = new CustomizeColoredTreeCellRenderer() {
    @Override
    public void customizeCellRenderer(SimpleColoredComponent renderer,
                                      JTree tree,
                                      Object value,
                                      boolean selected,
                                      boolean expanded,
                                      boolean leaf,
                                      int row,
                                      boolean hasFocus) {
      final Icon icon = TargetAWT.to(myVf.getFileType().getIcon());
      renderer.setIcon(icon);
      final String[] messages = getText();
      final String text = messages == null || messages.length == 0 ? vf.getPath() : messages[0];
      renderer.append(text);
    }
  };
}
 
Example 11
Source File: VFilePropertyChangeEvent.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Replaces file name in {@code myFile} path with {@code fileName}, if an event is a rename event; leaves path as is otherwise
 */
@Nonnull
private String getPathWithFileName(Object fileName) {
  if (VirtualFile.PROP_NAME.equals(myPropertyName)) {
    // fileName must be String, according to `checkPropertyValuesCorrect` implementation
    VirtualFile parent = myFile.getParent();
    if (parent == null) {
      return ((String)fileName);
    }
    return parent.getPath() + "/" + fileName;
  }
  return getPath();
}
 
Example 12
Source File: TestTargetHeuristic.java    From intellij with Apache License 2.0 5 votes vote down vote up
/**
 * Finds a test rule associated with a given {@link PsiElement}. Must be called from within a read
 * action.
 */
@Nullable
static ListenableFuture<TargetInfo> targetFutureForPsiElement(
    @Nullable PsiElement element, @Nullable TestSize testSize) {
  if (element == null) {
    return null;
  }
  PsiFile psiFile = element.getContainingFile();
  if (psiFile == null) {
    return null;
  }
  VirtualFile vf = psiFile.getVirtualFile();
  File file = vf != null ? new File(vf.getPath()) : null;
  if (file == null) {
    return null;
  }
  Project project = element.getProject();
  ListenableFuture<Collection<TargetInfo>> targets =
      SourceToTargetFinder.findTargetInfoFuture(project, file, Optional.of(RuleType.TEST));
  if (targets.isDone() && FuturesUtil.getIgnoringErrors(targets) == null) {
    return null;
  }
  Executor executor =
      ApplicationManager.getApplication().isUnitTestMode()
          ? MoreExecutors.directExecutor()
          : PooledThreadExecutor.INSTANCE;
  return Futures.transform(
      targets,
      list ->
          list == null
              ? null
              : TestTargetHeuristic.chooseTestTargetForSourceFile(
                  project, psiFile, file, list, testSize),
      executor);
}
 
Example 13
Source File: FlutterSdk.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public FlutterCommand flutterAttach(@NotNull PubRoot root, @NotNull VirtualFile main, @Nullable FlutterDevice device,
                                    @NotNull FlutterLaunchMode flutterLaunchMode, String... additionalArgs) {
  final List<String> args = new ArrayList<>();
  args.add("--machine");
  if (FlutterSettings.getInstance().isVerboseLogging()) {
    args.add("--verbose");
  }

  // TODO(messick): Check that 'flutter attach' supports these arguments.
  if (flutterLaunchMode == FlutterLaunchMode.PROFILE) {
    args.add("--profile");
  }
  else if (flutterLaunchMode == FlutterLaunchMode.RELEASE) {
    args.add("--release");
  }

  if (device != null) {
    args.add("--device-id=" + device.deviceId());
  }

  // TODO(messick): Add others (target, debug-port).
  args.addAll(asList(additionalArgs));

  // Make the path to main relative (to make the command line prettier).
  final String mainPath = root.getRelativePath(main);
  if (mainPath == null) {
    throw new IllegalArgumentException("main isn't within the pub root: " + main.getPath());
  }
  args.add(FileUtil.toSystemDependentName(mainPath));

  return new FlutterCommand(this, root.getRoot(), FlutterCommand.Type.ATTACH, args.toArray(new String[]{ }));
}
 
Example 14
Source File: ServiceIndexUtil.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
/**
 * "..src/Foo/{Foo,Foobar.php}"
 *
 */
public static boolean matchesResourcesGlob(@NotNull VirtualFile serviceFileAsBase, @NotNull VirtualFile phpClassFile, @NotNull String resource, @Nullable String exclude) {
    String replace = resource.replace("\\\\", "/");

    VirtualFile serviceFile = serviceFileAsBase.getParent();
    String[] split = replace.split("/");
    String[] replacePathParts = split;
    for (String s : split) {
        if (s.equals("..")) {
            replacePathParts = Arrays.copyOfRange(replacePathParts, 1, replacePathParts.length);
            serviceFile = serviceFile.getParent();
        } else {
            break;
        }
    }

    if (serviceFile == null) {
        return false;
    }

    // ending one wildcard must be *
    // "src/*" => "src/**"
    String path = (serviceFile.getPath() + "/" + StringUtils.join(replacePathParts, "/"))
        .replaceAll("[^*]([*])$", "**");

    // force "**" at the end
    if (!path.endsWith("*")) {
        path += "**";
    }

    String phpClassPath = phpClassFile.getPath();

    if (exclude == null) {
        return isMatchingGlobResource(path, phpClassPath);
    }

    return isMatchingGlobResource(path, phpClassPath)
        && !matchesResourcesGlob(serviceFileAsBase, phpClassFile, exclude, null);
}
 
Example 15
Source File: ChangelistConflictTracker.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void ignoreConflict(@Nonnull VirtualFile file, boolean ignore) {
  String path = file.getPath();
  Conflict conflict = myConflicts.get(path);
  if (conflict == null) {
    conflict = new Conflict();
    myConflicts.put(path, conflict);
  }
  conflict.ignored = ignore;
  myEditorNotifications.updateNotifications(file);
  myFileStatusManager.fileStatusChanged(file);
}
 
Example 16
Source File: PsiUtils.java    From intellij with Apache License 2.0 4 votes vote down vote up
@Nullable
public static String getFilePath(@Nullable PsiFile file) {
  VirtualFile virtualFile = file != null ? file.getVirtualFile() : null;
  return virtualFile != null ? virtualFile.getPath() : null;
}
 
Example 17
Source File: ModuleImportProvider.java    From consulo with Apache License 2.0 4 votes vote down vote up
static String getDefaultPath(@Nonnull VirtualFile file) {
  return file.isDirectory() ? file.getPath() : file.getParent().getPath();
}
 
Example 18
Source File: IdeDocumentHistoryImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
public void register(VirtualFile file) {
  final String path = file.getPath();
  CHANGED_PATHS.remove(path);
  CHANGED_PATHS.add(path);
  trimToSize();
}
 
Example 19
Source File: SdkType.java    From consulo with Apache License 2.0 4 votes vote down vote up
public String sdkPath(VirtualFile homePath) {
  return homePath.getPath();
}
 
Example 20
Source File: AbstractVcsHelperImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
private static String failedText(@Nonnull VirtualFile virtualFile, @Nonnull VcsRevisionNumber revision) {
  return "Show all affected files for " + virtualFile.getPath() + " at " + revision.asString() + " failed";
}