下面列出了com.intellij.psi.search.GlobalSearchScopes#com.intellij.openapi.vfs.VfsUtil 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void setProjectFilePathNoUI(@Nonnull final String filePath) {
final StateStorageManager stateStorageManager = getStateStorageManager();
final LocalFileSystem fs = LocalFileSystem.getInstance();
final File file = new File(filePath);
final File dirStore = file.isDirectory() ? new File(file, Project.DIRECTORY_STORE_FOLDER) : new File(file.getParentFile(), Project.DIRECTORY_STORE_FOLDER);
String defaultFilePath = new File(dirStore, "misc.xml").getPath();
// deprecated
stateStorageManager.addMacro(StoragePathMacros.PROJECT_FILE, defaultFilePath);
stateStorageManager.addMacro(StoragePathMacros.DEFAULT_FILE, defaultFilePath);
final File ws = new File(dirStore, "workspace.xml");
stateStorageManager.addMacro(StoragePathMacros.WORKSPACE_FILE, ws.getPath());
stateStorageManager.addMacro(StoragePathMacros.PROJECT_CONFIG_DIR, dirStore.getPath());
VfsUtil.markDirtyAndRefresh(false, true, true, fs.refreshAndFindFileByIoFile(dirStore));
myPresentableUrl = null;
}
@NotNull
public static Collection<String> resolveTemplateName(@NotNull Project project, @NotNull VirtualFile virtualFile) {
Set<String> templateNames = new HashSet<>();
for (TemplatePath templatePath : ViewCollector.getPaths(project)) {
VirtualFile viewDir = templatePath.getRelativePath(project);
if (viewDir == null) {
continue;
}
String relativePath = VfsUtil.getRelativePath(virtualFile, viewDir);
if (relativePath != null) {
relativePath = stripTemplateExtensions(relativePath);
if (templatePath.getNamespace() != null && StringUtils.isNotBlank(templatePath.getNamespace())) {
templateNames.add(templatePath.getNamespace() + "::" + relativePath.replace("/", "."));
} else {
templateNames.add(relativePath.replace("/", "."));
}
}
}
return templateNames;
}
public void testMoveClass() throws Exception {
final String testHx = "pack1/Moved.hx";
final String targetDirName = "pack2";
doTest((rootDir, rootAfter) -> {
final VirtualFile src = VfsUtil.findRelativeFile(testHx, rootDir);
assertNotNull("Class pack1.Moved not found", src);
PsiElement file = myPsiManager.findFile(src);
assertNotNull("Psi for " + testHx + " not found", file);
PsiElement cls = file.getNode().getPsi(HaxeFile.class).findChildByClass(HaxeClassDeclaration.class);
PackageWrapper pack = new PackageWrapper(myPsiManager, targetDirName);
VirtualFile targetDir = VfsUtil.findRelativeFile(targetDirName, rootDir);
PsiDirectoryImpl dir = new PsiDirectoryImpl(myPsiManager, targetDir);
ArrayList<PsiElement> list = new ArrayList<>();
list.add(cls);
new MoveClassesOrPackagesProcessor(myProject, PsiUtilCore.toPsiElementArray(list),
new SingleSourceRootMoveDestination(pack, dir),
true, true, null).run();
FileDocumentManager.getInstance().saveAllDocuments();
});
}
private static void generateSourceFile(String source, String baseDir) {
String packageName = extractPackage(source);
String className = extractClassName(source);
String sourcePath = buildSourcePath(baseDir, className, packageName);
VirtualFileManager manager = VirtualFileManager.getInstance();
VirtualFile virtualFile = manager.refreshAndFindFileByUrl(VfsUtil.pathToUrl(sourcePath));
if (virtualFile == null || !virtualFile.exists() || userConfirmedOverride(className)) {
ApplicationManager.getApplication().runWriteAction(() -> {
try {
if (virtualFile != null && virtualFile.exists()) {
virtualFile.setBinaryContent(source.getBytes("utf8"));
} else {
File file = new File(sourcePath);
FileUtils.writeStringToFile(file, source, "utf8");
manager.refreshAndFindFileByUrl(VfsUtil.pathToUrl(sourcePath));
}
} catch (IOException e) {
log.error(e);
}
});
}
}
/**
* Gives targets to files which relative to current file directory
*/
@NotNull
public static Collection<PsiFile> getFileResourceTargetsInDirectoryScope(@NotNull PsiFile psiFile, @NotNull String content) {
// bundle scope
if(content.startsWith("@")) {
return Collections.emptyList();
}
PsiDirectory containingDirectory = psiFile.getContainingDirectory();
if(containingDirectory == null) {
return Collections.emptyList();
}
VirtualFile relativeFile = VfsUtil.findRelativeFile(content, containingDirectory.getVirtualFile());
if(relativeFile == null) {
return Collections.emptyList();
}
PsiFile targetFile = PsiElementUtils.virtualFileToPsiFile(psiFile.getProject(), relativeFile);
if(targetFile == null) {
return Collections.emptyList();
}
return Collections.singletonList(targetFile);
}
public static void editFiles(final Project project, final List<VirtualFile> files, final List<VcsException> exceptions) {
ChangesUtil.processVirtualFilesByVcs(project, files, (vcs, items) -> {
final EditFileProvider provider = vcs.getEditFileProvider();
if (provider != null) {
try {
provider.editFiles(VfsUtil.toVirtualFileArray(items));
}
catch (VcsException e1) {
exceptions.add(e1);
}
for(VirtualFile file: items) {
VcsDirtyScopeManager.getInstance(project).fileDirty(file);
FileStatusManager.getInstance(project).fileStatusChanged(file);
}
}
});
}
private void saveToFile(AnActionEvent anActionEvent, String language, String className, String content, ClassEntry currentClass, DestinationChooser.FileDestination destination, String encoding) {
final VirtualFile file = destination.getFile();
final String sourcePath = file.getPath() + "/" + currentClass.getPackageName().replace(".", "/");
final String targetPath = CodeMakerUtil.generateClassPath(sourcePath, className, language);
VirtualFileManager manager = VirtualFileManager.getInstance();
VirtualFile virtualFile = manager
.refreshAndFindFileByUrl(VfsUtil.pathToUrl(targetPath));
if (virtualFile == null || !virtualFile.exists() || userConfirmedOverride()) {
// async write action
ApplicationManager.getApplication().runWriteAction(
new CreateFileAction(targetPath, content, encoding, anActionEvent
.getDataContext()));
}
}
@Override
public void setProjectFilePath(@Nonnull final String filePath) {
final StateStorageManager stateStorageManager = getStateStorageManager();
final LocalFileSystem fs = LocalFileSystem.getInstance();
final File file = new File(filePath);
final File dirStore = file.isDirectory() ? new File(file, Project.DIRECTORY_STORE_FOLDER) : new File(file.getParentFile(), Project.DIRECTORY_STORE_FOLDER);
String defaultFilePath = new File(dirStore, "misc.xml").getPath();
// deprecated
stateStorageManager.addMacro(StoragePathMacros.PROJECT_FILE, defaultFilePath);
stateStorageManager.addMacro(StoragePathMacros.DEFAULT_FILE, defaultFilePath);
final File ws = new File(dirStore, "workspace.xml");
stateStorageManager.addMacro(StoragePathMacros.WORKSPACE_FILE, ws.getPath());
stateStorageManager.addMacro(StoragePathMacros.PROJECT_CONFIG_DIR, dirStore.getPath());
ApplicationManager.getApplication().invokeAndWait(() -> VfsUtil.markDirtyAndRefresh(false, true, true, fs.refreshAndFindFileByIoFile(dirStore)), ModalityState.defaultModalityState());
myPresentableUrl = null;
}
private void updatePathFromTree(final List<? extends VirtualFile> selection, boolean now) {
if (!isToShowTextField() || myTreeIsUpdating) return;
String text = "";
if (selection.size() > 0) {
text = VfsUtil.getReadableUrl(selection.get(0));
}
else {
final List<VirtualFile> roots = myChooserDescriptor.getRoots();
if (!myFileSystemTree.getTree().isRootVisible() && roots.size() == 1) {
text = VfsUtil.getReadableUrl(roots.get(0));
}
}
myPathTextField.setText(text, now, new Runnable() {
public void run() {
myPathTextField.getField().selectAll();
setErrorText(null);
}
});
}
private static void updateFileContents(Project project, final VirtualFile vf, final File f) throws Throwable {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
InputStream in = null;
try {
in = new FileInputStream(f);
write(in, bytes);
} finally {
if (in != null) {
in.close();
}
}
VfsUtil.saveText(vf, bytes.toString());
PsiFile psiFile = PsiManager.getInstance(project).findFile(vf);
if (psiFile != null) {
new ReformatCodeProcessor(project, psiFile, null, false).run();
}
}
@RequiredUIAccess
@Override
public void reset() {
myFreeze = true;
try {
final String compilerOutput = CompilerConfiguration.getInstance(myProject).getCompilerOutputUrl();
if (compilerOutput != null) {
myProjectCompilerOutput.setText(FileUtil.toSystemDependentName(VfsUtil.urlToPath(compilerOutput)));
}
if (myProjectName != null) {
myProjectName.setText(myProject.getName());
}
}
finally {
myFreeze = false;
}
myContext.getDaemonAnalyzer().queueUpdate(mySettingsElement);
}
public static boolean isValidForIndex(@NotNull FileContent inputData) {
String fileName = inputData.getPsiFile().getName();
if(fileName.startsWith(".") || fileName.contains("Test")) {
return false;
}
// we check for project path, on no match we are properly inside external library paths
VirtualFile baseDir = inputData.getProject().getBaseDir();
if (baseDir == null) {
return true;
}
String relativePath = VfsUtil.getRelativePath(inputData.getFile(), baseDir, '/');
if(relativePath == null) {
return true;
}
// is Test file in path name
return !(relativePath.contains("\\Test\\") || relativePath.contains("\\Fixtures\\"));
}
@RequiredUIAccess
@Nonnull
public Image getIcon() {
if (myDirectory != null) {
VirtualFile virtualFile = myDirectory.getVirtualFile();
List<ContentFolder> contentFolders = ModuleUtilCore.getContentFolders(myDirectory.getProject());
for (ContentFolder contentFolder : contentFolders) {
VirtualFile file = contentFolder.getFile();
if(file == null) {
continue;
}
if(VfsUtil.isAncestor(file, virtualFile, false)) {
return contentFolder.getType().getIcon(contentFolder.getProperties());
}
}
}
return AllIcons.Nodes.Folder;
}
@Nullable
@RequiredReadAction
private static PsiDirectory tryNotNullizeDirectory(@Nonnull Project project, @Nullable PsiDirectory defaultTargetDirectory)
{
if(defaultTargetDirectory == null)
{
VirtualFile root = ArrayUtil.getFirstElement(ProjectRootManager.getInstance(project).getContentRoots());
if(root == null)
{
root = project.getBaseDir();
}
if(root == null)
{
root = VfsUtil.getUserHomeDir();
}
defaultTargetDirectory = root != null ? PsiManager.getInstance(project).findDirectory(root) : null;
if(defaultTargetDirectory == null)
{
LOG.warn("No directory found for project: " + project.getName() + ", root: " + root);
}
}
return defaultTargetDirectory;
}
@Override
public Module getModuleByFile(VirtualFile file) {
final Module module = myProjectFileIndex.getModuleForFile(file);
if (module != null) {
LOG.assertTrue(!module.isDisposed());
return module;
}
for (final VirtualFile root : myRootToModuleMap.keySet()) {
if (VfsUtil.isAncestor(root, file, false)) {
final Module mod = myRootToModuleMap.get(root);
if (mod != null) {
LOG.assertTrue(!mod.isDisposed());
}
return mod;
}
}
return null;
}
private static void createFile(@NotNull Project project, @NotNull String relativePath) {
VirtualFile relativeBlockScopeFile = null;
int i = relativePath.lastIndexOf("/");
if(i > 0) {
relativeBlockScopeFile = VfsUtil.findRelativeFile(ProjectUtil.getProjectDir(project), relativePath.substring(0, i).split("/"));
}
String content = TwigUtil.buildStringFromTwigCreateContainer(project, relativeBlockScopeFile);
IdeHelper.RunnableCreateAndOpenFile runnableCreateAndOpenFile = IdeHelper.getRunnableCreateAndOpenFile(project, TwigFileType.INSTANCE, ProjectUtil.getProjectDir(project), relativePath);
if(content != null) {
runnableCreateAndOpenFile.setContent(content);
}
runnableCreateAndOpenFile.run();
}
@Override
@Nullable
public LogicalRoot findLogicalRoot(@Nonnull final VirtualFile file) {
final Module module = ModuleUtil.findModuleForFile(file, myProject);
if (module == null) return null;
LogicalRoot result = null;
final List<LogicalRoot> list = getLogicalRoots(module);
for (final LogicalRoot root : list) {
final VirtualFile rootFile = root.getVirtualFile();
if (rootFile != null && VfsUtil.isAncestor(rootFile, file, false)) {
result = root;
break;
}
}
return result;
}
private static void removeImlFile(final File imlFile) {
final VirtualFile imlVirtualFile = VfsUtil.findFileByIoFile(imlFile, true);
if (imlVirtualFile != null && imlVirtualFile.exists()) {
ApplicationManager.getApplication()
.runWriteAction(
new Runnable() {
@Override
public void run() {
try {
imlVirtualFile.delete(this);
} catch (IOException e) {
logger.warn(
String.format(
"Could not delete file: %s, will try to continue anyway.",
imlVirtualFile.getPath()),
e);
}
}
});
}
}
@Nullable
private static OCFile correlateTestToHeader(OCFile file) {
// Quickly check foo_test.cc -> foo.h as well. "getAssociatedFileWithSameName" only does
// foo.cc <-> foo.h. However, if you do goto-related-symbol again, it will go from
// foo.h -> foo.cc instead of back to foo_test.cc.
PsiManager psiManager = PsiManager.getInstance(file.getProject());
String pathWithoutExtension = FileUtil.getNameWithoutExtension(file.getVirtualFile().getPath());
for (String testSuffix : PartnerFilePatterns.DEFAULT_PARTNER_SUFFIXES) {
if (pathWithoutExtension.endsWith(testSuffix)) {
String possibleHeaderName = StringUtil.trimEnd(pathWithoutExtension, testSuffix) + ".h";
VirtualFile virtualFile = VfsUtil.findFileByIoFile(new File(possibleHeaderName), false);
if (virtualFile != null) {
PsiFile psiFile = psiManager.findFile(virtualFile);
if (psiFile instanceof OCFile) {
return (OCFile) psiFile;
}
}
}
}
return null;
}
private void restartServiceIfConfigsChanged() {
if (!restartTypeScriptService.getValue()) {
return;
}
int pathHash = Arrays.hashCode(configs.keySet().stream().map(VirtualFile::getPath).toArray());
long contentTimestamp =
configs.values().stream()
.map(TypeScriptConfig::getDependencies)
.flatMap(Collection::stream)
.map(VfsUtil::virtualToIoFile)
.map(File::lastModified)
.max(Comparator.naturalOrder())
.orElse(0L);
int newConfigsHash = Objects.hash(pathHash, contentTimestamp);
if (configsHash.getAndSet(newConfigsHash) != newConfigsHash) {
TransactionGuard.getInstance()
.submitTransactionLater(
project, () -> TypeScriptCompilerService.restartServices(project, false));
}
}
public boolean matchesFile(VirtualFile file) {
if (myType == IgnoreSettingsType.MASK) {
myMatcher.reset(file.getName());
return myMatcher.matches();
} else {
// quick check for 'file' == exact match pattern
if (IgnoreSettingsType.FILE.equals(myType) && ! myFilenameIfFile.equals(file.getName())) return false;
VirtualFile selector = resolve();
if (Comparing.equal(selector, NullVirtualFile.INSTANCE)) return false;
if (myType == IgnoreSettingsType.FILE) {
return Comparing.equal(selector, file);
}
else {
if ("./".equals(myPath)) {
// special case for ignoring the project base dir (IDEADEV-16056)
return !file.isDirectory() && Comparing.equal(file.getParent(), selector);
}
return VfsUtil.isAncestor(selector, file, false);
}
}
}
@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();
}
public Icon getIcon() {
if (myIcon != null) {
return myIcon;
}
if (myIconPath != null && new File(FileUtil.toSystemDependentName(myIconPath)).exists()) {
Image image = null;
try {
image = ImageLoader.loadFromStream(VfsUtil.convertToURL(VfsUtil.pathToUrl(myIconPath)).openStream());
}
catch (IOException e) {
LOG.debug(e);
}
if (image != null){
return IconLoader.getIcon(image);
}
}
//return IconLoader.getIcon("/ant/filter.png");
return null;
}
@Nullable
private static String getRelativePathInSources(@Nonnull VirtualFile file,
final @Nonnull ModuleOutputPackagingElement moduleElement,
@Nonnull PackagingElementResolvingContext context) {
for (VirtualFile sourceRoot : moduleElement.getSourceRoots(context)) {
if (VfsUtil.isAncestor(sourceRoot, file, true)) {
return VfsUtilCore.getRelativePath(file, sourceRoot, '/');
}
}
return null;
}
@Nonnull
private MultiMap<VcsUser, String> generateHistory(@Nonnull List<VcsUser> users) throws IOException {
MultiMap<VcsUser, String> commits = MultiMap.createLinked();
for (VcsUser user : users) {
recordCommit(commits, user);
}
VfsUtil.markDirtyAndRefresh(false, true, false, myProject.getBaseDir());
return commits;
}
@Override
public void generateProject(@NotNull final Project project, final @NotNull VirtualFile baseDir, final @NotNull ShopwareInstallerSettings settings, @NotNull Module module) {
String downloadPath = settings.getVersion().getUrl();
String toDir = baseDir.getPath();
VirtualFile zipFile = PhpConfigurationUtil.downloadFile(project, null, toDir, downloadPath, "shopware.zip");
if (zipFile == null) {
showErrorNotification(project, "Cannot download Shopware.zip file");
return;
}
// Convert files
File zip = VfsUtil.virtualToIoFile(zipFile);
File base = VfsUtil.virtualToIoFile(baseDir);
Task.Backgroundable task = new Task.Backgroundable(project, "Extracting", true) {
@Override
public void run(@NotNull ProgressIndicator progressIndicator) {
try {
// unzip file
ZipUtil.extract(zip, base, null);
// Delete TMP File
FileUtil.delete(zip);
// Activate Plugin
IdeHelper.enablePluginAndConfigure(project);
} catch (IOException e) {
showErrorNotification(project, "There is a error occurred");
}
}
};
ProgressManager.getInstance().run(task);
}
@Nullable
public String getRelativePath(@NotNull Project project) {
if(!FileUtil.isAbsolute(path)) {
return path;
}
VirtualFile virtualFile = getDirectory();
if(virtualFile == null) {
return null;
}
return VfsUtil.getRelativePath(virtualFile, ProjectUtil.getProjectDir(project), '/');
}
@NotNull
public static Set<VirtualFile> resolveTemplateName(@NotNull Project project, @NotNull String templateName) {
Set<String> templateNames = new HashSet<>();
int i = templateName.indexOf("::");
String ns = null;
if (i > 0) {
ns = templateName.substring(0, i);
templateName = templateName.substring(i + 2, templateName.length());
}
String pointName = templateName.replace(".", "/");
// find template files by extensions
// templateNames.add(pointName.concat(".blade.php"));
templateNames.add(ViewCollector.curModule + "/" + pointName.concat(".html"));
templateNames.add(pointName.concat(".html"));
Set<VirtualFile> templateFiles = new HashSet<>();
for (TemplatePath templatePath : ViewCollector.getPaths(project)) {
// we have a namespace given; ignore all other paths
String namespace = templatePath.getNamespace();
if ((ns == null && namespace != null) || ns != null && !ns.equals(namespace)) {
continue;
}
VirtualFile viewDir = templatePath.getRelativePath(project);
if (viewDir == null) {
continue;
}
for (String templateRelative : templateNames) {
VirtualFile viewsDir = VfsUtil.findRelativeFile(templateRelative, viewDir);
if (viewsDir != null) {
templateFiles.add(viewsDir);
}
}
}
return templateFiles;
}
@SuppressWarnings("MethodMayBeStatic")
public void registerPaths(@Nonnull final Map<OrderRootType, Collection<File>> libraryFiles, @Nonnull Library.ModifiableModel model, @Nonnull String libraryName) {
for (Map.Entry<OrderRootType, Collection<File>> entry : libraryFiles.entrySet()) {
for (File file : entry.getValue()) {
VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file);
if (virtualFile == null) {
if (ExternalSystemConstants.VERBOSE_PROCESSING && entry.getKey() == BinariesOrderRootType.getInstance()) {
LOG.warn(String.format("Can't find %s of the library '%s' at path '%s'", entry.getKey(), libraryName, file.getAbsolutePath()));
}
String url = VfsUtil.getUrlForLibraryRoot(file);
model.addRoot(url, entry.getKey());
continue;
}
if (virtualFile.isDirectory()) {
model.addRoot(virtualFile, entry.getKey());
}
else {
VirtualFile archiveRoot = ArchiveVfsUtil.getArchiveRootForLocalFile(virtualFile);
if (archiveRoot == null) {
LOG.warn(String.format("Can't parse contents of the jar file at path '%s' for the library '%s''", file.getAbsolutePath(), libraryName));
continue;
}
model.addRoot(archiveRoot, entry.getKey());
}
}
}
}
public static boolean isEnabledForIndex(@Nullable Project project) {
if(project == null) {
return false;
}
if(isEnabled(project)) {
return true;
}
VirtualFile baseDir = project.getBaseDir();
return VfsUtil.findRelativeFile(baseDir, "vendor", "laravel") != null;
}