diff --git a/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/inspections/Ipv6CanonicalFormInspection.kt b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/inspections/Ipv6CanonicalFormInspection.kt index 0e50fc5b..6d20a332 100644 --- a/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/inspections/Ipv6CanonicalFormInspection.kt +++ b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/inspections/Ipv6CanonicalFormInspection.kt @@ -1,62 +1,23 @@ package net.sjrx.intellij.plugins.systemdunitfiles.inspections -import com.intellij.codeInspection.LocalInspectionTool -import com.intellij.codeInspection.ProblemHighlightType -import com.intellij.codeInspection.ProblemsHolder -import com.intellij.openapi.util.TextRange -import com.intellij.psi.PsiElementVisitor -import com.intellij.psi.util.PsiTreeUtil -import net.sjrx.intellij.plugins.systemdunitfiles.UnitFileLanguage +import com.intellij.codeInspection.LocalQuickFix import net.sjrx.intellij.plugins.systemdunitfiles.intentions.CanonicalizeIpv6QuickFix -import net.sjrx.intellij.plugins.systemdunitfiles.psi.UnitFile -import net.sjrx.intellij.plugins.systemdunitfiles.psi.UnitFilePropertyType -import net.sjrx.intellij.plugins.systemdunitfiles.psi.UnitFileSectionGroups -import net.sjrx.intellij.plugins.systemdunitfiles.psi.UnitFileVisitor -import net.sjrx.intellij.plugins.systemdunitfiles.semanticdata.SemanticDataRepository -import net.sjrx.intellij.plugins.systemdunitfiles.semanticdata.fileClass -import net.sjrx.intellij.plugins.systemdunitfiles.semanticdata.optionvalues.grammar.GrammarOptionValue -import net.sjrx.intellij.plugins.systemdunitfiles.semanticdata.optionvalues.grammar.canonicalizeIpv6 import net.sjrx.intellij.plugins.systemdunitfiles.semanticdata.optionvalues.grammar.SemanticTag -import net.sjrx.intellij.plugins.systemdunitfiles.semanticdata.optionvalues.grammar.labeledRegions +import net.sjrx.intellij.plugins.systemdunitfiles.semanticdata.optionvalues.grammar.canonicalizeIpv6 import net.sjrx.intellij.plugins.systemdunitfiles.settings.ExperimentalSettings /** - * Suggests rewriting an IPv6 address to its RFC 5952 canonical form (#363), behind the experimental - * flag. It walks the grammar's labeled value spans and, for those the grammar tagged - * [SemanticTag.IPV6], offers a quick-fix when the address isn't already canonical. Keying off the tag - * (rather than re-sniffing every literal span) means it only ever touches spans the grammar declared - * to be IPv6 addresses. + * Suggests rewriting an IPv6 address (a span tagged [SemanticTag.IPV6]) to its RFC 5952 canonical form + * (#363), behind the grammar flag. Addresses [canonicalizeIpv6] can't handle (e.g. an IPv4 tail) are + * left alone. */ -class Ipv6CanonicalFormInspection : LocalInspectionTool() { +class Ipv6CanonicalFormInspection : TaggedSpanRewriteInspection() { + + override val tag = SemanticTag.IPV6 - override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { - val file = holder.file - if (file !is UnitFile || !file.language.isKindOf(UnitFileLanguage.INSTANCE)) return PsiElementVisitor.EMPTY_VISITOR - if (!ExperimentalSettings.getInstance(file.project).state.useGrammarParseEngine) return PsiElementVisitor.EMPTY_VISITOR - return MyVisitor(holder) - } + override fun rewriter(settings: ExperimentalSettings.State): ((String) -> String?) = ::canonicalizeIpv6 - private class MyVisitor(private val holder: ProblemsHolder) : UnitFileVisitor() { - override fun visitPropertyType(property: UnitFilePropertyType) { - val section = PsiTreeUtil.getParentOfType(property, UnitFileSectionGroups::class.java) ?: return - val value = property.valueText ?: return - val validator = SemanticDataRepository.instance - .getOptionValidator(section.containingFile.fileClass(), section.sectionName, property.key) - if (validator !is GrammarOptionValue) return + override fun message(replacement: String) = "IPv6 address is not in canonical form (RFC 5952); use '$replacement'" - for (region in validator.combinator.labeledRegions(value)) { - if (region.tag != SemanticTag.IPV6) continue // act only on spans the grammar declared IPv6 - val text = value.substring(region.start, region.end) - val canonical = canonicalizeIpv6(text) ?: continue // e.g. an IPv4-tail form, out of scope - if (canonical == text) continue - holder.registerProblem( - property.valueNode.psi, - "IPv6 address is not in canonical form (RFC 5952); use '$canonical'", - ProblemHighlightType.WEAK_WARNING, - TextRange(region.start, region.end), - CanonicalizeIpv6QuickFix(region.start, text, canonical), - ) - } - } - } + override fun quickFix(original: String, replacement: String): LocalQuickFix = CanonicalizeIpv6QuickFix(original, replacement) } diff --git a/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/inspections/MacAddressFormatInspection.kt b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/inspections/MacAddressFormatInspection.kt new file mode 100644 index 00000000..44aca66b --- /dev/null +++ b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/inspections/MacAddressFormatInspection.kt @@ -0,0 +1,33 @@ +package net.sjrx.intellij.plugins.systemdunitfiles.inspections + +import com.intellij.codeInspection.LocalQuickFix +import net.sjrx.intellij.plugins.systemdunitfiles.intentions.NormalizeMacFormatQuickFix +import net.sjrx.intellij.plugins.systemdunitfiles.intentions.SetPreferredMacFormatQuickFix +import net.sjrx.intellij.plugins.systemdunitfiles.semanticdata.optionvalues.grammar.SemanticTag +import net.sjrx.intellij.plugins.systemdunitfiles.semanticdata.optionvalues.grammar.formatMac +import net.sjrx.intellij.plugins.systemdunitfiles.semanticdata.optionvalues.grammar.macFormatOf +import net.sjrx.intellij.plugins.systemdunitfiles.settings.ExperimentalSettings +import net.sjrx.intellij.plugins.systemdunitfiles.settings.PreferredMacFormat + +/** + * Suggests rewriting a 6-byte MAC address (a span tagged [SemanticTag.MAC_ADDRESS]) to the user's + * [PreferredMacFormat], behind the grammar flag. Off when the preference is [PreferredMacFormat.LEAVE_ALONE]. + */ +class MacAddressFormatInspection : TaggedSpanRewriteInspection() { + + override val tag = SemanticTag.MAC_ADDRESS + + override fun rewriter(settings: ExperimentalSettings.State): ((String) -> String?)? { + val format = settings.preferredMacFormat + if (format == PreferredMacFormat.LEAVE_ALONE) return null + return { formatMac(it, format) } + } + + override fun message(replacement: String) = "MAC address is not in preferred format, use: '$replacement'" + + override fun quickFix(original: String, replacement: String): LocalQuickFix = NormalizeMacFormatQuickFix(original, replacement) + + // If the address is already written in one of the other formats, offer to make that the preference instead. + override fun extraQuickFixes(original: String): List = + listOfNotNull(macFormatOf(original)?.let(::SetPreferredMacFormatQuickFix)) +} diff --git a/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/inspections/TaggedSpanRewriteInspection.kt b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/inspections/TaggedSpanRewriteInspection.kt new file mode 100644 index 00000000..3b58715d --- /dev/null +++ b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/inspections/TaggedSpanRewriteInspection.kt @@ -0,0 +1,78 @@ +package net.sjrx.intellij.plugins.systemdunitfiles.inspections + +import com.intellij.codeInspection.LocalInspectionTool +import com.intellij.codeInspection.LocalQuickFix +import com.intellij.codeInspection.ProblemHighlightType +import com.intellij.codeInspection.ProblemsHolder +import com.intellij.openapi.util.TextRange +import com.intellij.psi.PsiElementVisitor +import com.intellij.psi.util.PsiTreeUtil +import net.sjrx.intellij.plugins.systemdunitfiles.UnitFileLanguage +import net.sjrx.intellij.plugins.systemdunitfiles.psi.UnitFile +import net.sjrx.intellij.plugins.systemdunitfiles.psi.UnitFilePropertyType +import net.sjrx.intellij.plugins.systemdunitfiles.psi.UnitFileSectionGroups +import net.sjrx.intellij.plugins.systemdunitfiles.psi.UnitFileVisitor +import net.sjrx.intellij.plugins.systemdunitfiles.semanticdata.SemanticDataRepository +import net.sjrx.intellij.plugins.systemdunitfiles.semanticdata.fileClass +import net.sjrx.intellij.plugins.systemdunitfiles.semanticdata.optionvalues.grammar.GrammarOptionValue +import net.sjrx.intellij.plugins.systemdunitfiles.semanticdata.optionvalues.grammar.SemanticTag +import net.sjrx.intellij.plugins.systemdunitfiles.semanticdata.optionvalues.grammar.labeledRegions +import net.sjrx.intellij.plugins.systemdunitfiles.settings.ExperimentalSettings + +/** + * Base for inspections that suggest rewriting spans the grammar tagged with [tag] (behind the grammar + * engine flag): for each such span, if [rewrite] gives a different spelling, report a weak warning with + * a quick fix. Keying off the tag means only spans the grammar *declared* are touched, never a literal + * that merely looks similar. + * + * Region offsets are in the property's valueText (lines joined and trimmed), so they're mapped back + * onto the raw value element with [valueTextOffsets] before reporting; values whose mapping fails, or + * whose mapped text doesn't match, are skipped rather than highlighted in the wrong place. + */ +abstract class TaggedSpanRewriteInspection : LocalInspectionTool() { + + protected abstract val tag: SemanticTag + + /** The rewrite to apply under the current [settings], or null to report nothing at all. */ + protected abstract fun rewriter(settings: ExperimentalSettings.State): ((String) -> String?)? + + protected abstract fun message(replacement: String): String + + protected abstract fun quickFix(original: String, replacement: String): LocalQuickFix + + /** Further fixes offered next to [quickFix] that don't rewrite the span (e.g. changing the preference). */ + protected open fun extraQuickFixes(original: String): List = emptyList() + + override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { + val file = holder.file + if (file !is UnitFile || !file.language.isKindOf(UnitFileLanguage.INSTANCE)) return PsiElementVisitor.EMPTY_VISITOR + val settings = ExperimentalSettings.getInstance(file.project).state + if (!settings.useGrammarParseEngine) return PsiElementVisitor.EMPTY_VISITOR + val rewrite = rewriter(settings) ?: return PsiElementVisitor.EMPTY_VISITOR + + return object : UnitFileVisitor() { + override fun visitPropertyType(property: UnitFilePropertyType) { + val section = PsiTreeUtil.getParentOfType(property, UnitFileSectionGroups::class.java) ?: return + val value = property.valueText ?: return + val validator = SemanticDataRepository.instance + .getOptionValidator(section.containingFile.fileClass(), section.sectionName, property.key) + if (validator !is GrammarOptionValue) return + + val regions = validator.combinator.labeledRegions(value).filter { it.tag == tag && it.start < it.end } + if (regions.isEmpty()) return + val valueElement = property.valueNode.psi + val rawText = valueElement.text + val offsets = valueTextOffsets(valueElement, value) ?: return + + for (region in regions) { + val text = value.substring(region.start, region.end) + val replacement = rewrite(text) ?: continue + if (replacement == text) continue + val range = TextRange(offsets[region.start], offsets[region.end - 1] + 1) + if (range.substring(rawText) != text) continue + holder.registerProblem(valueElement, message(replacement), ProblemHighlightType.WEAK_WARNING, range, quickFix(text, replacement), *extraQuickFixes(text).toTypedArray()) + } + } + } + } +} diff --git a/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/inspections/ValueWarningInspection.kt b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/inspections/ValueWarningInspection.kt index ec5c4b24..275fd338 100644 --- a/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/inspections/ValueWarningInspection.kt +++ b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/inspections/ValueWarningInspection.kt @@ -73,7 +73,7 @@ class ValueWarningInspection : LocalInspectionTool() { * UnitFileValueType.getValue(): each value line is trimmed (String.trim(), i.e. chars <= ' '), a trailing continuation * backslash becomes a space, and the joined result is trimmed again. Null if the reconstruction does not match [value]. */ -private fun valueTextOffsets(valueElement: PsiElement, value: String): IntArray? { +internal fun valueTextOffsets(valueElement: PsiElement, value: String): IntArray? { val text = StringBuilder() val offsets = mutableListOf() var child = valueElement.firstChild diff --git a/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/intentions/CanonicalizeIpv6QuickFix.kt b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/intentions/CanonicalizeIpv6QuickFix.kt index ad04663f..a20f2f95 100644 --- a/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/intentions/CanonicalizeIpv6QuickFix.kt +++ b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/intentions/CanonicalizeIpv6QuickFix.kt @@ -1,25 +1,11 @@ package net.sjrx.intellij.plugins.systemdunitfiles.intentions -import com.intellij.codeInspection.LocalQuickFix -import com.intellij.codeInspection.ProblemDescriptor -import com.intellij.openapi.project.Project -import com.intellij.psi.util.PsiTreeUtil -import net.sjrx.intellij.plugins.systemdunitfiles.psi.impl.UnitFilePropertyImpl - /** - * Replaces the IPv6 address at [offset] (within the option value) with its RFC 5952 [canonical] form. + * Replaces the IPv6 address [original] with its RFC 5952 [canonical] form. */ -class CanonicalizeIpv6QuickFix(private val offset: Int, private val original: String, private val canonical: String) : LocalQuickFix { - - override fun getName(): String = "Convert to canonical IPv6 '$canonical'" - - override fun getFamilyName(): String = "Convert to canonical IPv6 (RFC 5952)" - - override fun applyFix(project: Project, descriptor: ProblemDescriptor) { - val fullPropertyValue = descriptor.psiElement.text - val newText = fullPropertyValue.substring(0, offset) + canonical + fullPropertyValue.substring(offset + original.length) - val property = PsiTreeUtil.getParentOfType(descriptor.psiElement, UnitFilePropertyImpl::class.java) ?: return - val newElement = UnitElementFactory.createProperty(project, property.key, newText) - property.replace(newElement) - } -} +class CanonicalizeIpv6QuickFix(original: String, canonical: String) : ReplaceValueSpanQuickFix( + original, + canonical, + name = "Convert to canonical IPv6 '$canonical'", + family = "Convert to canonical IPv6 (RFC 5952)", +) diff --git a/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/intentions/NormalizeMacFormatQuickFix.kt b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/intentions/NormalizeMacFormatQuickFix.kt new file mode 100644 index 00000000..9913d7ca --- /dev/null +++ b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/intentions/NormalizeMacFormatQuickFix.kt @@ -0,0 +1,12 @@ +package net.sjrx.intellij.plugins.systemdunitfiles.intentions + +/** + * Rewrites a MAC address from its current spelling [original] to the user's preferred [replacement], + * e.g. `00-1A-2B-3C-4D-5E` -> `00:1a:2b:3c:4d:5e`. + */ +class NormalizeMacFormatQuickFix(original: String, replacement: String) : ReplaceValueSpanQuickFix( + original, + replacement, + name = "Convert MAC address to '$replacement'", + family = "Convert MAC address to preferred format", +) diff --git a/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/intentions/ReplaceValueSpanQuickFix.kt b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/intentions/ReplaceValueSpanQuickFix.kt new file mode 100644 index 00000000..29d9a7ba --- /dev/null +++ b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/intentions/ReplaceValueSpanQuickFix.kt @@ -0,0 +1,55 @@ +package net.sjrx.intellij.plugins.systemdunitfiles.intentions + +import com.intellij.codeInspection.LocalQuickFix +import com.intellij.codeInspection.ProblemDescriptor +import com.intellij.openapi.project.Project +import com.intellij.openapi.util.TextRange +import com.intellij.psi.PsiDocumentManager + +/** + * Replaces one span of an option value, [original], with [replacement], editing the document in place + * so the rest of the value (other entries, line continuations, indentation) is left untouched. + * + * The span is the descriptor's range within its element. A value can carry several of these fixes (e.g. + * a list of MAC addresses), and applying one shifts the text after it, so the recorded range can be + * stale by the time a later fix runs ("Fix all"). The fix therefore only edits when the range still + * holds [original]; failing that, it falls back to a single whole-token occurrence of [original]. If + * neither holds it does nothing rather than corrupt the value. + */ +open class ReplaceValueSpanQuickFix( + private val original: String, + private val replacement: String, + private val name: String, + private val family: String, +) : LocalQuickFix { + + override fun getName(): String = name + + override fun getFamilyName(): String = family + + override fun applyFix(project: Project, descriptor: ProblemDescriptor) { + val element = descriptor.psiElement ?: return + if (!element.isValid) return + val start = locate(element.text, descriptor.textRangeInElement) ?: return + val documentManager = PsiDocumentManager.getInstance(project) + val document = documentManager.getDocument(element.containingFile) ?: return + val absoluteStart = element.textRange.startOffset + start + document.replaceString(absoluteStart, absoluteStart + original.length, replacement) + documentManager.commitDocument(document) + } + + private fun locate(text: String, range: TextRange?): Int? { + if (range != null && range.endOffset <= text.length && range.substring(text) == original) { + return range.startOffset + } + val matches = generateSequence(text.indexOf(original).takeIf { it >= 0 }) { previous -> + text.indexOf(original, previous + 1).takeIf { it >= 0 } + }.filter { isWholeToken(text, it) }.take(2).toList() + return matches.singleOrNull() + } + + private fun isWholeToken(text: String, start: Int): Boolean { + val end = start + original.length + return (start == 0 || text[start - 1].isWhitespace()) && (end == text.length || text[end].isWhitespace()) + } +} diff --git a/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/intentions/SetPreferredMacFormatQuickFix.kt b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/intentions/SetPreferredMacFormatQuickFix.kt new file mode 100644 index 00000000..5d13ea19 --- /dev/null +++ b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/intentions/SetPreferredMacFormatQuickFix.kt @@ -0,0 +1,31 @@ +package net.sjrx.intellij.plugins.systemdunitfiles.intentions + +import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer +import com.intellij.codeInsight.intention.preview.IntentionPreviewInfo +import com.intellij.codeInspection.LocalQuickFix +import com.intellij.codeInspection.ProblemDescriptor +import com.intellij.openapi.project.Project +import net.sjrx.intellij.plugins.systemdunitfiles.settings.ExperimentalSettings +import net.sjrx.intellij.plugins.systemdunitfiles.settings.PreferredMacFormat + +/** + * Keeps the MAC address as written and makes its [format] the preferred one instead, so the file stops + * being flagged. Changes the project setting only; the file is not edited. + */ +class SetPreferredMacFormatQuickFix(private val format: PreferredMacFormat) : LocalQuickFix { + + override fun getName(): String = "Set preferred MAC address format to ${format.displayName}" + + override fun getFamilyName(): String = "Set preferred MAC address format" + + override fun startInWriteAction(): Boolean = false + + // The default preview would run applyFix, which changes the real setting. + override fun generatePreview(project: Project, previewDescriptor: ProblemDescriptor): IntentionPreviewInfo = + IntentionPreviewInfo.Html("Changes Settings | Tools | systemd Unit Files | Preferred MAC address format to ${format.displayName}.") + + override fun applyFix(project: Project, descriptor: ProblemDescriptor) { + ExperimentalSettings.getInstance(project).state.preferredMacFormat = format + DaemonCodeAnalyzer.getInstance(project).restart() + } +} diff --git a/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/semanticdata/optionvalues/ai/ConfigParseAdActorSystemOptionValue.kt b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/semanticdata/optionvalues/ai/ConfigParseAdActorSystemOptionValue.kt index 515e5577..cd885a81 100644 --- a/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/semanticdata/optionvalues/ai/ConfigParseAdActorSystemOptionValue.kt +++ b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/semanticdata/optionvalues/ai/ConfigParseAdActorSystemOptionValue.kt @@ -11,21 +11,6 @@ import net.sjrx.intellij.plugins.systemdunitfiles.semanticdata.optionvalues.Simp * leaf https://github.com/systemd/systemd/blob/0f0682b773/src/basic/ether-addr-util.c#L196-L280 parse_hw_addr_full (via parse_ether_addr) */ -/** - * The six bytes of a [MAC_ADDRESS] spelling: colon- or hyphen-separated 1-byte fields, or three - * dot-separated 2-byte fields (`0223.4567.89ab`, where a short field such as `123` is 0x0123). - */ -private fun macAddressBytes(text: String): IntArray? { - val bytes = when { - '.' in text -> text.split('.').flatMap { word -> - val v = word.toIntOrNull(16) ?: return null - listOf(v shr 8, v and 0xFF) - } - else -> text.split(':', '-').map { it.toIntOrNull(16) ?: return null } - } - return if (bytes.size == 6) bytes.toIntArray() else null -} - /** * Validator for [Bond] AdActorSystem= (.netdev). * diff --git a/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/semanticdata/optionvalues/ai/ConfigParseWolPasswordOptionValue.kt b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/semanticdata/optionvalues/ai/ConfigParseWolPasswordOptionValue.kt index 761800da..02043205 100644 --- a/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/semanticdata/optionvalues/ai/ConfigParseWolPasswordOptionValue.kt +++ b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/semanticdata/optionvalues/ai/ConfigParseWolPasswordOptionValue.kt @@ -3,7 +3,7 @@ package net.sjrx.intellij.plugins.systemdunitfiles.semanticdata.optionvalues.ai import net.sjrx.intellij.plugins.systemdunitfiles.semanticdata.optionvalues.SimpleGrammarOptionValues import net.sjrx.intellij.plugins.systemdunitfiles.semanticdata.optionvalues.grammar.AlternativeCombinator import net.sjrx.intellij.plugins.systemdunitfiles.semanticdata.optionvalues.grammar.EOF -import net.sjrx.intellij.plugins.systemdunitfiles.semanticdata.optionvalues.grammar.MAC_ADDRESS +import net.sjrx.intellij.plugins.systemdunitfiles.semanticdata.optionvalues.grammar.SECUREON_PASSWORD import net.sjrx.intellij.plugins.systemdunitfiles.semanticdata.optionvalues.grammar.SAFE_ABSOLUTE_PATH import net.sjrx.intellij.plugins.systemdunitfiles.semanticdata.optionvalues.grammar.SequenceCombinator @@ -29,7 +29,7 @@ import net.sjrx.intellij.plugins.systemdunitfiles.semanticdata.optionvalues.gram class ConfigParseWolPasswordOptionValue : SimpleGrammarOptionValues( "config_parse_wol_password", AlternativeCombinator( - SequenceCombinator(MAC_ADDRESS, EOF()), + SequenceCombinator(SECUREON_PASSWORD, EOF()), SequenceCombinator(SAFE_ABSOLUTE_PATH, EOF()), ) ) diff --git a/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/semanticdata/optionvalues/grammar/Combinators.kt b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/semanticdata/optionvalues/grammar/Combinators.kt index 97c605e1..583e58fb 100644 --- a/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/semanticdata/optionvalues/grammar/Combinators.kt +++ b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/semanticdata/optionvalues/grammar/Combinators.kt @@ -204,34 +204,74 @@ private val HW_ADDR_WORD = RegexTerminal("[0-9a-fA-F]{1,4}", "[0-9a-fA-F]{1,4}") private fun hwAddrGroups(group: Combinator, sep: Combinator, count: Int): Combinator = SequenceCombinator(group, Repeat(SequenceCombinator(sep, group), count - 1, count - 1)) -// A 6-byte Ethernet MAC address, i.e. systemd parse_ether_addr (expected_len == ETH_ALEN). Used by -// SR-IOV=, BridgeFDB=, DHCPServerStaticLease=, MACsec*=, NetDev/Peer= and MACVLAN/MACVTAP source. -val MAC_ADDRESS = Labeled(Role.LITERAL, AlternativeCombinator( +// Hardware-address families, by byte length. Each accepts all three separator styles: colon and +// hyphen with 1-byte fields (N groups), dot with 2-byte fields (N/2 groups). Each family is Labeled +// exactly once, as a single literal span, so nothing that assembles them below adds another wrapper. +// Only the 6-byte family carries SemanticTag.MAC_ADDRESS. + +// 4 bytes: IPv4 tunnels (IPIP, GRE, SIT). The "hardware address" is the tunnel endpoint's IPv4 address. +private val IPV4_TUNNEL_HW_ADDR = Labeled(Role.LITERAL, AlternativeCombinator( + hwAddrGroups(HW_ADDR_BYTE, COLON, 4), + hwAddrGroups(HW_ADDR_BYTE, HYPHEN, 4), + hwAddrGroups(HW_ADDR_WORD, DOT, 2), +)) + +// 6 bytes, in parse_ether_addr's three spellings. Unlabeled: wrapped below as either a MAC or a password. +private val SIX_BYTE_HW_ADDR_FORMS = AlternativeCombinator( hwAddrGroups(HW_ADDR_BYTE, COLON, 6), hwAddrGroups(HW_ADDR_BYTE, HYPHEN, 6), hwAddrGroups(HW_ADDR_WORD, DOT, 3), +) + +// 6 bytes: an Ethernet MAC (Wi-Fi, wired NICs, bridges, VLANs, ...). +private val ETHERNET_HW_ADDR = Labeled(Role.LITERAL, SIX_BYTE_HW_ADDR_FORMS, SemanticTag.MAC_ADDRESS) + +// [Link] WakeOnLanPassword=: a 6-byte SecureOn password spelled like a MAC (systemd parses it with +// parse_ether_addr), but not an address, so it is deliberately NOT tagged SemanticTag.MAC_ADDRESS. +val SECUREON_PASSWORD = Labeled(Role.LITERAL, SIX_BYTE_HW_ADDR_FORMS) + +// 16 bytes: IPv6 tunnels (ip6tnl, ip6gre). The tunnel endpoint's IPv6 address. +private val IPV6_TUNNEL_HW_ADDR = Labeled(Role.LITERAL, AlternativeCombinator( + hwAddrGroups(HW_ADDR_BYTE, COLON, 16), + hwAddrGroups(HW_ADDR_BYTE, HYPHEN, 16), + hwAddrGroups(HW_ADDR_WORD, DOT, 8), )) -// The raw hex forms of a hardware address (colon/hyphen use 1-byte fields → 4/6/16/20 groups; dot uses -// 2-byte fields → 2/3/8/10 groups). Longest group counts come first so the classic (first-full-match) -// matcher never stops on a shorter prefix. Wrapped once so the whole address reads as a single literal -// span rather than per-field. -private val RAW_HARDWARE_ADDRESS = Labeled(Role.LITERAL, AlternativeCombinator( - hwAddrGroups(HW_ADDR_BYTE, COLON, 20), hwAddrGroups(HW_ADDR_BYTE, COLON, 16), hwAddrGroups(HW_ADDR_BYTE, COLON, 6), hwAddrGroups(HW_ADDR_BYTE, COLON, 4), - hwAddrGroups(HW_ADDR_BYTE, HYPHEN, 20), hwAddrGroups(HW_ADDR_BYTE, HYPHEN, 16), hwAddrGroups(HW_ADDR_BYTE, HYPHEN, 6), hwAddrGroups(HW_ADDR_BYTE, HYPHEN, 4), - hwAddrGroups(HW_ADDR_WORD, DOT, 10), hwAddrGroups(HW_ADDR_WORD, DOT, 8), hwAddrGroups(HW_ADDR_WORD, DOT, 3), hwAddrGroups(HW_ADDR_WORD, DOT, 2), +// 20 bytes: InfiniBand (4-byte queue-pair number + 16-byte GID). +private val INFINIBAND_HW_ADDR = Labeled(Role.LITERAL, AlternativeCombinator( + hwAddrGroups(HW_ADDR_BYTE, COLON, 20), + hwAddrGroups(HW_ADDR_BYTE, HYPHEN, 20), + hwAddrGroups(HW_ADDR_WORD, DOT, 10), )) +// A 6-byte Ethernet MAC address, i.e. systemd parse_ether_addr (expected_len == ETH_ALEN). Used by +// SR-IOV=, BridgeFDB=, DHCPServerStaticLease=, MACsec*=, NetDev/Peer= and MACVLAN/MACVTAP source. +// Already Labeled and tagged SemanticTag.MAC_ADDRESS (above), so MacAddressFormatInspection can find it. +val MAC_ADDRESS: Combinator = ETHERNET_HW_ADDR + // A hardware address as accepted by parse_hw_addr_full with expected_len == 0 (Match=, Link=, // Neighbor.LinkLayerAddress=). Besides 6-byte MACs it accepts 4-, 16- and 20-byte (Infiniband) -// hardware addresses, and — because the parser first tries in_addr_from_string — plain IPv4 and IPv6 -// address literals. IPV4_ADDR / IPV6_ADDR are already Labeled (IPv6 also carries SemanticTag.IPV6), so -// they sit alongside the wrapped raw forms rather than inside a second wrapper — a whole-alternation -// Labeled would emit a redundant second literal region over an IP literal's span. +// hardware addresses, and (because the parser first tries in_addr_from_string) plain IPv4 and IPv6 +// address literals. Every alternative is already Labeled exactly once (IPv6 carries SemanticTag.IPV6, +// the 6-byte family SemanticTag.MAC_ADDRESS), so nothing here adds another wrapper. +// +// ORDER MATTERS for the classic matcher (SyntacticMatch): it takes the first alternative that matches a +// *prefix* and never backtracks, so an alternative must not come before one whose values it can be a +// prefix of. Hence: +// - 20- and 16-byte families before IPV6_ADDR: the first 8 colon fields of `01:02:...:10` are a valid +// IPv6 address, which would otherwise win and leave the rest unmatched; +// - IPV6_ADDR / IPV4_ADDR before the 6- and 4-byte families: `1:2:3:4:5:6:7:8` starts with a valid MAC, +// and `192.168.1.1` with a valid 2-word dot address; +// - longer families before shorter ones (the 4-byte colon branch would eat the start of a MAC). +// The new parse() engine tries every alternative, so it doesn't care. MacAddressGrammarTest covers each +// length in each separator style with the classic engine. val HARDWARE_ADDRESS = AlternativeCombinator( + INFINIBAND_HW_ADDR, + IPV6_TUNNEL_HW_ADDR, IPV6_ADDR, IPV4_ADDR, - RAW_HARDWARE_ADDRESS, + ETHERNET_HW_ADDR, + IPV4_TUNNEL_HW_ADDR, ) diff --git a/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/semanticdata/optionvalues/grammar/MacAddress.kt b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/semanticdata/optionvalues/grammar/MacAddress.kt new file mode 100644 index 00000000..91e18501 --- /dev/null +++ b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/semanticdata/optionvalues/grammar/MacAddress.kt @@ -0,0 +1,58 @@ +package net.sjrx.intellij.plugins.systemdunitfiles.semanticdata.optionvalues.grammar + +import net.sjrx.intellij.plugins.systemdunitfiles.settings.PreferredMacFormat + +/* + * 6-byte MAC address parsing and re-formatting. The sibling of Ipv6.kt: parse the address to its raw + * bytes, then print those bytes in the requested style. + * + * Accepted spellings (systemd parse_ether_addr, as matched by the MAC_ADDRESS grammar in Combinators.kt): + * colon: 1:2:3:a:B:cc six fields of 1-2 hex digits + * hyphen: 01-02-03-0A-0B-CC six fields of 1-2 hex digits + * dot: 102.30a.bcc three fields of 1-4 hex digits, each one 16-bit word (2 bytes) + * Short fields are zero-padded on the left, so the colon example is 01:02:03:0a:0b:cc. + */ + +private val COLON_MAC = Regex("([0-9a-fA-F]{1,2}:){5}[0-9a-fA-F]{1,2}") +private val HYPHEN_MAC = Regex("([0-9a-fA-F]{1,2}-){5}[0-9a-fA-F]{1,2}") +private val DOT_MAC = Regex("([0-9a-fA-F]{1,4}\\.){2}[0-9a-fA-F]{1,4}") + +/** + * The six bytes of a MAC address in any accepted spelling, or `null` if [text] isn't one (wrong field + * count or width, non-hex digits, mixed separators). + */ +fun macAddressBytes(text: String): IntArray? { + val bytes = when { + COLON_MAC.matches(text) -> text.split(':').map { it.toInt(16) } + HYPHEN_MAC.matches(text) -> text.split('-').map { it.toInt(16) } + DOT_MAC.matches(text) -> text.split('.').flatMap { + val word = it.toInt(16) + listOf(word shr 8, word and 0xFF) + } + else -> return null + } + return bytes.toIntArray() +} + +/** + * Returns [address] rewritten in [format], or `null` when there's nothing to suggest: + * [PreferredMacFormat.LEAVE_ALONE], or [address] isn't a parseable 6-byte MAC. + * + * The result is compared with the original text, and the inspection fires only when they differ, so + * an address already in [format] comes back unchanged (same case, same zero padding). + */ +/** The format [address] is written in exactly, or null if it matches none (e.g. mixed case). */ +fun macFormatOf(address: String): PreferredMacFormat? = + PreferredMacFormat.entries.firstOrNull { it != PreferredMacFormat.LEAVE_ALONE && formatMac(address, it) == address } + +fun formatMac(address: String, format: PreferredMacFormat): String? { + if (format == PreferredMacFormat.LEAVE_ALONE) return null + val bytes = macAddressBytes(address) ?: return null + return when (format) { + PreferredMacFormat.LEAVE_ALONE -> null + PreferredMacFormat.COLON_LOWER -> bytes.joinToString(":") { "%02x".format(it) } + PreferredMacFormat.COLON_UPPER -> bytes.joinToString(":") { "%02X".format(it) } + PreferredMacFormat.HYPHEN_UPPER -> bytes.joinToString("-") { "%02X".format(it) } + PreferredMacFormat.DOT_LOWER -> bytes.toList().chunked(2).joinToString(".") { (high, low) -> "%02x%02x".format(high, low) } + } +} diff --git a/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/semanticdata/optionvalues/grammar/SemanticTag.kt b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/semanticdata/optionvalues/grammar/SemanticTag.kt index cd04a7fd..225aea17 100644 --- a/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/semanticdata/optionvalues/grammar/SemanticTag.kt +++ b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/semanticdata/optionvalues/grammar/SemanticTag.kt @@ -5,10 +5,13 @@ package net.sjrx.intellij.plugins.systemdunitfiles.semanticdata.optionvalues.gra * * Where [Role] answers "what colour?", a tag answers "what *is* this span?". It lets a feature act on * a span because the grammar *declared* what it is, rather than re-sniffing the raw text and hoping no - * other labeled span happens to look the same. Currently only IPv6 canonicalization keys off it (see - * Ipv6CanonicalFormInspection); add members as other features need structural identity. + * other labeled span happens to look the same. IPv6 canonicalization (Ipv6CanonicalFormInspection) and MAC + * formatting (MacAddressFormatInspection) key off it; add members as other features need structural identity. */ enum class SemanticTag { /** A whole IPv6 address (possibly with an IPv4 tail), as matched by `IPV6_ADDR`. */ IPV6, + + /** A 6-byte Ethernet MAC in any separator style systemd accepts, as matched by `MAC_ADDRESS`. */ + MAC_ADDRESS, } diff --git a/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/settings/ExperimentalSettings.kt b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/settings/ExperimentalSettings.kt index d01b40b1..3faaa4f4 100644 --- a/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/settings/ExperimentalSettings.kt +++ b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/settings/ExperimentalSettings.kt @@ -46,6 +46,12 @@ class ExperimentalSettings : PersistentStateComponent? = null override fun getDisplayName(): String = "systemd Unit Files" @@ -27,11 +30,15 @@ class PodmanQuadletConfigurable(private val project: Project) : Configurable { "Underline keys backed by the new grammar engine (experimental)", experimental.state.underlineGrammarEngineKeys, ) + macFormatCombo = ComboBox(PreferredMacFormat.entries.toTypedArray()).apply { + selectedItem = experimental.state.preferredMacFormat + } return FormBuilder.createFormBuilder() .addComponent(enabledCheckbox!!) .addComponent(grammarEngineCheckbox!!) .addComponent(underlineGrammarKeysCheckbox!!) + .addLabeledComponent("Preferred MAC address format:", macFormatCombo!!) .addComponentFillVertically(JPanel(), 0) .panel } @@ -41,7 +48,8 @@ class PodmanQuadletConfigurable(private val project: Project) : Configurable { val experimental = ExperimentalSettings.getInstance(project) return enabledCheckbox?.isSelected != settings.state.enabled || grammarEngineCheckbox?.isSelected != experimental.state.useGrammarParseEngine || - underlineGrammarKeysCheckbox?.isSelected != experimental.state.underlineGrammarEngineKeys + underlineGrammarKeysCheckbox?.isSelected != experimental.state.underlineGrammarEngineKeys || + selectedMacFormat() != experimental.state.preferredMacFormat } override fun apply() { @@ -52,9 +60,18 @@ class PodmanQuadletConfigurable(private val project: Project) : Configurable { } settings.state.enabled = newEnabled - val experimental = ExperimentalSettings.getInstance(project) - experimental.state.useGrammarParseEngine = grammarEngineCheckbox?.isSelected ?: false - experimental.state.underlineGrammarEngineKeys = underlineGrammarKeysCheckbox?.isSelected ?: false + val experimental = ExperimentalSettings.getInstance(project).state + val newGrammarEngine = grammarEngineCheckbox?.isSelected ?: false + val newUnderlineKeys = underlineGrammarKeysCheckbox?.isSelected ?: false + val newMacFormat = selectedMacFormat() + val changed = experimental.useGrammarParseEngine != newGrammarEngine || + experimental.underlineGrammarEngineKeys != newUnderlineKeys || + experimental.preferredMacFormat != newMacFormat + experimental.useGrammarParseEngine = newGrammarEngine + experimental.underlineGrammarEngineKeys = newUnderlineKeys + experimental.preferredMacFormat = newMacFormat + // Inspections and annotators read these when they build their visitors, so re-run them on open files. + if (changed) DaemonCodeAnalyzer.getInstance(project).restart() } override fun reset() { @@ -63,5 +80,9 @@ class PodmanQuadletConfigurable(private val project: Project) : Configurable { enabledCheckbox?.isSelected = settings.state.enabled grammarEngineCheckbox?.isSelected = experimental.state.useGrammarParseEngine underlineGrammarKeysCheckbox?.isSelected = experimental.state.underlineGrammarEngineKeys + macFormatCombo?.selectedItem = experimental.state.preferredMacFormat } + + private fun selectedMacFormat(): PreferredMacFormat = + macFormatCombo?.selectedItem as? PreferredMacFormat ?: PreferredMacFormat.COLON_LOWER } diff --git a/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/settings/PreferredMacFormat.kt b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/settings/PreferredMacFormat.kt new file mode 100644 index 00000000..dab32ffe --- /dev/null +++ b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/settings/PreferredMacFormat.kt @@ -0,0 +1,22 @@ +package net.sjrx.intellij.plugins.systemdunitfiles.settings + +/** + * Which spelling the user prefers for 6-byte MAC addresses. Drives + * [net.sjrx.intellij.plugins.systemdunitfiles.inspections.MacAddressFormatInspection], which suggests + * rewriting any MAC not already in this form. + * + * systemd's `parse_ether_addr()` accepts colon, hyphen and dot (Cisco) separators in any case, with + * leading zeros optional per field. The default is [COLON_LOWER], the form systemd itself prints + * (`ether_addr_to_string()`). [LEAVE_ALONE] disables the suggestion entirely. + */ +enum class PreferredMacFormat(val displayName: String) { + LEAVE_ALONE("Leave as written (no suggestions)"), + COLON_LOWER("00:1a:2b:3c:4d:5e (systemd default)"), + COLON_UPPER("00:1A:2B:3C:4D:5E"), + HYPHEN_UPPER("00-1A-2B-3C-4D-5E (Windows style)"), + DOT_LOWER("001a.2b3c.4d5e (Cisco style)"), + ; + + // Shown as-is in the settings combo box. + override fun toString(): String = displayName +} diff --git a/src/main/resources/META-INF/plugin.xml b/src/main/resources/META-INF/plugin.xml index 594c859a..c3e73b5d 100644 --- a/src/main/resources/META-INF/plugin.xml +++ b/src/main/resources/META-INF/plugin.xml @@ -90,6 +90,10 @@ groupPath="Unit files (systemd)" language="Unit File (systemd)" shortName="Ipv6CanonicalForm" displayName="IPv6 address not in canonical form (RFC 5952)" groupName="Style" enabledByDefault="true" level="WEAK WARNING"/> + + +

+ Suggests rewriting a MAC address in the format chosen under Settings | Tools | systemd Unit Files. +

+ +

systemd accepts a MAC address written several ways, for example 00:1a:2b:3c:4d:5e, +00-1A-2B-3C-4D-5E and 001a.2b3c.4d5e. This inspection flags any MAC address not +written in the preferred format and offers to convert it. If the address is already written in one of the other +formats, it also offers to make that format the preferred one.

+

Set the preferred format to Leave as written to turn the suggestions off. Other hardware addresses, such as +Infiniband addresses in [Match] sections, are left alone.

+

This inspection needs the new grammar engine, which you turn on under Settings | Tools | systemd Unit Files.

+ + diff --git a/src/test/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/inspections/MacAddressFormatInspectionTest.kt b/src/test/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/inspections/MacAddressFormatInspectionTest.kt new file mode 100644 index 00000000..0453e1f6 --- /dev/null +++ b/src/test/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/inspections/MacAddressFormatInspectionTest.kt @@ -0,0 +1,204 @@ +package net.sjrx.intellij.plugins.systemdunitfiles.inspections + +import com.intellij.lang.annotation.HighlightSeverity +import net.sjrx.intellij.plugins.systemdunitfiles.AbstractUnitFileTest +import net.sjrx.intellij.plugins.systemdunitfiles.settings.ExperimentalSettings +import net.sjrx.intellij.plugins.systemdunitfiles.settings.PreferredMacFormat +import org.junit.Test + +/** + * End-to-end: a MAC address not in the preferred format is flagged and the quick fix rewrites it + * (flag-gated, and off when the preference is LEAVE_ALONE). + * + * Expects the problem description to contain "preferred format" and the quick fix name to start with + * "Convert MAC address to". + */ +class MacAddressFormatInspectionTest : AbstractUnitFileTest() { + + override fun tearDown() { + try { + val state = ExperimentalSettings.getInstance(project).state + state.useGrammarParseEngine = false + state.preferredMacFormat = PreferredMacFormat.COLON_LOWER + } finally { + super.tearDown() + } + } + + private fun configure(format: PreferredMacFormat = PreferredMacFormat.COLON_LOWER, engine: Boolean = true) { + val state = ExperimentalSettings.getInstance(project).state + state.useGrammarParseEngine = engine + state.preferredMacFormat = format + } + + private fun hasFormatWarning() = myFixture.doHighlighting().any { + it.severity == HighlightSeverity.WEAK_WARNING && it.description?.contains("preferred format") == true + } + + @Test + fun testNonPreferredIsFlagged() { + configure() + setupFileInEditor("f.link", "[SR-IOV]\nMACAddress=00-1A-2B-3C-4D-5E\n") + enableInspection(MacAddressFormatInspection::class.java) + assertTrue(hasFormatWarning()) + } + + @Test + fun testAlreadyPreferredIsNotFlagged() { + configure() + setupFileInEditor("f.link", "[SR-IOV]\nMACAddress=00:1a:2b:3c:4d:5e\n") + enableInspection(MacAddressFormatInspection::class.java) + assertFalse(hasFormatWarning()) + } + + @Test + fun testOtherPreferenceFlagsSystemdDefault() { + configure(PreferredMacFormat.DOT_LOWER) + setupFileInEditor("f.link", "[SR-IOV]\nMACAddress=00:1a:2b:3c:4d:5e\n") + enableInspection(MacAddressFormatInspection::class.java) + assertTrue(hasFormatWarning()) + } + + @Test + fun testNotFlaggedWhenLeaveAlone() { + configure(PreferredMacFormat.LEAVE_ALONE) + setupFileInEditor("f.link", "[SR-IOV]\nMACAddress=00-1A-2B-3C-4D-5E\n") + enableInspection(MacAddressFormatInspection::class.java) + assertFalse(hasFormatWarning()) + } + + @Test + fun testNotFlaggedWhenEngineOff() { + configure(engine = false) + setupFileInEditor("f.link", "[SR-IOV]\nMACAddress=00-1A-2B-3C-4D-5E\n") + enableInspection(MacAddressFormatInspection::class.java) + assertFalse(hasFormatWarning()) + } + + // --- Hardware-address fields (Match=, Link=): 6-byte MACs are flagged, other lengths and IPs are not. + + @Test + fun testMacInHardwareAddressFieldIsFlagged() { + configure() + setupFileInEditor("f.network", "[Match]\nMACAddress=00-1A-2B-3C-4D-5E\n") + enableInspection(MacAddressFormatInspection::class.java) + assertTrue(hasFormatWarning()) + } + + @Test + fun testNonMacHardwareAddressesAreNotFlagged() { + configure() + // 4-byte and 20-byte (Infiniband) raw addresses, plus an IPv6 literal: none is a 6-byte MAC. + setupFileInEditor( + "f.network", + "[Match]\nMACAddress=01-02-03-04 " + + "00-01-02-03-04-05-06-07-08-09-0A-0B-0C-0D-0E-0F-10-11-12-13 2001:db8::1\n", + ) + enableInspection(MacAddressFormatInspection::class.java) + assertFalse(hasFormatWarning()) + } + + @Test + fun testQuickFixRewritesMacWithinHardwareAddressList() { + configure() + setupFileInEditor("f.network", "[Match]\nMACAddress=2001:db8::1 00-1A-${COMPLETION_POSITION}2B-3C-4D-5E\n") + enableInspection(MacAddressFormatInspection::class.java) + myFixture.doHighlighting() + + myFixture.launchAction(myFixture.findSingleIntention("Convert MAC address to")) + myFixture.checkResult("[Match]\nMACAddress=2001:db8::1 00:1a:2b:3c:4d:5e\n") + } + + @Test + fun testQuickFixRewritesToPreferred() { + configure() + setupFileInEditor("f.link", "[SR-IOV]\nMACAddress=00-1A-${COMPLETION_POSITION}2B-3C-4D-5E\n") + enableInspection(MacAddressFormatInspection::class.java) + myFixture.doHighlighting() + + myFixture.launchAction(myFixture.findSingleIntention("Convert MAC address to")) + myFixture.checkResult("[SR-IOV]\nMACAddress=00:1a:2b:3c:4d:5e\n") + } + + @Test + fun testQuickFixRewritesOnlyTheTargetInAList() { + // Offset handling: SourceMACAddress= is a whitespace-separated MAC list; only the second entry + // (where the caret is) should be rewritten. + configure() + setupFileInEditor( + "f.netdev", + "[MACVLAN]\nSourceMACAddress=00:11:22:33:44:55 AA-BB-${COMPLETION_POSITION}CC-DD-EE-FF\n", + ) + enableInspection(MacAddressFormatInspection::class.java) + myFixture.doHighlighting() + + myFixture.launchAction(myFixture.findSingleIntention("Convert MAC address to")) + myFixture.checkResult("[MACVLAN]\nSourceMACAddress=00:11:22:33:44:55 aa:bb:cc:dd:ee:ff\n") + } + + // --- Regressions from the PR #576 review. + + @Test + fun testFixAllRewritesEveryMacInAList() { + // Each fix lengthens the value, so later fixes in the same value must not use stale offsets. + configure() + setupFileInEditor("f.netdev", "[MACVLAN]\nSourceMACAddress=1-2-3-4-5-${COMPLETION_POSITION}6 A-B-C-D-E-F 00:11:22:33:44:55\n") + enableInspection(MacAddressFormatInspection::class.java) + myFixture.doHighlighting() + + myFixture.launchAction(myFixture.findSingleIntention("Fix all 'MAC address not in preferred format' problems in file")) + myFixture.checkResult("[MACVLAN]\nSourceMACAddress=01:02:03:04:05:06 0a:0b:0c:0d:0e:0f 00:11:22:33:44:55\n") + } + + @Test + fun testQuickFixOnContinuationLineKeepsLayout() { + // valueText joins the lines, so its offsets must be mapped back onto the raw text. + configure() + setupFileInEditor( + "f.netdev", + "[MACVLAN]\nSourceMACAddress=00:11:22:33:44:55 \\\n AA-BB-${COMPLETION_POSITION}CC-DD-EE-FF\n", + ) + enableInspection(MacAddressFormatInspection::class.java) + myFixture.doHighlighting() + + myFixture.launchAction(myFixture.findSingleIntention("Convert MAC address to")) + myFixture.checkResult("[MACVLAN]\nSourceMACAddress=00:11:22:33:44:55 \\\n aa:bb:cc:dd:ee:ff\n") + } + + @Test + fun testWakeOnLanPasswordIsNotTreatedAsAMac() { + // A SecureOn password is spelled like a MAC but isn't an address. + configure() + setupFileInEditor("f.link", "[Link]\nWakeOnLanPassword=00-11-22-33-44-55\n") + enableInspection(MacAddressFormatInspection::class.java) + assertFalse(hasFormatWarning()) + } + + // --- "Set preferred MAC address format": keep the address, adopt its format as the preference. + + @Test + fun testPreferenceFixAdoptsTheWrittenFormatWithoutEditingTheFile() { + configure() + val text = "[SR-IOV]\nMACAddress=00-1A-${COMPLETION_POSITION}2B-3C-4D-5E\n" + setupFileInEditor("f.link", text) + enableInspection(MacAddressFormatInspection::class.java) + myFixture.doHighlighting() + + myFixture.launchAction(myFixture.findSingleIntention("Set preferred MAC address format to")) + assertEquals(PreferredMacFormat.HYPHEN_UPPER, ExperimentalSettings.getInstance(project).state.preferredMacFormat) + myFixture.checkResult("[SR-IOV]\nMACAddress=00-1A-2B-3C-4D-5E\n") + assertFalse(hasFormatWarning()) + } + + @Test + fun testNoPreferenceFixWhenTheWrittenFormatIsNotOneOfTheChoices() { + // Mixed case matches none of the formats on offer, so only the rewrite is offered. + configure() + setupFileInEditor("f.link", "[SR-IOV]\nMACAddress=00-1a-${COMPLETION_POSITION}2B-3c-4D-5e\n") + enableInspection(MacAddressFormatInspection::class.java) + myFixture.doHighlighting() + + assertTrue(myFixture.availableIntentions.none { it.text.startsWith("Set preferred MAC address format") }) + assertNotNull(myFixture.findSingleIntention("Convert MAC address to")) + } +} diff --git a/src/test/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/semanticdata/optionvalues/grammar/MacAddressFormatTest.kt b/src/test/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/semanticdata/optionvalues/grammar/MacAddressFormatTest.kt new file mode 100644 index 00000000..f33933d9 --- /dev/null +++ b/src/test/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/semanticdata/optionvalues/grammar/MacAddressFormatTest.kt @@ -0,0 +1,66 @@ +package net.sjrx.intellij.plugins.systemdunitfiles.semanticdata.optionvalues.grammar + +import net.sjrx.intellij.plugins.systemdunitfiles.settings.PreferredMacFormat +import net.sjrx.intellij.plugins.systemdunitfiles.settings.PreferredMacFormat.COLON_LOWER +import net.sjrx.intellij.plugins.systemdunitfiles.settings.PreferredMacFormat.COLON_UPPER +import net.sjrx.intellij.plugins.systemdunitfiles.settings.PreferredMacFormat.DOT_LOWER +import net.sjrx.intellij.plugins.systemdunitfiles.settings.PreferredMacFormat.HYPHEN_UPPER +import net.sjrx.intellij.plugins.systemdunitfiles.settings.PreferredMacFormat.LEAVE_ALONE +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +/** Unit tests for [formatMac]. */ +class MacAddressFormatTest { + + private val inputs = listOf( + "00:1a:2b:3c:4d:5e", + "00:1A:2B:3C:4D:5E", + "00-1a-2b-3c-4d-5e", + "00-1A-2B-3C-4D-5E", + "001a.2b3c.4d5e", + "001A.2B3C.4D5E", + ) + + @Test + fun testEveryInputStyleConvertsToEveryFormat() { + for (input in inputs) { + assertEquals(input, "00:1a:2b:3c:4d:5e", formatMac(input, COLON_LOWER)) + assertEquals(input, "00:1A:2B:3C:4D:5E", formatMac(input, COLON_UPPER)) + assertEquals(input, "00-1A-2B-3C-4D-5E", formatMac(input, HYPHEN_UPPER)) + assertEquals(input, "001a.2b3c.4d5e", formatMac(input, DOT_LOWER)) + } + } + + @Test + fun testShortFieldsAreZeroPadded() { + assertEquals("01:02:03:0a:0b:cc", formatMac("1:2:3:a:B:cc", COLON_LOWER)) + assertEquals("01-02-03-0A-0B-CC", formatMac("1-2-3-a-b-cc", HYPHEN_UPPER)) + // Dot fields are 16-bit words: "102" is 0x0102 -> bytes 01, 02. + assertEquals("01:02:03:0a:0b:cc", formatMac("102.30a.bcc", COLON_LOWER)) + assertEquals("0102.030a.0bcc", formatMac("1:2:3:a:b:cc", DOT_LOWER)) + } + + @Test + fun testAlreadyPreferredIsUnchanged() { + for (format in PreferredMacFormat.entries - LEAVE_ALONE) { + val preferred = formatMac("00:1a:2b:3c:4d:5e", format)!! + assertEquals(format.name, preferred, formatMac(preferred, format)) + } + } + + @Test + fun testLeaveAloneReturnsNull() { + assertNull(formatMac("00-1A-2B-3C-4D-5E", LEAVE_ALONE)) + } + + @Test + fun testUnparseableReturnsNull() { + assertNull(formatMac("", COLON_LOWER)) + assertNull(formatMac("00:11:22:33:44", COLON_LOWER)) // too few fields + assertNull(formatMac("00:11:22:33:44:55:66", COLON_LOWER)) // too many + assertNull(formatMac("00:11-22:33:44:55", COLON_LOWER)) // mixed separators + assertNull(formatMac("0g:11:22:33:44:55", COLON_LOWER)) // not hex + assertNull(formatMac("001:11:22:33:44:55", COLON_LOWER)) // byte field too long + } +} diff --git a/src/test/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/semanticdata/optionvalues/grammar/MacAddressGrammarTest.kt b/src/test/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/semanticdata/optionvalues/grammar/MacAddressGrammarTest.kt index 30162545..4f301dde 100644 --- a/src/test/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/semanticdata/optionvalues/grammar/MacAddressGrammarTest.kt +++ b/src/test/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/semanticdata/optionvalues/grammar/MacAddressGrammarTest.kt @@ -80,8 +80,8 @@ class MacAddressGrammarTest { fun testAddressColorsAsOneLiteralSpan() { // Both combinators wrap the raw hex forms in Labeled(Role.LITERAL): the whole address is a single // literal span (not coloured per octet / with the separators as operators). - assertEquals(listOf(Region(0, 17, Role.LITERAL)), mac.colorize("00:11:22:33:44:55")) - assertEquals(listOf(Region(0, 17, Role.LITERAL)), hwAddr.colorize("00-11-22-33-44-55")) + assertEquals(listOf(Region(0, 17, Role.LITERAL, SemanticTag.MAC_ADDRESS)), mac.colorize("00:11:22:33:44:55")) + assertEquals(listOf(Region(0, 17, Role.LITERAL, SemanticTag.MAC_ADDRESS)), hwAddr.colorize("00-11-22-33-44-55")) } @Test @@ -91,4 +91,33 @@ class MacAddressGrammarTest { assertEquals(listOf(Region(0, 11, Role.LITERAL, SemanticTag.IPV6)), hwAddr.colorize("2001:db8::1")) assertEquals(listOf(Region(0, 11, Role.LITERAL)), hwAddr.colorize("192.168.1.1")) } -} \ No newline at end of file + + @Test + fun testClassicEngineAcceptsEveryHardwareAddressLength() { + // The classic engine takes the first alternative matching a prefix and never backtracks, so the + // hardware-address families must stay ordered longest first. A shorter family placed earlier would + // eat the start of a longer address and leave the rest unmatched. + fun bytes(n: Int, sep: String) = (1..n).joinToString(sep) { "%02x".format(it) } + fun words(n: Int) = (1..n / 2).joinToString(".") { "%04x".format(it) } + for (n in listOf(4, 6, 16, 20)) { + for (value in listOf(bytes(n, ":"), bytes(n, "-"), words(n))) { + assertEquals(value, GrammarEngineVerdict.VALID, GrammarEngineVerdict.classic(hwAddr, value)) + assertEquals(value, true, hwAddr.accepts(value)) + } + } + } + + @Test + fun testClassicEngineStillAcceptsIpLiterals() { + // IP literals sit between the long and short families; a short family must never eat their prefix. + for (value in listOf("1:2:3:4:5:6:7:8", "2001:db8::1", "::1", "192.168.1.1")) { + assertEquals(value, GrammarEngineVerdict.VALID, GrammarEngineVerdict.classic(hwAddr, value)) + } + } + + @Test + fun testOnlySixByteAddressesAreTaggedAsMacs() { + assertEquals(listOf(Region(0, 11, Role.LITERAL)), hwAddr.colorize("01:02:03:04")) + assertEquals(listOf(Region(0, 59, Role.LITERAL)), hwAddr.colorize((1..20).joinToString(":") { "%02x".format(it) })) + } +}