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

The following examples show how to use com.intellij.openapi.vfs.VirtualFile#findFileByRelativePath() . 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
@Nullable
public static List<String> getHttpRoots(final String[] roots, String relPath) {
  final ArrayList<String> result = new ArrayList<String>();
  for (String root : roots) {
    final VirtualFile virtualFile = VirtualFileManager.getInstance().findFileByUrl(root);
    if (virtualFile != null) {
      if (virtualFile.getFileSystem() instanceof HttpFileSystem) {
        String url = virtualFile.getUrl();
        if (!url.endsWith("/")) url += "/";
        result.add(url + relPath);
      }
      else {
        VirtualFile file = virtualFile.findFileByRelativePath(relPath);
        if (file != null) result.add(file.getUrl());
      }
    }
  }

  return result.isEmpty() ? null : result;
}
 
Example 2
Source Project: reasonml-idea-plugin   File: BsPlatform.java    License: MIT License 6 votes vote down vote up
private static Optional<VirtualFile> findBsPlatformPathForConfigFile(@NotNull VirtualFile bsConfigFile) {
    VirtualFile parentDir = bsConfigFile.getParent();
    VirtualFile bsPlatform = parentDir.findFileByRelativePath("node_modules/" + BS_PLATFORM_DIRECTORY_NAME);
    if (bsPlatform == null) {
        VirtualFile bsbBinary = parentDir.findFileByRelativePath("node_modules/.bin/bsb"); // In case of mono-repo, only the .bin with symlinks is found
        if (bsbBinary != null && bsbBinary.is(VFileProperty.SYMLINK)) {
            VirtualFile canonicalFile = bsbBinary.getCanonicalFile();
            if (canonicalFile != null) {
                VirtualFile canonicalBsPlatformDirectory = canonicalFile.getParent();
                while (canonicalBsPlatformDirectory != null && !canonicalBsPlatformDirectory.getName().equals(BS_PLATFORM_DIRECTORY_NAME)) {
                    canonicalBsPlatformDirectory = canonicalBsPlatformDirectory.getParent();
                }
                return Optional.ofNullable(canonicalBsPlatformDirectory);
            }
        }
    }

    return Optional.ofNullable(bsPlatform).filter(VirtualFile::isDirectory);
}
 
Example 3
Source Project: reasonml-idea-plugin   File: BsPlatform.java    License: MIT License 6 votes vote down vote up
private static Optional<VirtualFile> findBinaryInBsPlatform(@NotNull String executableName, @NotNull VirtualFile bsPlatformDirectory) {
    Optional<String> platform = getOsBsPrefix();
    if (!platform.isPresent()) {
        LOG.warn("Unable to determine OS prefix.");
        return Optional.empty();
    }
    VirtualFile executable;
    // first, try to find platform-specific binary
    executable = bsPlatformDirectory.findFileByRelativePath(platform.get() + "/" + executableName + WINDOWS_EXECUTABLE_SUFFIX);
    if (executable != null) {
        return Optional.of(executable);
    }
    // next, try to find platform-agnostic wrappers
    executable = bsPlatformDirectory.findFileByRelativePath(executableName + getOsBinaryWrapperExtension());
    if (executable != null) {
        return Optional.of(executable);
    }
    // last, try old locations of binary
    executable = bsPlatformDirectory.findFileByRelativePath("bin/" + executableName + WINDOWS_EXECUTABLE_SUFFIX);
    if (executable != null) {
        return Optional.of(executable);
    }
    executable = bsPlatformDirectory.findFileByRelativePath("lib/" + executableName + WINDOWS_EXECUTABLE_SUFFIX);
    return Optional.ofNullable(executable);
}
 
Example 4
/**
 * Autocomplete when inside the target part of a relative-qualified extension file, e.g. {@code
 * ":ex" => ":ext.bzl"}.
 */
private void doTargetsForRelativeExtensionFile(
    VirtualFile virtualFile, String prefixToAutocomplete, CompletionResultSet result) {
  if (!prefixToAutocomplete.startsWith(":")) {
    return;
  }
  Matcher matcher = RELATIVE_TARGET_TO_EXTENSION_FILE_PATTERN.matcher(prefixToAutocomplete);
  if (!matcher.matches()) {
    return;
  }
  String path = matcher.group("path");
  VirtualFile dir = virtualFile.findFileByRelativePath("../" + path);
  if (dir == null || !dir.isDirectory()) {
    return;
  }
  String partial = matcher.group("partial");
  for (VirtualFile child : dir.getChildren()) {
    String name = child.getName();
    if (!name.startsWith(partial)) {
      continue;
    }
    if (child.isDirectory() || name.endsWith(".bzl")) {
      addResultForFile(result, child, path + name);
    }
  }
}
 
Example 5
@Nullable
public static VirtualFile findResource(PsiFile file, String resourcePath) {
    Matcher m = RESOURCE_PATTERN.matcher(resourcePath);
    if (m.matches()) {
        resourcePath = "Resources/" + m.group(2);
        VirtualFile packagesDir = findPackagesDirectory(file);
        if (packagesDir == null) {
            VirtualFile projectDir = guessProjectDir(file.getProject());
            if (projectDir == null) {
                return null;
            }

            return projectDir.findFileByRelativePath(resourcePath);
        } else {
            VirtualFile packageDir = findPackageDirectory(packagesDir, m.group(1));
            if (packageDir != null) {
                return packageDir.findFileByRelativePath(resourcePath);
            }
        }
    }

    return null;
}
 
Example 6
protected VirtualFile findPathInContentRoot(String path) {
    VirtualFile[] contentRoots = ProjectRootManager.getInstance(project).getContentRoots();
    if (contentRoots.length > 0) {
        for(VirtualFile contentRoot : contentRoots) {
            VirtualFile vfPath = contentRoot.findFileByRelativePath(path);
            if (null != vfPath) {
                return vfPath;
            }
        }

        return null;
    } else {
        return project.getBaseDir().findFileByRelativePath(path);
    }
}
 
Example 7
Source Project: reasonml-idea-plugin   File: BsCompilerImpl.java    License: MIT License 5 votes vote down vote up
@Override
@NotNull
public Ninja readNinjaBuild(@Nullable VirtualFile contentRoot) {
    String content = null;

    if (contentRoot != null) {
        VirtualFile ninja = contentRoot.findFileByRelativePath("lib/bs/build.ninja");
        if (ninja != null) {
            content = FileUtil.readFileContent(ninja);
        }
    }

    return new Ninja(content);
}
 
Example 8
Source Project: buck   File: BuckGotoProviderTest.java    License: Apache License 2.0 5 votes vote down vote up
private VirtualFile makeFile(VirtualFile root, String relativePath, String... lines)
    throws IOException {
  File targetFile = Paths.get(root.getPath()).resolve(relativePath).toFile();
  targetFile.getParentFile().mkdirs();
  try (BufferedWriter writer = new BufferedWriter(new FileWriter(targetFile))) {
    for (String line : lines) {
      writer.write(line);
      writer.newLine();
    }
  }
  root.refresh(false, true);
  return root.findFileByRelativePath(relativePath);
}
 
Example 9
Source Project: yiistorm   File: ARRelationReferenceProvider.java    License: MIT License 5 votes vote down vote up
public static PsiReference[] getReference(String path, @NotNull PsiElement element) {
    try {

        String viewPath = path.replace(YiiPsiReferenceProvider.projectPath, "");
        String protectedPath = YiiRefsHelper.getCurrentProtected(path);
        protectedPath = protectedPath.replace(YiiPsiReferenceProvider.projectPath, "");
        if (ARRelationReferenceProvider.isARRelationClassName(element)) {

            String str = element.getText();
            TextRange textRange = CommonHelper.getTextRange(element, str);
            if (textRange != null) {
                VirtualFile baseDir = YiiPsiReferenceProvider.project.getBaseDir();
                if (baseDir != null) {
                    String className = element.getText();
                    VirtualFile v = ARRelationReferenceProvider.getClassFile(className);
                    VirtualFile appDir = baseDir.findFileByRelativePath(viewPath);
                    VirtualFile protectedPathDir = (!protectedPath.equals("")) ? baseDir.findFileByRelativePath(protectedPath) : null;
                    if (appDir != null) {
                        PsiReference ref = new FileReference(v, str.substring(textRange.getStartOffset(), textRange.getEndOffset())
                                , element,
                                textRange, YiiPsiReferenceProvider.project, protectedPathDir, appDir);
                        return new PsiReference[]{ref};
                    }
                }
            }
        }
        return PsiReference.EMPTY_ARRAY;
    } catch (Exception e) {
        //System.err.println("error" + e.getMessage());
    }
    return PsiReference.EMPTY_ARRAY;
}
 
Example 10
@NotNull
@Override
public VirtualFile getFile() {
    VirtualFile baseDir = project.getBaseDir();
    String baseDirUrl = unifyNameFormatAndRemoveProtocol(baseDir.getUrl());
    String fileNameInBaseDir = unifyNameFormatAndRemoveProtocol(fileName).replaceFirst(baseDirUrl, "");
    VirtualFile relativePath = baseDir.findFileByRelativePath(fileNameInBaseDir);
    return relativePath;
}
 
Example 11
Source Project: idea-gitignore   File: GitExcludeLanguage.java    License: MIT License 5 votes vote down vote up
/**
 * Returns fixed directory for the given {@link IgnoreLanguage}.
 *
 * @param project current project
 * @return fixed directory
 */
@Nullable
@Override
public VirtualFile getFixedDirectory(@NotNull Project project) {
    final VirtualFile projectDir = Utils.guessProjectDir(project);
    if (projectDir == null) {
        return null;
    }
    return projectDir.findFileByRelativePath(getVcsDirectory() + "/info");
}
 
Example 12
/**
 * Workhorse for findFileOnClasspath.
 * @param cp
 * @param filePath
 * @return
 */
@Nullable
private static VirtualFile findFileOnOneClasspath(@NotNull HaxeClasspath cp, @NotNull final String filePath) {
  final VirtualFileManager vfmInstance = VirtualFileManager.getInstance();

  class MyLambda implements HaxeClasspath.Lambda {
    public VirtualFile found = null;
    public boolean processEntry(HaxeClasspathEntry entry) {
      String dirUrl = entry.getUrl();
      if (!URLUtil.containsScheme(dirUrl)) {
        dirUrl = vfmInstance.constructUrl(URLUtil.FILE_PROTOCOL, dirUrl);
      }
      VirtualFile dirName = vfmInstance.findFileByUrl(dirUrl);
      if (null != dirName && dirName.isDirectory()) {
        // XXX: This is wrong if filePath is already an absolute file name.
        found = dirName.findFileByRelativePath(filePath);
        if (null != found) {
          return false;  // Stop the search.
        }
      }
      return true;
    }
  }

  MyLambda lambda = new MyLambda();
  cp.iterate(lambda);
  return lambda.found;
}
 
Example 13
Source Project: consulo   File: DvcsUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static void visitVcsDirVfs(@Nonnull VirtualFile vcsDir, @Nonnull Collection<String> subDirs) {
  vcsDir.getChildren();
  for (String subdir : subDirs) {
    VirtualFile dir = vcsDir.findFileByRelativePath(subdir);
    // process recursively, because we need to visit all branches under refs/heads and refs/remotes
    ensureAllChildrenInVfs(dir);
  }
}
 
Example 14
protected VirtualFile findPathInWebDir(String path) {
    if (settings.publicPath.isEmpty()) {
        return findPathInContentRoot(path);
    }
    VirtualFile vfWebDir = getWebDir();
    if (null != vfWebDir) {
        return vfWebDir.findFileByRelativePath(path);
    } else {
        return null;
    }
}
 
Example 15
@Nullable
private Result<PsiFile> getSourceFileResult(ClsFileImpl clsFile, VirtualFile root) {
  // This code is adapted from JavaPsiImplementationHelperImpl#getClsFileNavigationElement
  PsiClass[] classes = clsFile.getClasses();
  if (classes.length == 0) {
    return null;
  }

  String sourceFileName = ((ClsClassImpl) classes[0]).getSourceFileName();
  String packageName = clsFile.getPackageName();
  String relativePath =
      packageName.isEmpty()
          ? sourceFileName
          : packageName.replace('.', '/') + '/' + sourceFileName;

  VirtualFile source = root.findFileByRelativePath(relativePath);
  if (source != null && source.isValid()) {
    // Since we have an actual source jar tracked down, use that source jar as the modification
    // tracker. This means the result will continue to be cached unless that source jar changes.
    // If we didn't find a source jar, we use a modification tracker that invalidates on every
    // Blaze sync, which is less efficient.
    PsiFile psiSource = clsFile.getManager().findFile(source);
    if (psiSource instanceof PsiClassOwner) {
      return Result.create(psiSource, source);
    }
    return Result.create(null, source);
  }

  return null;
}
 
Example 16
@Nonnull
@Override
@RequiredReadAction
public VirtualFile[] getFiles(@Nonnull OrderRootType rootType)
{
	List<VirtualFile> files = new ArrayList<>();

	if(rootType == BinariesOrderRootType.getInstance() || rootType == SourcesOrderRootType.getInstance())
	{
		LocalFileSystem localFileSystem = LocalFileSystem.getInstance();

		// moved to project files
		String projectPackageCache = getProjectPackageCache();
		VirtualFile localFile = localFileSystem.findFileByIoFile(new File(projectPackageCache, myNameWithVersion));
		addDotNetModulesInsideLibrary(files, localFile);

		if(files.isEmpty())
		{
			Unity3dPackageWatcher watcher = Unity3dPackageWatcher.getInstance();
			for(String path : watcher.getPackageDirPaths())
			{
				VirtualFile file = localFileSystem.findFileByIoFile(new File(path, myNameWithVersion));
				addDotNetModulesInsideLibrary(files, file);
			}
		}
	}

	if(files.isEmpty())
	{
		Sdk sdk = getSdk();
		if(sdk != null)
		{
			VirtualFile homeDirectory = sdk.getHomeDirectory();
			if(homeDirectory != null)
			{
				VirtualFile builtInDirectory = homeDirectory.findFileByRelativePath(getBuiltInPackagesRelativePath());
				if(builtInDirectory != null)
				{
					VirtualFile packageDirectory = builtInDirectory.findChild(getPackageName());
					ContainerUtil.addIfNotNull(files, packageDirectory);
				}
			}
		}
	}
	return VfsUtilCore.toVirtualFileArray(files);
}
 
Example 17
private static Module createAssemblyCSharpModuleEditor(final Project project,
													   ModifiableModuleModel newModel,
													   final Sdk unityBundle,
													   MultiMap<Module, VirtualFile> virtualFilesByModule,
													   ProgressIndicator progressIndicator,
													   UnityProjectImportContext context)
{
	final List<String> paths = new ArrayList<>();
	paths.add("Assets/Standard Assets/Editor");
	paths.add("Assets/Pro Standard Assets/Editor");
	paths.add("Assets/Plugins/Editor");

	final VirtualFile baseDir = project.getBaseDir();

	final VirtualFile assetsDir = baseDir.findFileByRelativePath(ASSETS_DIRECTORY);
	if(assetsDir != null)
	{
		VfsUtil.visitChildrenRecursively(assetsDir, new VirtualFileVisitor()
		{
			@Override
			public boolean visitFile(@Nonnull VirtualFile file)
			{
				if(file.isDirectory() && "Editor".equals(file.getName()))
				{
					paths.add(VfsUtil.getRelativePath(file, baseDir, '/'));
				}
				return true;
			}
		});
	}

	final String[] pathsAsArray = ArrayUtil.toStringArray(paths);
	return createAndSetupModule("Assembly-CSharp-Editor", project, newModel, pathsAsArray, unityBundle, layer ->
	{
		if(!isVersionHigherOrEqual(unityBundle, "2018.2"))
		{
			layer.addInvalidModuleEntry(ASSEMBLY_UNITYSCRIPT_FIRSTPASS);
		}

		layer.addInvalidModuleEntry("Assembly-CSharp-firstpass");
		layer.addInvalidModuleEntry("Assembly-CSharp");

		layer.addOrderEntry(new DotNetLibraryOrderEntryImpl(layer, "UnityEditor.Graphs"));

		if(isVersionHigherOrEqual(unityBundle, "4.6.0"))
		{
			layer.addOrderEntry(new DotNetLibraryOrderEntryImpl(layer, "UnityEditor.UI"));
		}

		if(isVersionHigherOrEqual(unityBundle, "5.3.0"))
		{
			layer.addOrderEntry(new DotNetLibraryOrderEntryImpl(layer, "nunit.framework"));
			layer.addOrderEntry(new DotNetLibraryOrderEntryImpl(layer, "UnityEngine.TestRunner"));
			layer.addOrderEntry(new DotNetLibraryOrderEntryImpl(layer, "UnityEditor.TestRunner"));

			// enable nunit
			layer.getExtensionWithoutCheck(Unity3dNUnitMutableModuleExtension.class).setEnabled(true);
		}

		if(isVersionHigherOrEqual(unityBundle, "2017.1.0"))
		{
			layer.addOrderEntry(new DotNetLibraryOrderEntryImpl(layer, "UnityEditor.Timeline"));
		}

		if(isVuforiaEnabled(unityBundle, project))
		{
			layer.addOrderEntry(new DotNetLibraryOrderEntryImpl(layer, "Vuforia.UnityExtensions.Editor"));
		}
	}, "unity3d-csharp-child", CSharpFileType.INSTANCE, virtualFilesByModule, progressIndicator, context);
}
 
Example 18
@RequiredReadAction
private static void notifyAboutPluginFile(@Nonnull final Project project)
{
	Unity3dRootModuleExtension moduleExtension = Unity3dModuleExtensionUtil.getRootModuleExtension(project);
	if(moduleExtension == null)
	{
		return;
	}

	Unity3dDefineByVersion unity3dDefineByVersion = Unity3dProjectImportUtil.getUnity3dDefineByVersion(moduleExtension.getSdk());
	final String pluginFileName = unity3dDefineByVersion.getPluginFileName();
	if(pluginFileName == null)
	{
		return;
	}

	File pluginPath = PluginManager.getPluginPath(UnityPluginFileValidator.class);

	final File unityPluginFile = new File(pluginPath, "UnityEditorConsuloPlugin/" + pluginFileName);
	if(!unityPluginFile.exists())
	{
		return;
	}

	VirtualFile baseDir = project.getBaseDir();
	if(baseDir == null)
	{
		return;
	}

	DotNetTypeDeclaration consuloIntegration = DotNetPsiSearcher.getInstance(project).findType("Consulo.Internal.UnityEditor.ConsuloIntegration", GlobalSearchScope.allScope(project));
	if(consuloIntegration != null)
	{
		return;
	}

	List<VirtualFile> targetFiles = new SmartList<>();

	VirtualFile fileByRelativePath = baseDir.findFileByRelativePath(ourPath);
	if(fileByRelativePath != null)
	{
		VirtualFile[] children = fileByRelativePath.getChildren();
		for(VirtualFile child : children)
		{
			CharSequence nameSequence = child.getNameSequence();
			if(StringUtil.startsWith(nameSequence, "UnityEditorConsuloPlugin") && child.getFileType() == DotNetModuleFileType.INSTANCE)
			{
				targetFiles.add(child);
			}
		}
	}

	if(targetFiles.isEmpty())
	{
		showNotify(project, pluginFileName, unityPluginFile, "Consulo plugin for UnityEditor is missing<br><a href=\"update\">Install</a>", Collections.emptyList());
	}
	else
	{
		VirtualFile firstItem = targetFiles.size() == 1 ? targetFiles.get(0) : null;
		if(firstItem != null && VfsUtilCore.virtualToIoFile(firstItem).lastModified() == unityPluginFile.lastModified())
		{
			return;
		}

		String title = "Outdated Consulo plugin(s) for UnityEditor can create <a href=\"info\">issues</a>. <a href=\"update\">Update</a> are recommended";

		showNotify(project, pluginFileName, unityPluginFile, title, targetFiles);
	}
}
 
Example 19
@Nullable
private static VirtualFile getFlutterManagedAndroidDir(VirtualFile dir) {
  VirtualFile meta = dir.findChild(".metadata");
  if (meta != null) {
    try {
      Properties properties = new Properties();
      properties.load(new InputStreamReader(meta.getInputStream(), Charsets.UTF_8));
      String value = properties.getProperty("project_type");
      if (value == null) {
        return null;
      }
      switch (value) {
        case "app":
          return dir.findChild("android");
        case "module":
          return dir.findChild(".android");
        case "package":
          return null;
        case "plugin":
          return dir.findFileByRelativePath("example/android");
      }
    }
    catch (IOException e) {
      // fall thru
    }
  }
  VirtualFile android;
  android = dir.findChild(".android");
  if (android != null) {
    return android;
  }
  android = dir.findChild("android");
  if (android != null) {
    return android;
  }
  android = dir.findFileByRelativePath("example/android");
  if (android != null) {
    return android;
  }
  return null;
}
 
Example 20
public static PsiReference[] getReference(String path, @NotNull PsiElement element) {
    try {
        String currentPath = path.replace(YiiPsiReferenceProvider.projectPath, "").replaceAll("/[a-zA-Z0-9_]+?.(php|tpl)+$", "");
        String protectedPath = CommonHelper.searchCurrentProtected(path).replace(YiiPsiReferenceProvider.projectPath, "");
        String viewAbsolutePath = protectedPath + "/views";
        String viewPath = currentPath + "/views";

        String str = element.getText();
        TextRange textRange = CommonHelper.getTextRange(element, str);
        String uri = str.substring(textRange.getStartOffset(), textRange.getEndOffset());
        int start = textRange.getStartOffset();
        int len = textRange.getLength();

        if (!uri.endsWith(".tpl") && !uri.startsWith("smarty:")) {
            uri += ".php";
        }

        VirtualFile baseDir = YiiPsiReferenceProvider.project.getBaseDir();
        if (baseDir != null) {
            VirtualFile appDir = baseDir.findFileByRelativePath(viewPath);
            VirtualFile protectedPathDir = (!protectedPath.equals("")) ? baseDir.findFileByRelativePath(protectedPath) : null;

            String filepath = viewPath + "/" + uri;
            if (uri.matches("^//.+")) {
                filepath = viewAbsolutePath + "/" + uri.replace("//", "");
            }
            VirtualFile file = baseDir.findFileByRelativePath(filepath);

            if (file != null && appDir != null) {
                PsiReference ref = new FileReference(file, uri, element,
                        new TextRange(start, start + len), YiiPsiReferenceProvider.project, protectedPathDir, appDir);
                return new PsiReference[]{ref};
            }
        }
        return PsiReference.EMPTY_ARRAY;

    } catch (Exception e) {
        System.err.println("error" + e.getMessage());
    }
    return PsiReference.EMPTY_ARRAY;
}