org.jetbrains.yaml.YAMLUtil Java Examples

The following examples show how to use org.jetbrains.yaml.YAMLUtil. 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: EelHelperUtil.java    From intellij-neos with GNU General Public License v3.0 6 votes vote down vote up
public static HashMap<String, String> getHelpersInFile(@NotNull PsiFile psiFile) {
    YAMLKeyValue defaultContext = YAMLUtil.getQualifiedKeyInFile((YAMLFile) psiFile, "Neos", "Fusion", "defaultContext");

    if (defaultContext == null) {
        defaultContext = YAMLUtil.getQualifiedKeyInFile((YAMLFile) psiFile, "TYPO3", "TypoScript", "defaultContext");
    }

    HashMap<String, String> result = new HashMap<>();
    if (defaultContext != null) {
        PsiElement mapping = defaultContext.getLastChild();
        if (mapping instanceof YAMLMapping) {
            for (PsiElement mappingElement : mapping.getChildren()) {
                if (mappingElement instanceof YAMLKeyValue) {
                    YAMLKeyValue keyValue = (YAMLKeyValue) mappingElement;
                    result.put(keyValue.getKeyText(), keyValue.getValueText());
                    NeosProjectService.getLogger().debug(keyValue.getKeyText() + ": " + keyValue.getValueText());
                }
            }
        }
    }

    return result;
}
 
Example #2
Source File: NodeTypeReference.java    From intellij-neos with GNU General Public License v3.0 6 votes vote down vote up
@NotNull
@Override
public ResolveResult[] multiResolve(boolean incompleteCode) {
    String nodeTypeNameToFindReferenceFor = yamlElement.getKeyText();

    // files which contain the NodeType definition
    Collection<VirtualFile> files = FileBasedIndex.getInstance().getContainingFiles(NodeTypesYamlFileIndex.KEY, nodeTypeNameToFindReferenceFor, GlobalSearchScope.allScope(yamlElement.getProject()));

    return files
            .stream()
            // get the PSI for each file
            .map(file -> PsiManager.getInstance(yamlElement.getProject()).findFile(file))
            // ensure we only have YAML files
            .filter(psiFile -> psiFile instanceof YAMLFile)
            .map(psiFile -> (YAMLFile) psiFile)
            // get all YAML keys in these files
            .flatMap(yamlFile -> YAMLUtil.getTopLevelKeys(yamlFile).stream())
            // get the correct YAML key
            .filter(yamlKeyValue -> yamlKeyValue.getKeyText().equals(nodeTypeNameToFindReferenceFor))
            // remove "current" element if it exists
            .filter(yamlKeyValue -> yamlElement != yamlKeyValue)
            // build up the result object
            .map(yamlKeyValue -> new PsiElementResolveResult(yamlKeyValue, true))
            .toArray(PsiElementResolveResult[]::new);
}
 
Example #3
Source File: YamlHelper.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@Nullable
public static PsiElement insertKeyIntoFile(final @NotNull YAMLFile yamlFile, final @NotNull YAMLKeyValue yamlKeyValue, @NotNull String... keys) {
    String keyText = yamlKeyValue.getKeyText();

    return insertKeyIntoFile(yamlFile, (yamlMapping, chainedKey) -> {
        String text = yamlKeyValue.getText();

        final String previousIndent = StringUtil.repeatSymbol(' ', YAMLUtil.getIndentInThisLine(yamlMapping));

        // split content of array value object;
        // drop first item as getValueText() removes our key indent
        String[] remove = (String[]) ArrayUtils.remove(text.split("\\r?\\n"), 0);

        List<String> map = ContainerUtil.map(remove, s -> previousIndent + s);

        return "\n" + StringUtils.strip(StringUtils.join(map, "\n"), "\n");
    }, (String[]) ArrayUtils.add(keys, keyText));
}
 
Example #4
Source File: TranslationInsertUtil.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
private static PsiElement invokeTranslation(@NotNull final YAMLFile yamlFile, @NotNull final String keyName, @NotNull final String translation) {
    String[] split = keyName.split("\\.");
    PsiElement psiElement = YamlHelper.insertKeyIntoFile(yamlFile, "'" + translation + "'", split);
    if(psiElement == null) {
        return null;
    }

    // resolve target to get value
    YAMLKeyValue target = YAMLUtil.getQualifiedKeyInFile(yamlFile, split);
    if(target != null && target.getValue() != null) {
        return target.getValue();
    } else if(target != null) {
        return target;
    }

    return yamlFile;
}
 
Example #5
Source File: ServiceGenerateAction.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
private boolean isValidForFile(@NotNull PsiFile file) {

        if(file instanceof XmlFile) {
            XmlTag rootTag = ((XmlFile) file).getRootTag();
            return !(rootTag == null || !"container".equals(rootTag.getName()));
        } else if(file instanceof YAMLFile) {
            return
                YAMLUtil.getQualifiedKeyInFile((YAMLFile) file, "parameters") != null ||
                YAMLUtil.getQualifiedKeyInFile((YAMLFile) file, "services") != null;
        }

        return false;
    }
 
Example #6
Source File: NodeTypesYamlFileIndex.java    From intellij-neos with GNU General Public License v3.0 5 votes vote down vote up
@NotNull
private Map<String, Void> doIndex(FileContent fileContent) {
    Map<String, Void> result = new HashMap<>();
    YAMLUtil.getTopLevelKeys((YAMLFile)fileContent.getPsiFile())
            .forEach(yamlKeyValue -> result.put(yamlKeyValue.getKeyText(), null));
    return result;
}
 
Example #7
Source File: YamlHelper.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
@Nullable
public static String getStringValueOfKeyInProbablyMapping(@Nullable YAMLValue node, @NotNull String keyText) {
    YAMLKeyValue mapping = YAMLUtil.findKeyInProbablyMapping(node, keyText);
    if(mapping == null) {
        return null;
    }

    YAMLValue value = mapping.getValue();
    if(value == null) {
        return null;
    }

    return value.getText();
}
 
Example #8
Source File: YamlHelper.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
/**
 * Visit all key values in first level key
 *
 * parameters:
 *  foo: "foo"
 */
public static void visitQualifiedKeyValuesInFile(@NotNull YAMLFile yamlFile, @NotNull String firstLevelKeyToVisit, @NotNull Consumer<YAMLKeyValue> consumer) {
    YAMLKeyValue parameters = YAMLUtil.getQualifiedKeyInFile(yamlFile, firstLevelKeyToVisit);
    if(parameters == null) {
        return;
    }

    visitNextKeyValues(parameters, consumer);
}
 
Example #9
Source File: YamlHelper.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
/**
 * Get all key values in first level key visit
 *
 * parameters:
 *  foo: "foo"
 */
@NotNull
public static Collection<YAMLKeyValue> getQualifiedKeyValuesInFile(@NotNull YAMLFile yamlFile, @NotNull String firstLevelKeyToVisit) {
    YAMLKeyValue parameters = YAMLUtil.getQualifiedKeyInFile(yamlFile, firstLevelKeyToVisit);
    if(parameters == null) {
        return Collections.emptyList();
    }

    return getNextKeyValues(parameters);
}
 
Example #10
Source File: YamlHelper.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
/**
 * Process yaml key in second level filtered by a root:
 * File > roots -> "Item"
 * TODO: visitQualifiedKeyValuesInFile
 */
public static void processKeysAfterRoot(@NotNull PsiFile psiFile, @NotNull Processor<YAMLKeyValue> yamlKeyValueProcessor, @NotNull String... roots) {
    for (String root : roots) {
        YAMLKeyValue yamlKeyValue = YAMLUtil.getQualifiedKeyInFile((YAMLFile) psiFile, root);
        if(yamlKeyValue != null) {
            YAMLCompoundValue yaml = PsiTreeUtil.findChildOfType(yamlKeyValue, YAMLCompoundValue.class);
            if(yaml != null) {
                for(YAMLKeyValue yamlKeyValueVisit: PsiTreeUtil.getChildrenOfTypeAsList(yaml, YAMLKeyValue.class)) {
                    yamlKeyValueProcessor.process(yamlKeyValueVisit);
                }
            }
        }
    }
}
 
Example #11
Source File: YamlDuplicateServiceKeyInspection.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
protected void visitRoot(PsiFile psiFile, String rootName, @NotNull ProblemsHolder holder) {
    if(!(psiFile instanceof YAMLFile)) {
        return;
    }

    YAMLKeyValue yamlKeyValue = YAMLUtil.getQualifiedKeyInFile((YAMLFile) psiFile, rootName);
    if(yamlKeyValue == null) {
        return;
    }

    YAMLCompoundValue yaml = PsiTreeUtil.findChildOfType(yamlKeyValue, YAMLMapping.class);
    if(yaml != null) {
        YamlHelper.attachDuplicateKeyInspection(yaml, holder);
    }
}
 
Example #12
Source File: TwigUtil.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
/**
 * Collects Twig globals in given yaml configuration
 *
 * twig:
 *    globals:
 *       ga_tracking: '%ga_tracking%'
 *       user_management: '@AppBundle\Service\UserManagement'
 */
@NotNull
public static Map<String, String> getTwigGlobalsFromYamlConfig(@NotNull YAMLFile yamlFile) {
    YAMLKeyValue yamlKeyValue = YAMLUtil.getQualifiedKeyInFile(yamlFile, "twig", "globals");
    if(yamlKeyValue == null) {
        return Collections.emptyMap();
    }

    YAMLValue value = yamlKeyValue.getValue();
    if(!(value instanceof YAMLMapping)) {
        return Collections.emptyMap();
    }

    Map<String, String> pair = new HashMap<>();

    for (YAMLPsiElement element : value.getYAMLElements()) {
        if(!(element instanceof YAMLKeyValue)) {
            continue;
        }

        String keyText = ((YAMLKeyValue) element).getKeyText();
        if(StringUtils.isBlank(keyText)) {
            continue;
        }

        String valueText = ((YAMLKeyValue) element).getValueText();
        if(StringUtils.isBlank(valueText)) {
            continue;
        }

        pair.put(keyText, valueText);
    }

    return pair;
}
 
Example #13
Source File: ServiceContainerUtil.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
@NotNull
private static ServiceFileDefaults createDefaults(@NotNull YAMLFile psiFile) {
    YAMLKeyValue yamlKeyValueDefaults = YAMLUtil.getQualifiedKeyInFile(psiFile, "services", "_defaults");

    if(yamlKeyValueDefaults != null) {
        return new ServiceFileDefaults(
            YamlHelper.getYamlKeyValueAsBoolean(yamlKeyValueDefaults, "public"),
            YamlHelper.getYamlKeyValueAsBoolean(yamlKeyValueDefaults, "autowire")
        );
    }

    return ServiceFileDefaults.EMPTY;
}
 
Example #14
Source File: KubernetesYamlPsiUtil.java    From intellij-kubernetes with Apache License 2.0 5 votes vote down vote up
/**
 * Determines whether the element is within a Kubernetes YAML file. This is done by checking for the presence of "apiVersion" or "kind" as top-level keys within the first document of the file.
 *
 * @param element an element within the file to check.
 * @return true if the element is within A Kubernetes YAML file, otherwise, false.
 */
public static boolean isKubernetesFile(final PsiElement element) {
    final PsiFile file = element.getContainingFile();
    if (file instanceof YAMLFile) {
        final Collection<YAMLKeyValue> keys = YAMLUtil.getTopLevelKeys((YAMLFile) file);
        return keys.stream().map(YAMLKeyValue::getKeyText).anyMatch(s -> "apiVersion".equals(s) || "kind".equals(s));
    }
    return false;
}
 
Example #15
Source File: CreateMissingPropertiesIntentionAction.java    From intellij-kubernetes with Apache License 2.0 5 votes vote down vote up
@Override
public void invoke(@NotNull final Project project, final Editor editor, @NotNull final PsiElement psiElement) throws IncorrectOperationException {
    final YAMLElementGenerator elementGenerator = YAMLElementGenerator.getInstance(project);
    for (final String missingKey : missingKeys) {
        final YAMLKeyValue newKeyValue = elementGenerator.createYamlKeyValue(missingKey, "");
        mapping.add(elementGenerator.createEol());
        mapping.add(elementGenerator.createIndent(YAMLUtil.getIndentToThisElement(mapping)));
        mapping.add(newKeyValue);
    }
}
 
Example #16
Source File: ResolveEngine.java    From intellij-neos with GNU General Public License v3.0 5 votes vote down vote up
public static Collection<PsiElement> getNodeTypeDefinitions(Project project, String name, @Nullable String namespace) {
    String fqn = "Neos.Neos" + ":" + name;
    if (namespace != null) {
        String aliasNamespace = findNamespaceByAlias(project, namespace);
        if (aliasNamespace != null) {
            fqn = aliasNamespace + ":" + name;
        } else {
            fqn = namespace + ":" + name;
        }
    }

    Collection<VirtualFile> files = FileBasedIndex.getInstance().getContainingFiles(NodeTypesYamlFileIndex.KEY, fqn, GlobalSearchScope.allScope(project));

    // Check for legacy namespace
    if (files.isEmpty() && namespace == null) {
        return getNodeTypeDefinitions(project, name, "TYPO3.Neos");
    }

    final String finalFqn = fqn;
    return files
            .stream()
            // get the PSI for each file
            .map(file -> PsiManager.getInstance(project).findFile(file))
            // ensure we only have YAML files
            .filter(psiFile -> psiFile instanceof YAMLFile)
            .map(psiFile -> (YAMLFile) psiFile)
            // get all YAML keys in these files
            .flatMap(yamlFile -> YAMLUtil.getTopLevelKeys(yamlFile).stream())
            // get the correct YAML key
            .filter(yamlKeyValue -> yamlKeyValue.getKeyText().equals(finalFqn))
            .collect(Collectors.toList());
}
 
Example #17
Source File: TwigUtil.java    From idea-php-symfony2-plugin with MIT License 4 votes vote down vote up
/**
 * Collects Twig path in given yaml configuration
 *
 * twig:
 *  paths:
 *   "%kernel.root_dir%/../src/vendor/bundle/Resources/views": core
 */
@NotNull
public static Collection<Pair<String, String>> getTwigPathFromYamlConfig(@NotNull YAMLFile yamlFile) {
    YAMLKeyValue yamlKeyValue = YAMLUtil.getQualifiedKeyInFile(yamlFile, "twig", "paths");
    if(yamlKeyValue == null) {
        return Collections.emptyList();
    }

    YAMLValue value = yamlKeyValue.getValue();
    if(!(value instanceof YAMLMapping)) {
        return Collections.emptyList();
    }

    Collection<Pair<String, String>> pair = new ArrayList<>();

    for (YAMLPsiElement element : value.getYAMLElements()) {
        if(!(element instanceof YAMLKeyValue)) {
            continue;
        }

        String keyText = ((YAMLKeyValue) element).getKeyText();
        if(StringUtils.isBlank(keyText)) {
            continue;
        }

        keyText = keyText.replace("\\", "/").replaceAll("/+", "/");

        // empty value is empty string on out side:
        // "foo: "
        String valueText = "";

        YAMLValue yamlValue = ((YAMLKeyValue) element).getValue();
        if (yamlValue != null) {
            valueText = ((YAMLKeyValue) element).getValueText();
        } else {
            // workaround for foo: !foobar
            // as we got tag element
            PsiElement key = ((YAMLKeyValue) element).getKey();
            if(key != null) {
                PsiElement nextSiblingOfType = PsiElementUtils.getNextSiblingOfType(key, PlatformPatterns.psiElement(YAMLTokenTypes.TAG));
                if(nextSiblingOfType != null) {
                    String text = nextSiblingOfType.getText();
                    if(text.startsWith("!")) {
                        valueText = StringUtils.stripStart(text, "!");
                    }
                }
            }
        }

        // Symfony 3.4 / 4.0: namespace overwrite: "@!Foo" => "@Foo"
        valueText = StringUtils.stripStart(valueText, "!");

        // normalize null value
        if(valueText.equals("~")) {
            valueText = "";
        }

        pair.add(Pair.create(valueText, keyText));
    }

    return pair;
}
 
Example #18
Source File: RouteHelper.java    From idea-php-symfony2-plugin with MIT License 4 votes vote down vote up
/**
 * Find every possible route name declaration inside yaml, xml or @Route annotation
 */
@Nullable
public static PsiElement getRouteNameTarget(@NotNull Project project, @NotNull String routeName) {
    for(VirtualFile virtualFile: RouteHelper.getRouteDefinitionInsideFile(project, routeName)) {
        PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile);

        if(psiFile instanceof YAMLFile) {
            return YAMLUtil.getQualifiedKeyInFile((YAMLFile) psiFile, routeName);
        } else if(psiFile instanceof XmlFile) {
            PsiElement target = RouteHelper.getXmlRouteNameTarget((XmlFile) psiFile, routeName);
            if(target != null) {
                return target;
            }
        } else if(psiFile instanceof PhpFile) {
            // find on @Route annotation
            for (PhpClass phpClass : PhpPsiUtil.findAllClasses((PhpFile) psiFile)) {
                // get prefix by PhpClass
                String prefix = getRouteNamePrefix(phpClass);

                for (Method method : phpClass.getOwnMethods()) {
                    PhpDocComment docComment = method.getDocComment();
                    if(docComment == null) {
                        continue;
                    }

                    PhpDocCommentAnnotation container = AnnotationUtil.getPhpDocCommentAnnotationContainer(docComment);
                    if(container == null) {
                        continue;
                    }

                    // multiple @Route annotation in bundles are allowed
                    for (String routeClass : ROUTE_CLASSES) {
                        PhpDocTagAnnotation phpDocTagAnnotation = container.getPhpDocBlock(routeClass);
                        if(phpDocTagAnnotation != null) {
                            String annotationRouteName = phpDocTagAnnotation.getPropertyValue("name");
                            if(annotationRouteName != null) {
                                // name provided @Route(name="foobar")
                                if(routeName.equals(prefix + annotationRouteName)) {
                                    return phpDocTagAnnotation.getPropertyValuePsi("name");
                                }
                            } else {
                                // just @Route() without name provided
                                String routeByMethod = AnnotationBackportUtil.getRouteByMethod(phpDocTagAnnotation.getPhpDocTag());
                                if(routeName.equals(prefix + routeByMethod)) {
                                    return phpDocTagAnnotation.getPhpDocTag();
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    return null;
}
 
Example #19
Source File: RouteHelper.java    From idea-php-symfony2-plugin with MIT License 4 votes vote down vote up
@NotNull
public static Collection<StubIndexedRoute> getYamlRouteDefinitions(@NotNull YAMLDocument yamlDocument) {
    Collection<StubIndexedRoute> indexedRoutes = new ArrayList<>();

    for(YAMLKeyValue yamlKeyValue : YamlHelper.getTopLevelKeyValues((YAMLFile) yamlDocument.getContainingFile())) {

        YAMLValue element = yamlKeyValue.getValue();

        YAMLKeyValue path = YAMLUtil.findKeyInProbablyMapping(element, "path");

        // Symfony bc
        if(path == null) {
            path = YAMLUtil.findKeyInProbablyMapping(element, "pattern");
        }

        if(path == null) {
            continue;
        }

        // cleanup: 'foo', "foo"
        String keyText = StringUtils.strip(StringUtils.strip(yamlKeyValue.getKeyText(), "'"), "\"");
        if(StringUtils.isBlank(keyText)) {
            continue;
        }

        StubIndexedRoute route = new StubIndexedRoute(keyText);

        String routePath = path.getValueText();
        if(StringUtils.isNotBlank(routePath)) {
            route.setPath(routePath);
        }

        String methods = YamlHelper.getStringValueOfKeyInProbablyMapping(element, "methods");
        if(methods != null) {
            // value: [GET, POST,
            String[] split = methods.replace("[", "").replace("]", "").replaceAll(" +", "").toLowerCase().split(",");
            if(split.length > 0) {
                route.addMethod(split);
            }
        }

        String controller = getYamlController(yamlKeyValue);
        if(controller != null) {
            route.setController(normalizeRouteController(controller));
        }

        indexedRoutes.add(route);
    }

    return indexedRoutes;

}
 
Example #20
Source File: YamlHelper.java    From idea-php-symfony2-plugin with MIT License 4 votes vote down vote up
/**
 * Adds a yaml key on path. This implemention merge values and support nested key values
 * foo:\n  bar: car -> foo.car.foo.bar
 *
 * @param formatter any string think of provide qoute
 */
@Nullable
public static PsiElement insertKeyIntoFile(final @NotNull YAMLFile yamlFile, @NotNull KeyInsertValueFormatter formatter, @NotNull String... keys) {
    final Pair<YAMLKeyValue, String[]> lastKeyStorage = findLastKnownKeyInFile(yamlFile, keys);

    if(lastKeyStorage.getSecond().length == 0) {
        return null;
    }

    YAMLMapping childOfType = null;

    // root condition
    if(lastKeyStorage.getFirst() == null && lastKeyStorage.getSecond().length == keys.length) {
        YAMLValue topLevelValue = yamlFile.getDocuments().get(0).getTopLevelValue();
        if(topLevelValue instanceof YAMLMapping) {
            childOfType = (YAMLMapping) topLevelValue;
        }
    } else if(lastKeyStorage.getFirst() != null) {
        // found a key value in key path append it there
        childOfType = PsiTreeUtil.getChildOfType(lastKeyStorage.getFirst(), YAMLMapping.class);
    }

    if(childOfType == null) {
        return null;
    }

    // pre-generate an empty key value
    String chainedKey = YAMLElementGenerator.createChainedKey(Arrays.asList(lastKeyStorage.getSecond()), YAMLUtil.getIndentInThisLine(childOfType));

    // append value: should be string with right indent for key value
    String value = formatter.format(childOfType, chainedKey);
    if(value != null) {
        chainedKey += value;
    }

    YAMLFile dummyFile = YAMLElementGenerator.getInstance(yamlFile.getProject()).createDummyYamlWithText(chainedKey);

    final YAMLKeyValue next = PsiTreeUtil.collectElementsOfType(dummyFile, YAMLKeyValue.class).iterator().next();
    if(next == null) {
        return null;
    }

    // finally wirte changes
    final YAMLMapping finalChildOfType = childOfType;
    new WriteCommandAction(yamlFile.getProject()) {
        @Override
        protected void run(@NotNull Result result) throws Throwable {
            finalChildOfType.putKeyValue(next);
        }

        @Override
        public String getGroupID() {
            return "Key insertion";
        }
    }.execute();

    return childOfType;
}
 
Example #21
Source File: YamlTraversal.java    From intellij-swagger with MIT License 4 votes vote down vote up
@Override
public void addReferenceDefinition(final String path, PsiElement anchorPsiElement) {
  YAMLUtil.createI18nRecord(
      ((YAMLFile) anchorPsiElement.getContainingFile()), path.split("/"), "");
}