下面列出了org.junit.jupiter.api.extension.ExtendWith#com.intellij.openapi.vfs.VirtualFile 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void processImport(Module module) {
Project project = module.getProject();
File gradleFile = null;
for(VirtualFile virtualFile : ModuleRootManager.getInstance(module).getContentRoots()) {
File baseDir = VfsUtilCore.virtualToIoFile(virtualFile);
File file = new File(baseDir, "build.gradle");
if (file.exists()) {
gradleFile = file;
break;
}
}
if (gradleFile != null) {
ProjectImportProvider gradleProjectImportProvider = getGradleProjectImportProvider();
ProjectImportBuilder gradleProjectImportBuilder = gradleProjectImportProvider.getBuilder();
AddModuleWizard wizard = new AddModuleWizard(project, gradleFile.getPath(), new ProjectImportProvider[]{gradleProjectImportProvider});
if (wizard.getStepCount() == 0 || wizard.showAndGet()) {
gradleProjectImportBuilder.commit(project, (ModifiableModuleModel)null, (ModulesProvider)null);
}
}
}
@Nullable
private static FileElement getFileElementFor(@Nonnull VirtualFile file) {
VirtualFile selectFile;
if ((file.getFileSystem() instanceof ArchiveFileSystem) && file.getParent() == null) {
selectFile = ArchiveVfsUtil.getVirtualFileForJar(file);
if (selectFile == null) {
return null;
}
}
else {
selectFile = file;
}
return new FileElement(selectFile, selectFile.getName());
}
public void testUnsavedDocument_DoNotGC() throws Exception {
final VirtualFile file = createFile();
Document document = myDocumentManager.getDocument(file);
int idCode = System.identityHashCode(document);
assertNotNull(file.toString(), document);
WriteCommandAction.runWriteCommandAction(myProject, new Runnable() {
@Override
public void run() {
myDocumentManager.getDocument(file).insertString(0, "xxx");
}
});
//noinspection UnusedAssignment
document = null;
System.gc();
System.gc();
document = myDocumentManager.getDocument(file);
assertEquals(idCode, System.identityHashCode(document));
}
@NotNull
public static Collection<Route> getRoute(@NotNull Project project, @NotNull String routeName) {
Map<String, Route> compiledRoutes = RouteHelper.getCompiledRoutes(project);
if(compiledRoutes.containsKey(routeName)) {
return Collections.singletonList(compiledRoutes.get(routeName));
}
Collection<Route> routes = new ArrayList<>();
Collection<VirtualFile> routeFiles = FileBasedIndex.getInstance().getContainingFiles(RoutesStubIndex.KEY, routeName, GlobalSearchScope.allScope(project));
for(StubIndexedRoute route: FileBasedIndex.getInstance().getValues(RoutesStubIndex.KEY, routeName, GlobalSearchScope.filesScope(project, routeFiles))) {
routes.add(new Route(route));
}
return routes;
}
@Nullable
protected PsiElement probeResolvePackage() {
for (Package pkg : component.packageConfig.packages) {
if (this.getPath().startsWith(pkg.name)) {
VirtualFile targetFile;
String moduleFilePath;
if (this.getPath().equals(pkg.name)) {
moduleFilePath = pkg.main;
} else {
moduleFilePath = this.getPath().replace(pkg.name, "");
}
targetFile = component.getBaseUrlPath(false)
.findFileByRelativePath(pkg.location + "/" + moduleFilePath + ".js");
if (null != targetFile) {
return getPsiManager().findFile(targetFile);
}
}
}
return null;
}
@Nullable
@Override
public Object collectInformation(@NotNull PsiFile file, @NotNull Editor editor, boolean hasErrors) {
try {
VirtualFile virtualFile = file.getVirtualFile();
// If the file is not supported, we skips the annotation by returning null.
if (!FileUtils.isFileSupported(virtualFile) || !IntellijLanguageClient.isExtensionSupported(virtualFile)) {
return null;
}
String uri = FileUtils.VFSToURI(virtualFile);
EditorEventManager eventManager = EditorEventManagerBase.forUri(uri);
// If the diagnostics list is locked, we need to skip annotating the file.
if (eventManager == null || !(eventManager.isDiagnosticSyncRequired() || eventManager.isCodeActionSyncRequired())) {
return null;
}
return RESULT;
} catch (Exception e) {
return null;
}
}
@Override
public Collection<VirtualFile> getRoots() {
Value value = getValue();
if (value instanceof RootsProvider) {
return ((RootsProvider)value).getRoots();
}
else if (value instanceof PsiFile) {
PsiFile vFile = ((PsiFile)value).getContainingFile();
if (vFile != null && vFile.getVirtualFile() != null) {
return Collections.singleton(vFile.getVirtualFile());
}
}
else if (value instanceof VirtualFile) {
return Collections.singleton(((VirtualFile)value));
}
else if (value instanceof PsiFileSystemItem) {
return Collections.singleton(((PsiFileSystemItem)value).getVirtualFile());
}
return Collections.emptyList();
}
public void setupSdkRoots(Sdk sdk, Sdk jdk) {
SdkModificator sdkModificator = sdk.getSdkModificator();
sdkModificator.removeAllRoots();
// add all class and source jars from the SDK lib/ folder
for(File file: RoboVmPlugin.getSdkLibraries()) {
VirtualFile virtualFile = JarFileSystem.getInstance().findLocalVirtualFileByPath(file.getAbsolutePath());
sdkModificator.addRoot(virtualFile, file.getName().endsWith("-sources.jar")? OrderRootType.SOURCES: OrderRootType.CLASSES);
}
// set the JDK version as the version string, otherwise
// IDEA gets angry
sdkModificator.setVersionString(jdk.getVersionString());
// set the home path, we check this in createSdkIfNotExists
sdkModificator.setHomePath(RoboVmPlugin.getSdkHome().getAbsolutePath());
// commit changes and let IDEA handle the rest
sdkModificator.commitChanges();
}
@Override
public String expand(final DataContext dataContext) {
final Project project = dataContext.getData(CommonDataKeys.PROJECT);
if (project == null) {
return null;
}
VirtualFile file = dataContext.getData(PlatformDataKeys.VIRTUAL_FILE);
if (file == null) {
return null;
}
final VirtualFile contentRoot = ProjectRootManager.getInstance(project).getFileIndex().getContentRootForFile(file);
if (contentRoot == null) {
return null;
}
return FileUtil.getRelativePath(getIOFile(contentRoot), getIOFile(file));
}
public void
testRenameExternalResponseDefinitionDeclarationWhereResponseDefinitionsAreNotInRoot() {
final VirtualFile definitionsFile =
myFixture.copyFileToProject(
FILES_PATH + "response_definitions_not_in_root_with_caret.yaml", "responses.yaml");
myFixture.copyFileToProject(
FILES_PATH + "external_definition_response_definitions_not_in_root.yaml", "swagger.yaml");
myFixture.configureFromExistingVirtualFile(definitionsFile);
myFixture.renameElementAtCaret("newName");
myFixture.checkResultByFile(
"swagger.yaml",
FILES_PATH + "external_definition_response_definitions_not_in_root_after.yaml",
true);
myFixture.checkResultByFile(
"responses.yaml",
FILES_PATH + "response_definitions_not_in_root_with_caret_after.yaml",
true);
}
/**
* 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);
}
}
}
public IntellijReferencePoint(@NotNull Project project, @NotNull VirtualFile virtualFile) {
if (!project.isInitialized()) {
throw new IllegalArgumentException("The given project must be initialized - " + project);
}
if (!virtualFile.exists()) {
throw new IllegalArgumentException("The given virtual file must exist - " + virtualFile);
} else if (!virtualFile.isDirectory()) {
throw new IllegalArgumentException(
"The given virtual file must be a directory - " + virtualFile);
}
this.project = project;
this.virtualFile = virtualFile;
}
@Override
@Nullable
public String getCompilerOutputUrl(@Nonnull ContentFolderTypeProvider contentFolderType) {
if (!myInheritOutput) {
VirtualFilePointer virtualFilePointer = myVirtualFilePointers.get(contentFolderType.getId());
if (virtualFilePointer != null) {
return virtualFilePointer.getUrl();
}
}
String backUrl = myCompilerConfiguration.getCompilerOutputUrl() + "/" + contentFolderType.getId().toLowerCase() + "/" + myModule.getName();
VirtualFile compilerOutput = myCompilerConfiguration.getCompilerOutput();
if (compilerOutput == null) {
return backUrl;
}
VirtualFile outDir = compilerOutput.findFileByRelativePath(contentFolderType.getId().toLowerCase() + "/" + myModule.getName());
return outDir != null ? outDir.getUrl() : backUrl;
}
public void contentsChanged(@NotNull VirtualFileEvent event) {
VirtualFile confFile = findPathInWebDir(settings.configFilePath);
if (confFile == null || !confFile.exists() || !event.getFile().equals(confFile)) {
return;
}
LOG.debug("RequireConfigVfsListener contentsChanged");
// RequirejsProjectComponent.this.project.getComponent(RequirejsProjectComponent.class).parseRequirejsConfig();
RequirejsProjectComponent.this.parseRequirejsConfig();
}
private static Properties loadProps(@Nullable VirtualFile filePath) throws IOException {
Properties props = new Properties();
if (filePath != null) {
try (InputStreamReader reader = new InputStreamReader(filePath.getInputStream(), filePath.getCharset())) {
// The Perforce config file is NOT the same as a Java
// config file. Java config files will read the "\" as
// an escape character, whereas the Perforce config file
// will keep it.
try (BufferedReader inp = new BufferedReader(reader)) {
String line;
while ((line = inp.readLine()) != null) {
int pos = line.indexOf('=');
if (pos > 0) {
final String key = line.substring(0, pos).trim();
final String value = line.substring(pos + 1).trim();
// NOTE: an empty value is a set value!
if (key.length() > 0) {
props.setProperty(key, value);
}
}
}
}
}
}
LOG.debug("Loaded property file " + filePath + " keys " + props.keySet());
return props;
}
public void setAutoBases(@Nonnull final Collection<VirtualFile> autoBases) {
final String path = myPatch.getBeforeName() == null ? myPatch.getAfterName() : myPatch.getBeforeName();
for (VirtualFile autoBase : autoBases) {
final VirtualFile willBeBase = PathMerger.getBase(autoBase, path);
if (willBeBase != null) {
myAutoBases.add(willBeBase);
}
}
}
private static boolean isProjectDirectory(@NotNull VirtualFile file, @Nullable Project project) {
if (!file.isDirectory() || project == null) {
return false;
}
final VirtualFile baseDir = project.getBaseDir();
return baseDir != null && baseDir.getPath().equals(file.getPath());
}
private void chooseWorkspacePath() {
FileChooserDescriptor descriptor =
new FileChooserDescriptor(true, false, false, false, false, false)
.withShowHiddenFiles(true) // Show root project view file
.withHideIgnored(false)
.withTitle("Select Project View File")
.withDescription("Select a project view file to import.")
.withFileFilter(
virtualFile ->
ProjectViewStorageManager.isProjectViewFile(new File(virtualFile.getPath())));
// File filters are broken for the native Mac file chooser.
descriptor.setForcedToUseIdeaFileChooser(true);
FileChooserDialog chooser =
FileChooserFactory.getInstance().createFileChooser(descriptor, null, null);
File startingLocation = null;
String projectViewPath = getProjectViewPath();
if (!projectViewPath.isEmpty()) {
File fileLocation = new File(projectViewPath);
if (fileLocation.exists()) {
startingLocation = fileLocation;
}
}
final VirtualFile[] files;
if (startingLocation != null) {
VirtualFile toSelect =
LocalFileSystem.getInstance().refreshAndFindFileByPath(startingLocation.getPath());
files = chooser.choose(null, toSelect);
} else {
files = chooser.choose(null);
}
if (files.length == 0) {
return;
}
VirtualFile file = files[0];
projectViewPathField.setText(file.getPath());
}
@Override
public String getCharset(@NotNull final VirtualFile file, @NotNull final byte[] content) {
String charset = XmlCharsetDetector.extractXmlEncodingFromProlog(content);
if (charset != null) return charset;
@NonNls String strContent;
try {
strContent = new String(content, "ISO-8859-1");
}
catch (UnsupportedEncodingException e) {
return null;
}
Charset c = HtmlUtil.detectCharsetFromMetaTag(strContent);
return c == null ? null : c.name();
}
public static void queryForSelectedTextEditor(@NotNull Project project) {
try {
Editor selectedTextEditor = FileEditorManager.getInstance(project).getSelectedTextEditor();
if (selectedTextEditor != null) {
Document document = selectedTextEditor.getDocument();
PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);
if (psiFile instanceof FileBase && !FileHelper.isInterface(psiFile.getFileType())) {
// Try to get the inferred types cached at the psi file user data
VirtualFile sourceFile = psiFile.getVirtualFile();
Application application = ApplicationManager.getApplication();
SignatureProvider.InferredTypesWithLines sigContext = psiFile.getUserData(SignatureProvider.SIGNATURE_CONTEXT);
InferredTypes signatures = sigContext == null ? null : sigContext.getTypes();
if (signatures == null) {
FileType fileType = sourceFile.getFileType();
if (FileHelper.isCompilable(fileType)) {
InsightManager insightManager = ServiceManager.getService(project, InsightManager.class);
if (!DumbService.isDumb(project)) {
LOG.debug("Reading types from file", psiFile);
PsiFile cmtFile = findCmtFileFromSource(project, sourceFile.getNameWithoutExtension());
if (cmtFile != null) {
Path cmtPath = FileSystems.getDefault().getPath(cmtFile.getVirtualFile().getPath());
insightManager.queryTypes(sourceFile, cmtPath, types -> application
.runReadAction(() -> annotatePsiFile(project, psiFile.getLanguage(), sourceFile, types)));
}
}
}
} else {
LOG.debug("Signatures found in user data cache");
application.runReadAction(() -> annotatePsiFile(project, psiFile.getLanguage(), sourceFile, signatures));
}
}
}
} catch (Error e) {
// might produce an AssertionError when project is being disposed, but the invokeLater still process that code
}
}
private InputStream getContents(Project project, Editor editor, VirtualFile file) throws IOException {
editor = getEditor(project, editor, file);
if (editor != null) {
return new ByteArrayInputStream(getText(editor).getBytes());
} else {
return file.getInputStream();
}
}
ConfigPartStack(VirtualFile vcsRoot, ConfigConnectionController connectionController) {
$$$setupUI$$$();
this.vcsRoot = vcsRoot;
this.connectionController = connectionController;
SwingUtil.iconOnlyButton(myAddItemButton, ADD_ITEM, SwingUtil.ButtonType.MINOR);
myAddItemButton.addActionListener(e -> showAddItemPopup());
}
@Override
public void selectFile(@Nullable VirtualFile vFile) {
if (vFile == null) return;
Change change = ChangeListManager.getInstance(myProject).getChange(vFile);
Object objectToFind = change != null ? change : vFile;
DefaultMutableTreeNode root = (DefaultMutableTreeNode)myView.getModel().getRoot();
DefaultMutableTreeNode node = TreeUtil.findNodeWithObject(root, objectToFind);
if (node != null) {
TreeUtil.selectNode(myView, node);
}
}
@NotNull
@Override
public Runnable processFile(final PsiFile file) {
VirtualFile vFile = file.getVirtualFile();
if (vFile instanceof VirtualFileWindow) vFile = ((VirtualFileWindow)vFile).getDelegate();
if (vFile == null || !ProjectRootManager.getInstance(file.getProject()).getFileIndex().isInSourceContent(vFile)) {
return EmptyRunnable.INSTANCE;
}
return () -> optimizeImports(file);
}
public BasicFormatResult(VirtualFile _file, int start, int end, int _line, int _column, boolean error) {
super(start, end, createHyperLink(_file, _line, _column));
file = _file;
line = _line;
column = _column;
isError = error;
}
protected byte readFlagsFromCache(@Nonnull VirtualFile file) {
boolean wasAutoDetectRun = false;
byte status = 0;
try (DataInputStream stream = autoDetectedAttribute.readAttribute(file)) {
status = stream == null ? 0 : stream.readByte();
wasAutoDetectRun = stream != null;
}
catch (IOException ignored) {
}
status = BitUtil.set(status, AUTO_DETECT_WAS_RUN_MASK, wasAutoDetectRun);
return (byte)(status & (AUTO_DETECTED_AS_TEXT_MASK | AUTO_DETECTED_AS_BINARY_MASK | AUTO_DETECT_WAS_RUN_MASK));
}
public void testCreatingDirectory() throws Exception {
String subSubDirPath = myRoot.getPath() + "/subDir/subSubDir";
assertFalse(new File(subSubDirPath).exists());
VirtualFile subDir = myGateway.findOrCreateFileSafely(subSubDirPath, true);
assertNotNull(subDir);
assertEquals(subSubDirPath, subDir.getPath());
assertTrue(new File(subSubDirPath).exists());
}
@Override
public void acceptPatch(TextFilePatch patch, Collection<VirtualFile> foundByName) {
if (! mySucceeded) return;
final Collection<VirtualFile> variants = filterVariants(patch, foundByName);
if ((variants != null) && (! variants.isEmpty())) {
final TextFilePatchInProgress textFilePatchInProgress = new TextFilePatchInProgress(patch, variants, myBaseDir);
myResult.add(textFilePatchInProgress);
registerFolderDecision(patch.getBeforeName(), textFilePatchInProgress.getBase());
} else {
mySucceeded = false;
}
}
public CompilerMessageImpl(Project project,
CompilerMessageCategory category,
String message,
@Nullable final VirtualFile file,
int row,
int column,
@Nullable final Navigatable navigatable) {
myProject = project;
myCategory = category;
myNavigatable = navigatable;
myMessage = message == null ? "" : message;
myRow = row;
myColumn = column;
myFile = file;
}
private boolean isValidFile(@NotNull VirtualFile virtualFile) {
if (virtualFile.isDirectory()) {
return false;
}
if(filterExtension.size() == 0) {
return true;
}
String extension = virtualFile.getExtension();
return extension != null && this.filterExtension.contains(extension);
}