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

The following examples show how to use com.intellij.openapi.vfs.VirtualFile#getPath() . These examples are extracted from open source projects. 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
@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 2
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 3
Source Project: Thinkphp5-Plugin   File: RouteUtil.java    License: 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 4
Source Project: buck   File: BuckDeps.java    License: 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 5
Source Project: consulo   File: PersistentFSTest.java    License: 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 6
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 7
@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 8
Source Project: arma-intellij-plugin   File: ArmaPlugin.java    License: 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 9
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 10
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 11
/**
 * "..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 12
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 13
Source Project: intellij   File: TestTargetHeuristic.java    License: 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 14
/**
 * 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 15
Source Project: consulo   File: ErrorViewStructure.java    License: 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 16
Source Project: consulo   File: SdkType.java    License: Apache License 2.0 4 votes vote down vote up
public String sdkPath(VirtualFile homePath) {
  return homePath.getPath();
}
 
Example 17
Source Project: consulo   File: ModuleImportProvider.java    License: 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 Project: intellij   File: PsiUtils.java    License: 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 19
Source Project: consulo   File: IdeDocumentHistoryImpl.java    License: 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 20
Source Project: consulo   File: AbstractVcsHelperImpl.java    License: 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";
}