From 74ec70e21bfd80bf252f66a1ae6ceb7c3859e2ef Mon Sep 17 00:00:00 2001 From: Steve Ramage Date: Fri, 6 Nov 2026 05:41:20 -0700 Subject: [PATCH 1/3] feat: suggest a preferred format for MAC addresses (Resolves #575) Add a MacAddressFormatInspection (grammar engine only) that flags 6-byte MAC addresses not written in the user's preferred format and offers a quick fix to rewrite them. The format is a new project setting on the "systemd Unit Files" page: leave alone, colon lower (systemd's own output, default), colon upper, hyphen upper or dot (Cisco) lower. Hardware-address families are now grouped by length (IPv4 tunnel, Ethernet, IPv6 tunnel, InfiniBand), each Labeled exactly once. Only the 6-byte Ethernet family carries the new SemanticTag.MAC_ADDRESS, so the inspection also covers MACs inside Match=/Link= hardware-address lists without touching tunnel or InfiniBand addresses. Co-Authored-By: Claude Opus 5.5 --- .../inspections/MacAddressFormatInspection.kt | 65 +++++++++ .../intentions/NormalizeMacFormatQuickFix.kt | 26 ++++ .../optionvalues/grammar/Combinators.kt | 57 ++++++-- .../optionvalues/grammar/MacAddress.kt | 48 ++++++ .../optionvalues/grammar/SemanticTag.kt | 7 +- .../settings/ExperimentalSettings.kt | 6 + .../settings/PodmanQuadletConfigurable.kt | 20 ++- .../settings/PreferredMacFormat.kt | 22 +++ src/main/resources/META-INF/plugin.xml | 4 + .../MacAddressFormatInspectionTest.kt | 138 ++++++++++++++++++ .../grammar/MacAddressFormatTest.kt | 66 +++++++++ .../grammar/MacAddressGrammarTest.kt | 4 +- 12 files changed, 447 insertions(+), 16 deletions(-) create mode 100644 src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/inspections/MacAddressFormatInspection.kt create mode 100644 src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/intentions/NormalizeMacFormatQuickFix.kt create mode 100644 src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/semanticdata/optionvalues/grammar/MacAddress.kt create mode 100644 src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/settings/PreferredMacFormat.kt create mode 100644 src/test/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/inspections/MacAddressFormatInspectionTest.kt create mode 100644 src/test/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/semanticdata/optionvalues/grammar/MacAddressFormatTest.kt 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..34c1a500 --- /dev/null +++ b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/inspections/MacAddressFormatInspection.kt @@ -0,0 +1,65 @@ +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 net.sjrx.intellij.plugins.systemdunitfiles.intentions.NormalizeMacFormatQuickFix +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.formatMac +import net.sjrx.intellij.plugins.systemdunitfiles.semanticdata.optionvalues.grammar.labeledRegions +import net.sjrx.intellij.plugins.systemdunitfiles.settings.ExperimentalSettings +import net.sjrx.intellij.plugins.systemdunitfiles.settings.PreferredMacFormat + +/** + * Suggests rewriting a 6-byte MAC address to the user's [PreferredMacFormat], behind the grammar flag. + * It walks the grammar's labeled value spans and, for those tagged [SemanticTag.MAC_ADDRESS], offers a + * quick fix when the spelling isn't already the preferred one. + */ +class MacAddressFormatInspection : LocalInspectionTool() { + + 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 experimental = ExperimentalSettings.getInstance(file.project).state + if (!experimental.useGrammarParseEngine) return PsiElementVisitor.EMPTY_VISITOR + val format = experimental.preferredMacFormat + if (format == PreferredMacFormat.LEAVE_ALONE) return PsiElementVisitor.EMPTY_VISITOR + return MyVisitor(holder, format) + } + + private class MyVisitor(private val holder: ProblemsHolder, private val format: PreferredMacFormat) : + 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 + + for (region in validator.combinator.labeledRegions(value)) { + if (region.tag != SemanticTag.MAC_ADDRESS) continue // act only on spans the grammar detects as a Mac address + val text = value.substring(region.start, region.end) + val canonical = formatMac(text, format) ?: continue // the correct format for mac + if (canonical == text) continue + holder.registerProblem( + property.valueNode.psi, + "MAC address is not in preferred format, use: '$canonical'", + ProblemHighlightType.WEAK_WARNING, + TextRange(region.start, region.end), + NormalizeMacFormatQuickFix(region.start, text, canonical), + ) + } + } + } +} 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..7261b875 --- /dev/null +++ b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/intentions/NormalizeMacFormatQuickFix.kt @@ -0,0 +1,26 @@ +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 + +/** + * Rewrites the MAC address at [offset] (within the option value) 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(private val offset: Int, private val original: String, private val replacement: String) : LocalQuickFix { + + override fun getName(): String ="Convert MAC address to '$replacement'" + + override fun getFamilyName(): String = "Convert to canonical MAC address format" + + override fun applyFix(project: Project, descriptor: ProblemDescriptor) { + val fullPropertyValue = descriptor.psiElement.text + val newText = fullPropertyValue.substring(0, offset) + replacement + 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) + } +} 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..d65b93f8 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,24 +204,59 @@ 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: an Ethernet MAC (Wi-Fi, wired NICs, bridges, VLANs, ...). +private val ETHERNET_HW_ADDR = Labeled(Role.LITERAL, AlternativeCombinator( hwAddrGroups(HW_ADDR_BYTE, COLON, 6), hwAddrGroups(HW_ADDR_BYTE, HYPHEN, 6), hwAddrGroups(HW_ADDR_WORD, DOT, 3), +), tag=SemanticTag.MAC_ADDRESS) + +// 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 + +// Every raw hex hardware-address length. Not wrapped: each family is already its own literal span, and +// an outer Labeled would add a second, untagged region over every address. +// +// ORDER MATTERS: the classic matcher (SyntacticMatch) takes the first alternative that matches a +// *prefix* and never backtracks, so longer families must come before shorter ones. Otherwise e.g. the +// 4-byte colon branch eats the first 4 fields of a MAC and the rest is left over. (The new parse() +// engine tries every alternative, so it doesn't care.) +private val RAW_HARDWARE_ADDRESS = AlternativeCombinator( + INFINIBAND_HW_ADDR, + IPV6_TUNNEL_HW_ADDR, + ETHERNET_HW_ADDR, + IPV4_TUNNEL_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 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..c64c92a4 --- /dev/null +++ b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/semanticdata/optionvalues/grammar/MacAddress.kt @@ -0,0 +1,48 @@ +package net.sjrx.intellij.plugins.systemdunitfiles.semanticdata.optionvalues.grammar + +import net.sjrx.intellij.plugins.systemdunitfiles.settings.PreferredMacFormat + +/* + * MAC address re-formatting for MacAddressFormatInspection. The sibling of Ipv6.kt: parse the address + * to its raw bytes, then print those bytes in the requested style. + * + * Input is whatever the MAC_ADDRESS grammar matched (Combinators.kt), i.e. one of: + * 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. + */ + +/** + * 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] must come back unchanged (same case, same zero padding). + */ +fun formatMac(address: String, format: PreferredMacFormat): String? { + + var sixBlocks: List + if (address.matches("([a-fA-F0-9]{1,2}:){5}[a-fA-F0-9]{1,2}".toRegex())) { + sixBlocks = address.split(":").map { it -> it.toInt(16) } + } else if (address.matches("([a-fA-F0-9]{1,2}-){5}[a-fA-F0-9]{1,2}".toRegex())) { + sixBlocks = address.split("-").map { it -> it.toInt(16) } + } else if (address.matches("([a-fA-F0-9]{1,4}\\.){2}[a-fA-F0-9]{1,4}".toRegex())) { + sixBlocks = address.split(".").map { it.toInt(16) }.flatMap { listOf(it /256, it % 256) } + } else { + return null + } + + if (sixBlocks.size != 6) { + throw IllegalStateException("Uh this shouldn't be possible") + } + + + return when (format) { + PreferredMacFormat.LEAVE_ALONE -> null + PreferredMacFormat.COLON_LOWER -> sixBlocks.map { "%02x".format(it) }.joinToString(":") + PreferredMacFormat.COLON_UPPER -> sixBlocks.map { "%02X".format(it) }.joinToString(":") + PreferredMacFormat.HYPHEN_UPPER -> sixBlocks.map { "%02X".format(it) }.joinToString("-") + PreferredMacFormat.DOT_LOWER -> sixBlocks.chunked(2).joinToString(".") { "%02x%02x".format(it[0], it[1]) } + } +} 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 (grammar engine only):", 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() { @@ -55,6 +63,12 @@ class PodmanQuadletConfigurable(private val project: Project) : Configurable { val experimental = ExperimentalSettings.getInstance(project) experimental.state.useGrammarParseEngine = grammarEngineCheckbox?.isSelected ?: false experimental.state.underlineGrammarEngineKeys = underlineGrammarKeysCheckbox?.isSelected ?: false + val newMacFormat = selectedMacFormat() + if (experimental.state.preferredMacFormat != newMacFormat) { + experimental.state.preferredMacFormat = newMacFormat + // Inspections read the setting when they build their visitor, so re-run them on open files. + DaemonCodeAnalyzer.getInstance(project).restart() + } } override fun reset() { @@ -63,5 +77,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"/> + 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..19162755 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 From 4dc60cbb780fdfe5e61dab2ba10d57d8f17ccdd5 Mon Sep 17 00:00:00 2001 From: Steve Ramage Date: Fri, 6 Nov 2026 05:52:34 -0700 Subject: [PATCH 2/3] fix: address review findings on the MAC address format inspection (#575) - Share one ReplaceValueSpanQuickFix between the MAC and IPv6 fixes. It edits the document in place and only replaces text that still matches, falling back to a unique whole-token match, so "Fix all" on a value with several addresses no longer works from stale offsets. - Share a TaggedSpanRewriteInspection base for the MAC and IPv6 inspections. It maps valueText offsets back onto the raw value with valueTextOffsets(), so values continued over several lines are highlighted and fixed in the right place. - Stop tagging [Link] WakeOnLanPassword= as a MAC: it uses a new untagged SECUREON_PASSWORD grammar. - Order HARDWARE_ADDRESS so the classic engine accepts 16- and 20-byte colon addresses. Before, their first 8 fields matched as an IPv6 literal and the rest was rejected. This predates the PR; it was found by the new test. - Make macAddressBytes() in MacAddress.kt the one MAC parser (AdActorSystem now uses it), hoist its regexes, and return early from formatMac for LEAVE_ALONE. - Restart highlighting when any experimental setting changes, not only the MAC format. Co-Authored-By: Claude Opus 5.5 --- .../Ipv6CanonicalFormInspection.kt | 61 +++------------ .../inspections/MacAddressFormatInspection.kt | 64 ++++------------ .../TaggedSpanRewriteInspection.kt | 75 +++++++++++++++++++ .../inspections/ValueWarningInspection.kt | 2 +- .../intentions/CanonicalizeIpv6QuickFix.kt | 28 ++----- .../intentions/NormalizeMacFormatQuickFix.kt | 30 ++------ .../intentions/ReplaceValueSpanQuickFix.kt | 55 ++++++++++++++ .../ai/ConfigParseAdActorSystemOptionValue.kt | 15 ---- .../ai/ConfigParseWolPasswordOptionValue.kt | 4 +- .../optionvalues/grammar/Combinators.kt | 51 +++++++------ .../optionvalues/grammar/MacAddress.kt | 62 ++++++++------- .../settings/PodmanQuadletConfigurable.kt | 19 +++-- .../MacAddressFormatInspectionTest.kt | 38 ++++++++++ .../grammar/MacAddressGrammarTest.kt | 31 +++++++- 14 files changed, 313 insertions(+), 222 deletions(-) create mode 100644 src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/inspections/TaggedSpanRewriteInspection.kt create mode 100644 src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/intentions/ReplaceValueSpanQuickFix.kt 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 index 34c1a500..bbfb3d6c 100644 --- a/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/inspections/MacAddressFormatInspection.kt +++ b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/inspections/MacAddressFormatInspection.kt @@ -1,65 +1,27 @@ 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.NormalizeMacFormatQuickFix -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.formatMac -import net.sjrx.intellij.plugins.systemdunitfiles.semanticdata.optionvalues.grammar.labeledRegions import net.sjrx.intellij.plugins.systemdunitfiles.settings.ExperimentalSettings import net.sjrx.intellij.plugins.systemdunitfiles.settings.PreferredMacFormat /** - * Suggests rewriting a 6-byte MAC address to the user's [PreferredMacFormat], behind the grammar flag. - * It walks the grammar's labeled value spans and, for those tagged [SemanticTag.MAC_ADDRESS], offers a - * quick fix when the spelling isn't already the preferred one. + * 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 : LocalInspectionTool() { +class MacAddressFormatInspection : TaggedSpanRewriteInspection() { - 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 experimental = ExperimentalSettings.getInstance(file.project).state - if (!experimental.useGrammarParseEngine) return PsiElementVisitor.EMPTY_VISITOR - val format = experimental.preferredMacFormat - if (format == PreferredMacFormat.LEAVE_ALONE) return PsiElementVisitor.EMPTY_VISITOR - return MyVisitor(holder, format) - } + override val tag = SemanticTag.MAC_ADDRESS - private class MyVisitor(private val holder: ProblemsHolder, private val format: PreferredMacFormat) : - 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 rewriter(settings: ExperimentalSettings.State): ((String) -> String?)? { + val format = settings.preferredMacFormat + if (format == PreferredMacFormat.LEAVE_ALONE) return null + return { formatMac(it, format) } + } - for (region in validator.combinator.labeledRegions(value)) { - if (region.tag != SemanticTag.MAC_ADDRESS) continue // act only on spans the grammar detects as a Mac address - val text = value.substring(region.start, region.end) - val canonical = formatMac(text, format) ?: continue // the correct format for mac - if (canonical == text) continue - holder.registerProblem( - property.valueNode.psi, - "MAC address is not in preferred format, use: '$canonical'", - ProblemHighlightType.WEAK_WARNING, - TextRange(region.start, region.end), - NormalizeMacFormatQuickFix(region.start, text, canonical), - ) - } - } - } + 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) } 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..8d8d7c0b --- /dev/null +++ b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/inspections/TaggedSpanRewriteInspection.kt @@ -0,0 +1,75 @@ +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 + + 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)) + } + } + } + } +} 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 index 7261b875..9913d7ca 100644 --- a/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/intentions/NormalizeMacFormatQuickFix.kt +++ b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/intentions/NormalizeMacFormatQuickFix.kt @@ -1,26 +1,12 @@ 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 - /** - * Rewrites the MAC address at [offset] (within the option value) 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`. + * 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(private val offset: Int, private val original: String, private val replacement: String) : LocalQuickFix { - - override fun getName(): String ="Convert MAC address to '$replacement'" - - override fun getFamilyName(): String = "Convert to canonical MAC address format" - - override fun applyFix(project: Project, descriptor: ProblemDescriptor) { - val fullPropertyValue = descriptor.psiElement.text - val newText = fullPropertyValue.substring(0, offset) + replacement + 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 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/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 d65b93f8..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 @@ -216,12 +216,19 @@ private val IPV4_TUNNEL_HW_ADDR = Labeled(Role.LITERAL, AlternativeCombinator( hwAddrGroups(HW_ADDR_WORD, DOT, 2), )) -// 6 bytes: an Ethernet MAC (Wi-Fi, wired NICs, bridges, VLANs, ...). -private val ETHERNET_HW_ADDR = Labeled(Role.LITERAL, AlternativeCombinator( +// 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), -), tag=SemanticTag.MAC_ADDRESS) +) + +// 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( @@ -242,31 +249,29 @@ private val INFINIBAND_HW_ADDR = Labeled(Role.LITERAL, AlternativeCombinator( // Already Labeled and tagged SemanticTag.MAC_ADDRESS (above), so MacAddressFormatInspection can find it. val MAC_ADDRESS: Combinator = ETHERNET_HW_ADDR -// Every raw hex hardware-address length. Not wrapped: each family is already its own literal span, and -// an outer Labeled would add a second, untagged region over every address. -// -// ORDER MATTERS: the classic matcher (SyntacticMatch) takes the first alternative that matches a -// *prefix* and never backtracks, so longer families must come before shorter ones. Otherwise e.g. the -// 4-byte colon branch eats the first 4 fields of a MAC and the rest is left over. (The new parse() -// engine tries every alternative, so it doesn't care.) -private val RAW_HARDWARE_ADDRESS = AlternativeCombinator( - INFINIBAND_HW_ADDR, - IPV6_TUNNEL_HW_ADDR, - ETHERNET_HW_ADDR, - IPV4_TUNNEL_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 index c64c92a4..3f2c25e5 100644 --- 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 @@ -3,46 +3,52 @@ package net.sjrx.intellij.plugins.systemdunitfiles.semanticdata.optionvalues.gra import net.sjrx.intellij.plugins.systemdunitfiles.settings.PreferredMacFormat /* - * MAC address re-formatting for MacAddressFormatInspection. The sibling of Ipv6.kt: parse the address - * to its raw bytes, then print those bytes in the requested style. + * 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. * - * Input is whatever the MAC_ADDRESS grammar matched (Combinators.kt), i.e. one of: + * 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] must come back unchanged (same case, same zero padding). + * an address already in [format] comes back unchanged (same case, same zero padding). */ fun formatMac(address: String, format: PreferredMacFormat): String? { - - var sixBlocks: List - if (address.matches("([a-fA-F0-9]{1,2}:){5}[a-fA-F0-9]{1,2}".toRegex())) { - sixBlocks = address.split(":").map { it -> it.toInt(16) } - } else if (address.matches("([a-fA-F0-9]{1,2}-){5}[a-fA-F0-9]{1,2}".toRegex())) { - sixBlocks = address.split("-").map { it -> it.toInt(16) } - } else if (address.matches("([a-fA-F0-9]{1,4}\\.){2}[a-fA-F0-9]{1,4}".toRegex())) { - sixBlocks = address.split(".").map { it.toInt(16) }.flatMap { listOf(it /256, it % 256) } - } else { - return null - } - - if (sixBlocks.size != 6) { - throw IllegalStateException("Uh this shouldn't be possible") - } - - - return when (format) { - PreferredMacFormat.LEAVE_ALONE -> null - PreferredMacFormat.COLON_LOWER -> sixBlocks.map { "%02x".format(it) }.joinToString(":") - PreferredMacFormat.COLON_UPPER -> sixBlocks.map { "%02X".format(it) }.joinToString(":") - PreferredMacFormat.HYPHEN_UPPER -> sixBlocks.map { "%02X".format(it) }.joinToString("-") - PreferredMacFormat.DOT_LOWER -> sixBlocks.chunked(2).joinToString(".") { "%02x%02x".format(it[0], it[1]) } - } + 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/settings/PodmanQuadletConfigurable.kt b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/settings/PodmanQuadletConfigurable.kt index 6d6e77be..9cdeb6e1 100644 --- a/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/settings/PodmanQuadletConfigurable.kt +++ b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/settings/PodmanQuadletConfigurable.kt @@ -60,15 +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() - if (experimental.state.preferredMacFormat != newMacFormat) { - experimental.state.preferredMacFormat = newMacFormat - // Inspections read the setting when they build their visitor, so re-run them on open files. - DaemonCodeAnalyzer.getInstance(project).restart() - } + 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() { 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 index f3dbeba0..46a999aa 100644 --- a/src/test/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/inspections/MacAddressFormatInspectionTest.kt +++ b/src/test/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/inspections/MacAddressFormatInspectionTest.kt @@ -135,4 +135,42 @@ class MacAddressFormatInspectionTest : AbstractUnitFileTest() { 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()) + } } 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 19162755..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 @@ -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) })) + } +} From cf52c8ba6f47c5eb00a9f834879d950b16a0b88a Mon Sep 17 00:00:00 2001 From: Steve Ramage Date: Sat, 7 Nov 2026 14:16:03 -0700 Subject: [PATCH 3/3] feat: offer to adopt a MAC address's format as the preferred one (#575) Next to "Convert MAC address to ...", the MAC address format inspection now offers "Set preferred MAC address format to ..." when the address is written in one of the other formats on offer. It changes the setting and leaves the file alone. Also add the inspection's description (the Inspections settings page showed "Can't find inspection description") and drop "(grammar engine only)" from the setting's label. Co-Authored-By: Claude Opus 5.5 --- .../inspections/MacAddressFormatInspection.kt | 6 ++++ .../TaggedSpanRewriteInspection.kt | 5 ++- .../SetPreferredMacFormatQuickFix.kt | 31 +++++++++++++++++++ .../optionvalues/grammar/MacAddress.kt | 4 +++ .../settings/PodmanQuadletConfigurable.kt | 2 +- .../MacAddressFormat.html | 15 +++++++++ .../MacAddressFormatInspectionTest.kt | 28 +++++++++++++++++ 7 files changed, 89 insertions(+), 2 deletions(-) create mode 100644 src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/intentions/SetPreferredMacFormatQuickFix.kt create mode 100644 src/main/resources/inspectionDescriptions/MacAddressFormat.html 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 index bbfb3d6c..44aca66b 100644 --- a/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/inspections/MacAddressFormatInspection.kt +++ b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/inspections/MacAddressFormatInspection.kt @@ -2,8 +2,10 @@ 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 @@ -24,4 +26,8 @@ class MacAddressFormatInspection : TaggedSpanRewriteInspection() { 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 index 8d8d7c0b..3b58715d 100644 --- a/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/inspections/TaggedSpanRewriteInspection.kt +++ b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/inspections/TaggedSpanRewriteInspection.kt @@ -40,6 +40,9 @@ abstract class TaggedSpanRewriteInspection : LocalInspectionTool() { 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 @@ -67,7 +70,7 @@ abstract class TaggedSpanRewriteInspection : LocalInspectionTool() { 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)) + 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/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/grammar/MacAddress.kt b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/semanticdata/optionvalues/grammar/MacAddress.kt index 3f2c25e5..91e18501 100644 --- 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 @@ -41,6 +41,10 @@ fun macAddressBytes(text: String): IntArray? { * 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 diff --git a/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/settings/PodmanQuadletConfigurable.kt b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/settings/PodmanQuadletConfigurable.kt index 9cdeb6e1..9e0e621c 100644 --- a/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/settings/PodmanQuadletConfigurable.kt +++ b/src/main/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/settings/PodmanQuadletConfigurable.kt @@ -38,7 +38,7 @@ class PodmanQuadletConfigurable(private val project: Project) : Configurable { .addComponent(enabledCheckbox!!) .addComponent(grammarEngineCheckbox!!) .addComponent(underlineGrammarKeysCheckbox!!) - .addLabeledComponent("Preferred MAC address format (grammar engine only):", macFormatCombo!!) + .addLabeledComponent("Preferred MAC address format:", macFormatCombo!!) .addComponentFillVertically(JPanel(), 0) .panel } diff --git a/src/main/resources/inspectionDescriptions/MacAddressFormat.html b/src/main/resources/inspectionDescriptions/MacAddressFormat.html new file mode 100644 index 00000000..4dd401bd --- /dev/null +++ b/src/main/resources/inspectionDescriptions/MacAddressFormat.html @@ -0,0 +1,15 @@ + + +

+ 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 index 46a999aa..0453e1f6 100644 --- a/src/test/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/inspections/MacAddressFormatInspectionTest.kt +++ b/src/test/kotlin/net/sjrx/intellij/plugins/systemdunitfiles/inspections/MacAddressFormatInspectionTest.kt @@ -173,4 +173,32 @@ class MacAddressFormatInspectionTest : AbstractUnitFileTest() { 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")) + } }