Search in sources :

Example 11 with RuleReference

use of net.sourceforge.pmd.lang.rule.RuleReference in project pmd by pmd.

the class RuleSetFactory method parseRuleSetReferenceNode.

/**
 * Parse a rule node as an RuleSetReference for all Rules. Every Rule from
 * the referred to RuleSet will be added as a RuleReference except for those
 * explicitly excluded, below the minimum priority threshold for this
 * RuleSetFactory, or which are deprecated.
 *
 * @param ruleSetBuilder
 *            The RuleSet being constructed.
 * @param ruleElement
 *            Must be a rule element node.
 * @param ref
 *            The RuleSet reference.
 */
private void parseRuleSetReferenceNode(RuleSetBuilder ruleSetBuilder, Element ruleElement, String ref) throws RuleSetNotFoundException {
    String priority = null;
    NodeList childNodes = ruleElement.getChildNodes();
    Set<String> excludedRulesCheck = new HashSet<>();
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node child = childNodes.item(i);
        if (isElementNode(child, "exclude")) {
            Element excludeElement = (Element) child;
            String excludedRuleName = excludeElement.getAttribute("name");
            excludedRulesCheck.add(excludedRuleName);
        } else if (isElementNode(child, PRIORITY)) {
            priority = parseTextNode(child).trim();
        }
    }
    final RuleSetReference ruleSetReference = new RuleSetReference(ref, true, excludedRulesCheck);
    // load the ruleset with minimum priority low, so that we get all rules, to be able to exclude any rule
    // minimum priority will be applied again, before constructing the final ruleset
    RuleSetFactory ruleSetFactory = new RuleSetFactory(resourceLoader, RulePriority.LOW, warnDeprecated, this.compatibilityFilter != null);
    RuleSet otherRuleSet = ruleSetFactory.createRuleSet(RuleSetReferenceId.parse(ref).get(0));
    List<RuleReference> potentialRules = new ArrayList<>();
    int countDeprecated = 0;
    for (Rule rule : otherRuleSet.getRules()) {
        excludedRulesCheck.remove(rule.getName());
        if (!ruleSetReference.getExcludes().contains(rule.getName())) {
            RuleReference ruleReference = new RuleReference(rule, ruleSetReference);
            // override the priority
            if (priority != null) {
                ruleReference.setPriority(RulePriority.valueOf(Integer.parseInt(priority)));
            }
            if (rule.isDeprecated()) {
                countDeprecated++;
            }
            potentialRules.add(ruleReference);
        }
    }
    boolean rulesetDeprecated = false;
    if (!potentialRules.isEmpty() && potentialRules.size() == countDeprecated) {
        // all rules in the ruleset have been deprecated - the ruleset itself is considered to be deprecated
        rulesetDeprecated = true;
        LOG.warning("The RuleSet " + ref + " has been deprecated and will be removed in PMD " + PMDVersion.getNextMajorRelease());
    }
    for (RuleReference r : potentialRules) {
        if (rulesetDeprecated || !r.getRule().isDeprecated()) {
            // add the rule, if either the ruleset itself is deprecated (then we add all rules)
            // or if the rule is not deprecated (in that case, the ruleset might contain deprecated as well
            // as valid references to rules)
            ruleSetBuilder.addRuleIfNotExists(r);
        }
    }
    if (!excludedRulesCheck.isEmpty()) {
        throw new IllegalArgumentException("Unable to exclude rules " + excludedRulesCheck + "; perhaps the rule name is mispelled?");
    }
}
Also used : RuleReference(net.sourceforge.pmd.lang.rule.RuleReference) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) XPathRule(net.sourceforge.pmd.lang.rule.XPathRule) MockRule(net.sourceforge.pmd.lang.rule.MockRule) HashSet(java.util.HashSet)

Example 12 with RuleReference

use of net.sourceforge.pmd.lang.rule.RuleReference in project pmd-eclipse-plugin by pmd.

the class ExamplePanelManager method updateOverridenFields.

protected void updateOverridenFields() {
    Rule rule = soleRule();
    if (rule instanceof RuleReference) {
        RuleReference ruleReference = (RuleReference) rule;
        exampleField.setBackground(ruleReference.getOverriddenExamples() != null ? overridenColour : null);
    }
}
Also used : RuleReference(net.sourceforge.pmd.lang.rule.RuleReference) Rule(net.sourceforge.pmd.Rule)

Example 13 with RuleReference

use of net.sourceforge.pmd.lang.rule.RuleReference in project pmd-eclipse-plugin by pmd.

the class RuleDialog method refreshOverridden.

/**
 * Based on current settings of a RuleReference being edited, update the
 * visual indicators of whether an override of the underlying Rule is
 * occurring or not.
 */
protected void refreshOverridden() {
    if (mode == MODE_EDIT || mode == MODE_VIEW) {
        if (editedRule instanceof RuleReference) {
            RuleReference ruleReference = (RuleReference) editedRule;
            Color lightBlue = new Color(null, 196, 196, 255);
            nameText.setBackground(ruleReference.getOverriddenName() != null ? lightBlue : null);
            messageText.setBackground(ruleReference.getOverriddenMessage() != null ? lightBlue : null);
            priorityCombo.setBackground(ruleReference.getOverriddenPriority() != null ? lightBlue : null);
            descriptionText.setBackground(ruleReference.getOverriddenDescription() != null ? lightBlue : null);
            externalInfoUrlText.setBackground(ruleReference.getOverriddenExternalInfoUrl() != null ? lightBlue : null);
            exampleText.setBackground(ruleReference.getOverriddenExamples() != null ? lightBlue : null);
            xpathText.setBackground(ruleReference.hasOverriddenProperty(XPathRule.XPATH_DESCRIPTOR) ? lightBlue : null);
        }
    }
}
Also used : RuleReference(net.sourceforge.pmd.lang.rule.RuleReference) Color(org.eclipse.swt.graphics.Color)

Example 14 with RuleReference

use of net.sourceforge.pmd.lang.rule.RuleReference in project pmd-eclipse-plugin by pmd.

the class RuleDialog method buildRuleReferenceButton.

/**
 * Build the rule reference button
 */
private Button buildRuleReferenceButton(Composite parent) {
    final Button button = new Button(parent, SWT.CHECK);
    button.setText(getMessage(StringKeys.PREF_RULEEDIT_BUTTON_RULE_REFERENCE));
    button.setEnabled(false);
    button.setSelection(editedRule instanceof RuleReference);
    return button;
}
Also used : RuleReference(net.sourceforge.pmd.lang.rule.RuleReference) Button(org.eclipse.swt.widgets.Button)

Example 15 with RuleReference

use of net.sourceforge.pmd.lang.rule.RuleReference in project pmd by pmd.

the class RuleDocGenerator method generateRuleSetIndex.

/**
 * Generates for each ruleset a page. The page contains the details for each rule.
 *
 * @param rulesets all rulesets
 * @throws IOException
 */
private void generateRuleSetIndex(Map<Language, List<RuleSet>> rulesets) throws IOException {
    for (Map.Entry<Language, List<RuleSet>> entry : rulesets.entrySet()) {
        String languageTersename = entry.getKey().getTerseName();
        for (RuleSet ruleset : entry.getValue()) {
            String rulesetFilename = RuleSetUtils.getRuleSetFilename(ruleset);
            String filename = RULESET_INDEX_FILENAME_PATTERN.replace("${language.tersename}", languageTersename).replace("${ruleset.name}", rulesetFilename);
            Path path = getAbsoluteOutputPath(filename);
            String permalink = RULESET_INDEX_PERMALINK_PATTERN.replace("${language.tersename}", languageTersename).replace("${ruleset.name}", rulesetFilename);
            List<String> lines = new LinkedList<>();
            lines.add("---");
            lines.add("title: " + ruleset.getName());
            lines.add("summary: " + getRuleSetDescriptionSingleLine(ruleset));
            lines.add("permalink: " + permalink);
            lines.add("folder: pmd/rules/" + languageTersename);
            lines.add("sidebaractiveurl: /" + LANGUAGE_INDEX_PERMALINK_PATTERN.replace("${language.tersename}", languageTersename));
            lines.add("editmepath: ../" + getRuleSetSourceFilepath(ruleset));
            lines.add("keywords: " + getRuleSetKeywords(ruleset));
            lines.add("---");
            for (Rule rule : getSortedRules(ruleset)) {
                lines.add("## " + rule.getName());
                lines.add("");
                if (rule instanceof RuleReference) {
                    RuleReference ref = (RuleReference) rule;
                    if (ruleset.getFileName().equals(ref.getRuleSetReference().getRuleSetFileName())) {
                        // rule renamed within same ruleset
                        lines.add(DEPRECATION_LABEL);
                        lines.add("");
                        lines.add("This rule has been renamed. Use instead: [" + ref.getRule().getName() + "](" + "#" + ref.getRule().getName().toLowerCase(Locale.ROOT) + ")");
                        lines.add("");
                    } else {
                        // rule moved to another ruleset
                        String otherLink = RULESET_INDEX_PERMALINK_PATTERN.replace("${language.tersename}", languageTersename).replace("${ruleset.name}", RuleSetUtils.getRuleSetFilename(ref.getRuleSetReference().getRuleSetFileName()));
                        lines.add(DEPRECATION_LABEL);
                        lines.add("");
                        lines.add("The rule has been moved to another ruleset. Use instead: [" + ref.getRule().getName() + "](" + otherLink + "#" + ref.getRule().getName().toLowerCase(Locale.ROOT) + ")");
                        lines.add("");
                    }
                }
                if (rule.isDeprecated()) {
                    lines.add(DEPRECATION_LABEL);
                    lines.add("");
                }
                if (rule.getSince() != null) {
                    lines.add("**Since:** PMD " + rule.getSince());
                    lines.add("");
                }
                lines.add("**Priority:** " + rule.getPriority() + " (" + rule.getPriority().getPriority() + ")");
                lines.add("");
                if (rule.getMinimumLanguageVersion() != null) {
                    lines.add("**Minimum Language Version:** " + rule.getLanguage().getName() + " " + rule.getMinimumLanguageVersion().getVersion());
                    lines.add("");
                }
                lines.addAll(toLines(stripIndentation(rule.getDescription())));
                lines.add("");
                if (rule instanceof XPathRule || rule instanceof RuleReference && ((RuleReference) rule).getRule() instanceof XPathRule) {
                    lines.add("```");
                    lines.addAll(toLines(StringUtils.stripToEmpty(rule.getProperty(XPathRule.XPATH_DESCRIPTOR))));
                    lines.add("```");
                    lines.add("");
                } else {
                    lines.add("**This rule is defined by the following Java class:** " + "[" + rule.getRuleClass() + "](" + GITHUB_SOURCE_LINK + getRuleClassSourceFilepath(rule.getRuleClass()) + ")");
                    lines.add("");
                }
                if (!rule.getExamples().isEmpty()) {
                    lines.add("**Example(s):**");
                    lines.add("");
                    for (String example : rule.getExamples()) {
                        lines.add("``` " + mapLanguageForHighlighting(languageTersename));
                        lines.addAll(toLines(StringUtils.stripToEmpty(example)));
                        lines.add("```");
                        lines.add("");
                    }
                }
                List<PropertyDescriptor<?>> properties = new ArrayList<>(rule.getPropertyDescriptors());
                // filter out standard properties
                properties.remove(Rule.VIOLATION_SUPPRESS_REGEX_DESCRIPTOR);
                properties.remove(Rule.VIOLATION_SUPPRESS_XPATH_DESCRIPTOR);
                properties.remove(XPathRule.XPATH_DESCRIPTOR);
                properties.remove(XPathRule.VERSION_DESCRIPTOR);
                if (!properties.isEmpty()) {
                    lines.add("**This rule has the following properties:**");
                    lines.add("");
                    lines.add("|Name|Default Value|Description|");
                    lines.add("|----|-------------|-----------|");
                    for (PropertyDescriptor<?> propertyDescriptor : properties) {
                        String description = propertyDescriptor.description();
                        if (description != null && description.toLowerCase(Locale.ROOT).startsWith(DEPRECATED_RULE_PROPERTY_MARKER)) {
                            description = DEPRECATION_LABEL_SMALL + description.substring(DEPRECATED_RULE_PROPERTY_MARKER.length());
                        }
                        lines.add("|" + propertyDescriptor.name() + "|" + (propertyDescriptor.defaultValue() != null ? String.valueOf(propertyDescriptor.defaultValue()) : "") + "|" + description + "|");
                    }
                    lines.add("");
                }
                lines.add("**Use this rule by referencing it:**");
                lines.add("``` xml");
                lines.add("<rule ref=\"category/" + languageTersename + "/" + rulesetFilename + ".xml/" + rule.getName() + "\" />");
                lines.add("```");
                lines.add("");
            }
            writer.write(path, lines);
            System.out.println("Generated " + path);
        }
    }
}
Also used : Path(java.nio.file.Path) RuleSet(net.sourceforge.pmd.RuleSet) RuleReference(net.sourceforge.pmd.lang.rule.RuleReference) PropertyDescriptor(net.sourceforge.pmd.properties.PropertyDescriptor) ArrayList(java.util.ArrayList) XPathRule(net.sourceforge.pmd.lang.rule.XPathRule) LinkedList(java.util.LinkedList) Language(net.sourceforge.pmd.lang.Language) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) XPathRule(net.sourceforge.pmd.lang.rule.XPathRule) Rule(net.sourceforge.pmd.Rule) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap) SortedMap(java.util.SortedMap)

Aggregations

RuleReference (net.sourceforge.pmd.lang.rule.RuleReference)23 Test (org.junit.Test)10 MockRule (net.sourceforge.pmd.lang.rule.MockRule)9 Rule (net.sourceforge.pmd.Rule)7 XPathRule (net.sourceforge.pmd.lang.rule.XPathRule)7 ArrayList (java.util.ArrayList)5 Language (net.sourceforge.pmd.lang.Language)4 List (java.util.List)3 PropertyDescriptor (net.sourceforge.pmd.properties.PropertyDescriptor)3 StringProperty (net.sourceforge.pmd.properties.StringProperty)3 Path (java.nio.file.Path)2 HashMap (java.util.HashMap)2 LinkedList (java.util.LinkedList)2 Map (java.util.Map)2 SortedMap (java.util.SortedMap)2 TreeMap (java.util.TreeMap)2 RuleSet (net.sourceforge.pmd.RuleSet)2 JavaUtilLoggingRule (net.sourceforge.pmd.junit.JavaUtilLoggingRule)2 Element (org.w3c.dom.Element)2 HashSet (java.util.HashSet)1