com.intellij.lang.javascript.psi.JSFile Java Examples

The following examples show how to use com.intellij.lang.javascript.psi.JSFile. 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: SnippetUtilTest.java    From idea-php-shopware-plugin with MIT License 6 votes vote down vote up
public void testSnippetsForBackend() {
    PsiFile psiFile = myFixture.configureByFile("snippets.js");

    Collection<ShopwareSnippet> snippetsInFile = SnippetUtil.getSnippetsInFile((JSFile) psiFile);

    assertNotNull(ContainerUtil.find(snippetsInFile, snippet ->
        "backend/foobar/namespace".equals(snippet.getNamespace()) && "start_accept".equals(snippet.getName())
    ));

    assertNotNull(ContainerUtil.find(snippetsInFile, snippet ->
        "backend/foobar".equals(snippet.getNamespace()) && "start_accept".equals(snippet.getName())
    ));

    assertNotNull(ContainerUtil.find(snippetsInFile, snippet ->
        "backend/foobar/namespace".equals(snippet.getNamespace()) && "filter_feature".equals(snippet.getName())
    ));

    assertNotNull(ContainerUtil.find(snippetsInFile, snippet ->
        "foobar".equals(snippet.getNamespace()) && "filter_feature".equals(snippet.getName())
    ));
}
 
Example #2
Source File: BlazeTypescriptGotoDeclarationHandler.java    From intellij with Apache License 2.0 6 votes vote down vote up
private static ImmutableList<JSLiteralExpression> getModuleDeclarations(
    ImmutableList<JSFile> jsFiles) {
  return findChildrenOfType(jsFiles, JSCallExpression.class).stream()
      .filter(
          call -> {
            JSExpression method = call.getMethodExpression();
            return method != null
                && (Objects.equals(method.getText(), "goog.provide")
                    || Objects.equals(method.getText(), "goog.module"));
          })
      .map(JSCallExpression::getArguments)
      .filter(a -> a.length == 1)
      .map(a -> a[0])
      .filter(JSLiteralExpression.class::isInstance)
      .map(JSLiteralExpression.class::cast)
      .filter(JSLiteralExpression::isQuotedLiteral)
      .collect(toImmutableList());
}
 
Example #3
Source File: BlazeTypescriptGotoDeclarationHandler.java    From intellij with Apache License 2.0 6 votes vote down vote up
private static ImmutableList<JSFile> jsFilesFromDtsSymbol(
    ExecutionRootPathResolver pathResolver,
    LocalFileSystem lfs,
    PsiManager psiManager,
    PsiElement dtsElement) {
  while (dtsElement != null && !(dtsElement instanceof PsiFile)) {
    PsiElement comment =
        PsiTreeUtil.findSiblingBackward(dtsElement, JSTokenTypes.END_OF_LINE_COMMENT, null);
    if (comment != null) {
      Matcher matcher = SYMBOL_GENERATED_FROM_JS_COMMENT.matcher(comment.getText());
      if (matcher.find()) {
        JSFile file = pathToJsFile(pathResolver, lfs, psiManager, matcher.group(1));
        return file != null ? ImmutableList.of(file) : ImmutableList.of();
      }
    }
    dtsElement = dtsElement.getParent();
  }
  return ImmutableList.of();
}
 
Example #4
Source File: GraphQLLanguageInjectionUtil.java    From js-graphql-intellij-plugin with MIT License 6 votes vote down vote up
public static String getEnvironment(PsiFile file) {
    if (file instanceof JSFile) {
        // for JS Files we have to check the kind of environment being used
        final Ref<String> envRef = new Ref<>();
        file.accept(new PsiRecursiveElementVisitor() {
            @Override
            public void visitElement(PsiElement element) {
                if (!isJSGraphQLLanguageInjectionTarget(element, envRef)) {
                    // no match yet, so keep visiting
                    super.visitElement(element);
                }
            }
        });
        final String environment = envRef.get();
        if (environment != null) {
            return environment;
        }
    } else if (file instanceof GraphQLFile) {
        final Ref<String> tag = new Ref<>();
        if (file.getContext() != null && isJSGraphQLLanguageInjectionTarget(file.getContext(), tag)) {
            return tag.get();
        }
    }
    // fallback is traditional GraphQL
    return GRAPHQL_ENVIRONMENT;
}
 
Example #5
Source File: GraphQLInjectedFormattingModelBuilder.java    From js-graphql-intellij-plugin with MIT License 6 votes vote down vote up
@NotNull
@Override
public FormattingModel createModel(PsiElement element, CodeStyleSettings settings) {
    if(element instanceof JSFile || element.getContainingFile() instanceof JSFile) {
        final JSFile file = (JSFile)(element instanceof JSFile ? element : element.getContainingFile());
        file.putUserData(WANT_DEFAULT_FORMATTER_KEY, true);
        try {
            final FormattingModelBuilder formattingModelBuilder = LanguageFormatting.INSTANCE.forContext(file.getLanguage(), element);
            if (formattingModelBuilder != null) {
                final FormattingModel model = formattingModelBuilder.createModel(element, settings);
                final Block rootBlock = model.getRootBlock();
                return new DelegatingFormattingModel(model, new GraphQLBlockWrapper(rootBlock, null, element.getNode(), rootBlock.getWrap(), rootBlock.getAlignment(), createSpaceBuilder(settings, element), settings));
            }
        } finally {
            file.putUserData(WANT_DEFAULT_FORMATTER_KEY, null);
        }
    }
    throw new IllegalArgumentException("Unsupported element '" + element + "'. It must be an element in a JSFile with its own default formatter to support injected GraphQL formatting");
}
 
Example #6
Source File: GraphQLInjectedFormattingModelBuilder.java    From js-graphql-intellij-plugin with MIT License 6 votes vote down vote up
@Override
public boolean isEngagedToFormat(PsiElement context) {
    if(context instanceof JSFile) {
        if(Boolean.TRUE.equals(context.getUserData(WANT_DEFAULT_FORMATTER_KEY))) {
            // we're looking up the default formatter at the moment
            return false;
        }
        Collection<JSStringTemplateExpression> templateExpressions = PsiTreeUtil.findChildrenOfType(context, JSStringTemplateExpression.class);
        for (JSStringTemplateExpression templateExpression : templateExpressions) {
            if(GraphQLLanguageInjectionUtil.isJSGraphQLLanguageInjectionTarget(templateExpression)) {
                return true;
            }
        }
    }
    return false;
}
 
Example #7
Source File: UnityScriptRootNamespaceAsElement.java    From consulo-unity3d with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
@RequiredReadAction
public Set<PsiElement> compute(@Nonnull final Project project,
		@Nullable final IndexBasedDotNetPsiSearcher searcher,
		@Nonnull final String indexKey,
		@Nonnull final String thisQName,
		@Nonnull final GlobalSearchScope scope)
{
	Set<PsiElement> elements = new LinkedHashSet<>();
	Collection<String> keys = UnityScriptFileByNameIndex.getInstance().getAllKeys(project);
	for(String key : keys)
	{
		ProgressManager.checkCanceled();
		Collection<JSFile> jsFiles = UnityScriptFileByNameIndex.getInstance().get(key, project, scope);
		for(JSFile jsFile : jsFiles)
		{
			elements.add(new UnityScriptDotNetTypeDeclaration(key, jsFile));
		}
	}
	return elements;
}
 
Example #8
Source File: BlazeJavaScriptTestRunLineMarkerContributor.java    From intellij with Apache License 2.0 6 votes vote down vote up
private static Icon getClosureTestIcon(
    Project project, Collection<Label> labels, JSFile file, JSFunction function) {
  WorkspaceRoot root = WorkspaceRoot.fromProject(project);
  WorkspacePath path = root.workspacePathFor(file.getVirtualFile());
  String relativePath = root.directory().getName() + '/' + path.relativePath();
  if (relativePath.endsWith(".js")) {
    relativePath = relativePath.substring(0, relativePath.lastIndexOf(".js"));
  }
  String urlSuffix =
      relativePath
          + SmRunnerUtils.TEST_NAME_PARTS_SPLITTER
          + function.getName()
          + SmRunnerUtils.TEST_NAME_PARTS_SPLITTER
          + relativePath; // redundant class name
  return labels.stream()
      .map(
          label ->
              SmRunnerUtils.GENERIC_TEST_PROTOCOL
                  + URLUtil.SCHEME_SEPARATOR
                  + label
                  + SmRunnerUtils.TEST_NAME_PARTS_SPLITTER
                  + urlSuffix)
      .map(url -> getTestStateIcon(url, project, /* isClass = */ false))
      .max(Comparator.comparingInt(iconPriorities::get))
      .orElse(TestState.Run);
}
 
Example #9
Source File: UnityScriptPsiSearcher.java    From consulo-unity3d with Apache License 2.0 6 votes vote down vote up
@RequiredReadAction
@Nonnull
@Override
public Collection<? extends DotNetTypeDeclaration> findTypesImpl(@Nonnull String key, @Nonnull GlobalSearchScope searchScope)
{
	if(DumbService.isDumb(myProject))
	{
		return Collections.emptyList();
	}

	Collection<JSFile> jsFiles = UnityScriptFileByNameIndex.getInstance().get(key, myProject, searchScope);
	JSFile jsFile = ContainerUtil.getFirstItem(jsFiles);
	if(jsFile == null)
	{
		return Collections.emptyList();
	}
	return Collections.singletonList(new UnityScriptDotNetTypeDeclaration(key, jsFile));
}
 
Example #10
Source File: BlazeJavascriptTestEventsHandler.java    From intellij with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public String getTestFilter(Project project, List<Location<?>> testLocations) {
  WorkspaceRoot root = WorkspaceRoot.fromProject(project);
  String rootName = root.directory().getName();
  String filter =
      testLocations.stream()
          .map(Location::getPsiElement)
          .map(PsiElement::getContainingFile)
          .filter(JSFile.class::isInstance)
          .map(PsiFile::getVirtualFile)
          .map(root::workspacePathFor)
          .map(WorkspacePath::relativePath)
          .map(FileUtil::getNameWithoutExtension)
          .distinct()
          .map(name -> '^' + rootName + '/' + name + '$')
          .reduce((a, b) -> a + "|" + b)
          .orElse(null);
  return filter != null
      ? String.format(
          "%s=%s", BlazeFlags.TEST_FILTER, BlazeParametersListUtil.encodeParam(filter))
      : null;
}
 
Example #11
Source File: BlazeJavascriptTestLocator.java    From intellij with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
private static List<Location> findClosureTestCase(
    Project project, File file, @Nullable String testName) {
  VirtualFile virtualFile = VfsUtils.resolveVirtualFile(file, /* refreshIfNeeded= */ false);
  if (virtualFile == null) {
    return ImmutableList.of();
  }
  PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile);
  if (!(psiFile instanceof JSFile)) {
    return ImmutableList.of();
  }
  if (testName != null) {
    for (JSFunction function : PsiTreeUtil.findChildrenOfType(psiFile, JSFunction.class)) {
      if (Objects.equals(function.getName(), testName)) {
        return ImmutableList.of(new PsiLocation<>(function));
      }
    }
  }
  return ImmutableList.of(new PsiLocation<>(psiFile));
}
 
Example #12
Source File: BlazeTypescriptGotoDeclarationHandler.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Nullable
private static JSFile pathToJsFile(
    ExecutionRootPathResolver pathResolver,
    LocalFileSystem lfs,
    PsiManager psiManager,
    String path) {
  return Optional.of(path)
      .map(ExecutionRootPath::new)
      .map(pathResolver::resolveExecutionRootPath)
      .map(lfs::findFileByIoFile)
      .map(psiManager::findFile)
      .filter(JSFile.class::isInstance)
      .map(JSFile.class::cast)
      .orElse(null);
}
 
Example #13
Source File: UnityScriptEventFunctionLineMarkerProvider.java    From consulo-unity3d with Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
@Nullable
@Override
public LineMarkerInfo getLineMarkerInfo(@Nonnull PsiElement element)
{
	if(element.getNode().getElementType() == JSTokenTypes.IDENTIFIER && element.getParent() instanceof JSReferenceExpression && element.getParent().getParent() instanceof JSFunction)
	{
		UnityFunctionManager functionManager = UnityFunctionManager.getInstance();
		Map<String, UnityFunctionManager.FunctionInfo> map = functionManager.getFunctionsByType().get(Unity3dTypes.UnityEngine.MonoBehaviour);
		if(map == null)
		{
			return null;
		}
		UnityFunctionManager.FunctionInfo functionInfo = map.get(element.getText());
		if(functionInfo == null)
		{
			return null;
		}
		Unity3dModuleExtension extension = ModuleUtilCore.getExtension(element, Unity3dModuleExtension.class);
		if(extension == null)
		{
			return null;
		}
		JSFunction jsFunction = (JSFunction) element.getParent().getParent();
		if(jsFunction.getParent() instanceof JSFile)
		{
			if(!isEqualParameters(functionInfo.getParameters(), jsFunction))
			{
				return null;
			}

			return new LineMarkerInfo<>(element, element.getTextRange(), Unity3dIcons.EventMethod, Pass.LINE_MARKERS, new ConstantFunction<>(functionInfo.getDescription()), null,
					GutterIconRenderer.Alignment.LEFT);
		}
	}
	return null;
}
 
Example #14
Source File: SnippetUtil.java    From idea-php-shopware-plugin with MIT License 5 votes vote down vote up
/**
 * This call should only used inside index process
 */
@NotNull
public static Collection<ShopwareSnippet> getSnippetsInFile(@NotNull JSFile file) {
    Collection<ShopwareSnippet> snippets = new ArrayList<>();
    visitSnippets(file, snippets::add);
    return snippets;
}
 
Example #15
Source File: UnityScriptDotNetTypeDeclaration.java    From consulo-unity3d with Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
public UnityScriptDotNetTypeDeclaration(@Nonnull String nameWithoutExtension, @Nonnull JSFile file)
{
	super(file.getManager(), file.getLanguage());
	myNameWithoutExtension = nameWithoutExtension;
	myFile = file;
}
 
Example #16
Source File: BlazeTypescriptGotoDeclarationHandler.java    From intellij with Apache License 2.0 5 votes vote down vote up
private static <T extends PsiElement> ImmutableList<T> findChildrenOfType(
    ImmutableList<JSFile> jsFiles, Class<? extends T> aClass) {
  return jsFiles.stream()
      .map(f -> PsiTreeUtil.findChildrenOfType(f, aClass))
      .flatMap(Collection::stream)
      .collect(toImmutableList());
}
 
Example #17
Source File: UnityScriptFileProjectViewProvider.java    From consulo-unity3d with Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
@Nonnull
private Collection<AbstractTreeNode> doModify(Collection<AbstractTreeNode> children, ViewSettings settings)
{
	Unity3dRootModuleExtension rootModuleExtension = Unity3dModuleExtensionUtil.getRootModuleExtension(myProject);
	if(rootModuleExtension == null)
	{
		return children;
	}

	List<AbstractTreeNode> nodes = new ArrayList<>(children.size());
	for(AbstractTreeNode child : children)
	{
		ProgressManager.checkCanceled();

		Object value = child.getValue();
		if(value instanceof JSFile && ((JSFile) value).getFileType() == JavaScriptFileType.INSTANCE)
		{
			Module moduleForPsiElement = ModuleUtilCore.findModuleForPsiElement((PsiElement) value);
			if(moduleForPsiElement != null)
			{
				nodes.add(new UnityScriptFileNode(myProject, (PsiFile) value, settings));
				continue;
			}
		}
		nodes.add(child);
	}
	return nodes;
}
 
Example #18
Source File: BlazeTypescriptGotoDeclarationHandler.java    From intellij with Apache License 2.0 5 votes vote down vote up
/**
 * Usually, we can just compare {@link JSQualifiedNamedElement#getQualifiedName()}, but in
 * goog.module()s, the name "exports" replaces the actual exported symbol. E.g.,
 *
 * <pre>
 * goog.module('Foo');
 * exports.bar = goog.defineClass(null, { foo: function() {}});
 * </pre>
 *
 * creates a function with the qualified name of Foo.bar.foo.
 */
@Nullable
private static String getJsQualifiedName(JSQualifiedNamedElement jsElement) {
  String exportedName =
      Optional.ofNullable(
              PsiTreeUtil.getTopmostParentOfType(jsElement, JSAssignmentExpression.class))
          .map(JSAssignmentExpression::getDefinitionExpression)
          .map(JSQualifiedNamedElement::getQualifiedName)
          .filter(name -> name.equals("exports") || name.startsWith("exports."))
          .orElse(null);
  String qualifiedName = jsElement.getQualifiedName();
  if (qualifiedName == null || exportedName == null) {
    return qualifiedName;
  }
  String moduleName =
      Stream.of(jsElement)
          .map(PsiElement::getContainingFile)
          .map(JSFile.class::cast)
          .map(ImmutableList::of)
          // should be only one goog.module()
          .map(BlazeTypescriptGotoDeclarationHandler::getModuleDeclarations)
          .flatMap(Collection::stream)
          .findFirst()
          .map(JSLiteralExpression::getStringValue)
          .orElse(null);
  // if exports is already part of the element's qualified name, then the exported name is already
  // included, otherwise we have to include the exported name
  return qualifiedName.startsWith("exports")
      ? moduleName + qualifiedName.substring("exports".length())
      : moduleName + exportedName.substring("exports".length()) + '.' + qualifiedName;
}
 
Example #19
Source File: BlazeTypescriptGotoDeclarationHandler.java    From intellij with Apache License 2.0 5 votes vote down vote up
private static ImmutableList<? extends JSQualifiedNamedElement> getResolveCandidates(
    PsiElement dtsElement, ImmutableList<JSFile> jsFiles) {
  if (dtsElement instanceof TypeScriptClass) {
    return Stream.concat(
            findChildrenOfType(jsFiles, JSClass.class).stream(),
            // Apparently you can declare a JS class with just a constructor function and
            // attach some properties to it.
            findChildrenOfType(jsFiles, JSFunction.class).stream())
        .collect(toImmutableList());
  } else if (dtsElement instanceof TypeScriptFunction) {
    TypeScriptFunction dtsFunction = (TypeScriptFunction) dtsElement;
    return findChildrenOfType(jsFiles, JSFunction.class).stream()
        .filter(f -> staticModifierEquals(f, dtsFunction))
        .collect(toImmutableList());
  } else if (dtsElement instanceof TypeScriptEnum) {
    return findChildrenOfType(jsFiles, JSObjectLiteralExpression.class).stream()
        .map(PsiElement::getParent)
        .filter(JSAssignmentExpression.class::isInstance)
        .map(PsiElement::getFirstChild)
        .filter(JSDefinitionExpression.class::isInstance)
        .map(JSDefinitionExpression.class::cast)
        .collect(toImmutableList());
  } else if (dtsElement instanceof TypeScriptEnumField) {
    return findChildrenOfType(jsFiles, JSProperty.class);
  }
  return ImmutableList.of();
}
 
Example #20
Source File: BlazeTypescriptGotoDeclarationHandler.java    From intellij with Apache License 2.0 5 votes vote down vote up
private static ImmutableList<PsiElement> resolveToJs(
    ExecutionRootPathResolver pathResolver,
    LocalFileSystem lfs,
    PsiManager psiManager,
    boolean isConstructor,
    PsiElement dtsElement) {
  dtsElement = PsiTreeUtil.getParentOfType(dtsElement, JSQualifiedNamedElement.class, false);
  if (dtsElement == null) {
    return ImmutableList.of();
  }
  if (!TypeScriptUtil.isDefinitionFile(dtsElement.getContainingFile())) {
    return ImmutableList.of();
  }
  String qualifiedName = getDtsQualifiedName((JSQualifiedNamedElement) dtsElement);
  if (qualifiedName == null) {
    return ImmutableList.of();
  }
  ImmutableList<JSFile> jsFiles = jsFilesFromDtsSymbol(pathResolver, lfs, psiManager, dtsElement);
  if (jsFiles.isEmpty()) {
    return ImmutableList.of();
  }
  if (dtsElement instanceof TypeScriptModule) {
    String moduleName = getModuleName(qualifiedName);
    return isConstructor
        ? findChildrenOfType(jsFiles, JSFunction.class).stream()
            .filter(e -> isConstructorWithName(e, moduleName))
            .collect(toImmutableList())
        : getModuleDeclarations(jsFiles).stream()
            .filter(a -> Objects.equals(a.getStringValue(), moduleName))
            .collect(toImmutableList());
  }
  return getResolveCandidates(dtsElement, jsFiles).stream()
      .filter(e -> Objects.equals(getJsQualifiedName(e), qualifiedName))
      .collect(toImmutableList());
}
 
Example #21
Source File: JavascriptTestContextProvider.java    From intellij with Apache License 2.0 5 votes vote down vote up
/**
 * A closure test suite will contain
 *
 * <pre>goog.require('goog.testing.testSuite')</pre>
 *
 * and call the imported symbol as a top level statement.
 */
private static boolean isClosureTestSuite(JSFile file) {
  PsiElement testSuite = null;
  for (PsiElement element : file.getChildren()) {
    if (testSuite == null) {
      testSuite = findTestSuiteReference(element);
    } else {
      if (isTestSuiteCalled(testSuite, element)) {
        return true;
      }
    }
  }
  return false;
}
 
Example #22
Source File: JavascriptTestContextProvider.java    From intellij with Apache License 2.0 5 votes vote down vote up
/** jsunit_test can just be top level functions with a test prefix. */
private static boolean hasTopLevelTests(JSFile file) {
  return Arrays.stream(file.getChildren())
      .filter(JSFunction.class::isInstance)
      .map(JSFunction.class::cast)
      .map(JSFunction::getName)
      .filter(Objects::nonNull)
      .anyMatch(name -> name.startsWith("test"));
}
 
Example #23
Source File: JavascriptTestContextProvider.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public RunConfigurationContext getTestContext(ConfigurationContext context) {
  JSFile file =
      Optional.of(context)
          .map(ConfigurationContext::getPsiLocation)
          .map(PsiElement::getContainingFile)
          .filter(JSFile.class::isInstance)
          .map(JSFile.class::cast)
          .orElse(null);
  if (file == null) {
    return null;
  }
  ListenableFuture<TargetInfo> targetFuture =
      TestTargetHeuristic.targetFutureForPsiElement(file, null);
  if (targetFuture == null) {
    return null;
  }
  targetFuture =
      Futures.transform(
          targetFuture,
          (target) ->
              target != null && ReadAction.compute(() -> isTestFile(file)) ? target : null,
          ApplicationManager.getApplication().isUnitTestMode()
              ? MoreExecutors.directExecutor()
              : PooledThreadExecutor.INSTANCE);
  return TestContext.builder(file, ExecutorType.DEBUG_UNSUPPORTED_TYPES)
      .setTarget(targetFuture)
      .setTestFilter(getTestFilter(file))
      .setDescription(file.getName())
      .build();
}
 
Example #24
Source File: JavascriptTestTargetHeuristic.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Override
public boolean matchesSource(
    Project project,
    TargetInfo target,
    @Nullable PsiFile sourcePsiFile,
    File sourceFile,
    @Nullable TestSize testSize) {
  Kind kind = target.getKind();
  return sourcePsiFile instanceof JSFile
      && kind != null
      && kind.getLanguageClass() == LanguageClass.JAVASCRIPT
      && kind.getRuleType() == RuleType.TEST;
}
 
Example #25
Source File: BlazeJavaScriptTestRunLineMarkerContributor.java    From intellij with Apache License 2.0 5 votes vote down vote up
private static ImmutableList<Label> getWrapperTests(JSFile file) {
  return CachedValuesManager.getCachedValue(
      file,
      () -> {
        Project project = file.getProject();
        BlazeProjectData projectData =
            BlazeProjectDataManager.getInstance(project).getBlazeProjectData();
        if (projectData == null) {
          return Result.create(
              ImmutableList.of(), BlazeSyncModificationTracker.getInstance(project));
        }
        ImmutableMultimap<TargetKey, TargetKey> rdeps = ReverseDependencyMap.get(project);
        TargetMap targetMap = projectData.getTargetMap();
        return Result.create(
            SourceToTargetFinder.findTargetsForSourceFile(
                    project,
                    VfsUtil.virtualToIoFile(file.getVirtualFile()),
                    Optional.of(RuleType.TEST))
                .stream()
                .filter(t -> t.getKind() != null)
                .filter(t -> t.getKind().getLanguageClass() == LanguageClass.JAVASCRIPT)
                .map(t -> t.label)
                .map(TargetKey::forPlainTarget)
                .map(rdeps::get)
                .filter(Objects::nonNull)
                .flatMap(Collection::stream)
                .filter(
                    key -> {
                      TargetIdeInfo target = targetMap.get(key);
                      return target != null && target.getKind().isWebTest();
                    })
                .map(TargetKey::getLabel)
                .collect(ImmutableList.toImmutableList()),
            BlazeSyncModificationTracker.getInstance(project));
      });
}
 
Example #26
Source File: IconProvider.java    From reasonml-idea-plugin with MIT License 5 votes vote down vote up
private static boolean isBsJsFile(PsiFile psiFile) {
    if (psiFile instanceof JSFile) {
        JSFile jsFile = (JSFile) psiFile;
        return jsFile.getName().endsWith("." + BsConstants.BS_JS_FILE_EXTENSION);
    }
    return false;
}
 
Example #27
Source File: BlazeJavascriptTestLocator.java    From intellij with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
private static List<Location> findJasmineTestCase(
    Project project, TargetIdeInfo target, String suiteName, @Nullable String testName) {
  if (!searchForJasmineSources.getValue()) {
    return ImmutableList.of();
  }
  BlazeProjectData projectData =
      BlazeProjectDataManager.getInstance(project).getBlazeProjectData();
  if (projectData == null) {
    return ImmutableList.of();
  }
  PsiManager psiManager = PsiManager.getInstance(project);
  return OutputArtifactResolver.resolveAll(
          project,
          projectData.getArtifactLocationDecoder(),
          getJasmineSources(projectData, target))
      .stream()
      .map(f -> VfsUtils.resolveVirtualFile(f, /* refreshIfNeeded= */ false))
      .filter(Objects::nonNull)
      .map(psiManager::findFile)
      .filter(JSFile.class::isInstance)
      .map(JSFile.class::cast)
      .map(JasmineFileStructureBuilder.getInstance()::buildTestFileStructure)
      .map(file -> findJasmineSuiteByName(file, suiteName))
      .filter(Objects::nonNull)
      .map(testSuite -> maybeFindJasmineTestCase(testSuite, testName))
      .map(AbstractJasmineElement::getEnclosingPsiElement)
      .map(PsiLocation::new)
      .collect(ImmutableList.toImmutableList());
}
 
Example #28
Source File: JsEnvironmentVariablesUsagesProvider.java    From idea-php-dotenv-plugin with MIT License 5 votes vote down vote up
@NotNull
@Override
public Collection<KeyUsagePsiElement> getUsages(PsiFile psiFile) {
    if(psiFile instanceof JSFile) {
        JsEnvironmentCallsVisitor visitor = new JsEnvironmentCallsVisitor();
        psiFile.acceptChildren(visitor);

        return visitor.getCollectedItems();
    }

    return Collections.emptyList();
}
 
Example #29
Source File: ReferenceTest.java    From WebStormRequireJsPlugin with MIT License 4 votes vote down vote up
public void testReference()
{
    PsiReference reference;
    PsiElement referenceElement;

    // referenceNotFound
    myFixture.getEditor().getCaretModel().moveToLogicalPosition(new LogicalPosition(1, 40));
    reference = myFixture.getReferenceAtCaretPosition();
    assertTrue(reference instanceof RequirejsReference);
    assertEquals("'app/as'", reference.getCanonicalText());
    referenceElement = reference.resolve();
    assertNull(referenceElement);

    // referenceTrue
    myFixture
            .getEditor()
            .getCaretModel()
            .moveToLogicalPosition(new LogicalPosition(2, 40));
    reference = myFixture.getReferenceAtCaretPosition();
    assertTrue(reference instanceof RequirejsReference);
    assertEquals("'blocks/block'", reference.getCanonicalText());
    referenceElement = reference.resolve();
    assertTrue(referenceElement instanceof JSFile);
    assertEquals("block.js", ((JSFile) referenceElement).getName());

    // referenceNotFound2
    myFixture
            .getEditor()
            .getCaretModel()
            .moveToLogicalPosition(new LogicalPosition(3, 40));
    reference = myFixture.getReferenceAtCaretPosition();
    assertTrue(reference instanceof PsiMultiReference);
    reference = ((PsiMultiReference) reference).getReferences()[1];
    assertEquals("'bl'", reference.getCanonicalText());
    referenceElement = reference.resolve();
    assertNull(referenceElement);

    // referenceDirectory
    myFixture
            .getEditor()
            .getCaretModel()
            .moveToLogicalPosition(new LogicalPosition(4, 40));
    reference = myFixture.getReferenceAtCaretPosition();
    assertTrue(reference instanceof RequirejsReference);
    assertEquals("'blocks/childBlocks'", reference.getCanonicalText());
    referenceElement = reference.resolve();
    assertNull(referenceElement);

    // referenceWithTwoDot
    myFixture
            .getEditor()
            .getCaretModel()
            .moveToLogicalPosition(new LogicalPosition(5, 46));
    reference = myFixture.getReferenceAtCaretPosition();
    assertTrue(reference instanceof RequirejsReference);
    assertEquals("'../blocks/block'", reference.getCanonicalText());
    referenceElement = reference.resolve();
    assertTrue(referenceElement instanceof JSFile);
    assertEquals("block.js", ((JSFile) referenceElement).getName());

    // referenceWithTwoDotTwoDir
    myFixture
            .getEditor()
            .getCaretModel()
            .moveToLogicalPosition(new LogicalPosition(6, 49));
    reference = myFixture.getReferenceAtCaretPosition();
    assertTrue(reference instanceof RequirejsReference);
    assertEquals("'../blocks/childBlocks/childBlock'", reference.getCanonicalText());
    referenceElement = reference.resolve();
    assertTrue(referenceElement instanceof JSFile);
    assertEquals("childBlock.js", ((JSFile) referenceElement).getName());

    // referenceWithOneDot
    myFixture
            .getEditor()
            .getCaretModel()
            .moveToLogicalPosition(new LogicalPosition(7, 44));
    reference = myFixture.getReferenceAtCaretPosition();
    assertTrue(reference instanceof RequirejsReference);
    assertEquals("'./block'", reference.getCanonicalText());
    referenceElement = reference.resolve();
    assertTrue(referenceElement instanceof JSFile);
    assertEquals("block.js", ((JSFile) referenceElement).getName());

    // referenceWithOneDotTwoDir
    myFixture
            .getEditor()
            .getCaretModel()
            .moveToLogicalPosition(new LogicalPosition(8, 50));
    reference = myFixture.getReferenceAtCaretPosition();
    assertTrue(reference instanceof RequirejsReference);
    assertEquals("'./childBlocks/childBlock'", reference.getCanonicalText());
    referenceElement = reference.resolve();
    assertTrue(referenceElement instanceof JSFile);
    assertEquals("childBlock.js", ((JSFile) referenceElement).getName());
}
 
Example #30
Source File: ESLintConfigFileUtil.java    From eslint-plugin with MIT License 4 votes vote down vote up
public static boolean isESLintConfigFile(JSFile file) {
    return file != null && (isESLintConfigFile(file.getVirtualFile()) || file.getFileType().equals(ESLintConfigFileType.INSTANCE));
}