|
| 1 | +import type { Root } from 'mdast' |
| 2 | +import type { |
| 3 | + MdxJsxAttribute, |
| 4 | + MdxJsxAttributeValueExpression, |
| 5 | +} from 'mdast-util-mdx-jsx' |
| 6 | +import { lintRule } from 'unified-lint-rule' |
| 7 | +import { visitParents } from 'unist-util-visit-parents' |
| 8 | + |
| 9 | +const LEGACY_OS_NAME_REGEX = |
| 10 | + /(?<![\p{L}\p{N}])(?:micro\s*os|micros|kube\s*os)(?![\p{L}\p{N}])/giu |
| 11 | + |
| 12 | +interface StringValueNode { |
| 13 | + value: string |
| 14 | + position?: Root['position'] |
| 15 | +} |
| 16 | + |
| 17 | +const isStringValueNode = (node: unknown): node is StringValueNode => |
| 18 | + !!node && |
| 19 | + typeof node === 'object' && |
| 20 | + 'value' in node && |
| 21 | + typeof node.value === 'string' |
| 22 | + |
| 23 | +const reportLegacyOSNames = ( |
| 24 | + value: string, |
| 25 | + report: (legacyName: string) => void, |
| 26 | +) => { |
| 27 | + for (const { 0: legacyName } of value.matchAll(LEGACY_OS_NAME_REGEX)) { |
| 28 | + report(legacyName) |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +const createMessage = (legacyName: string) => |
| 33 | + `Unexpected legacy OS name "${legacyName}", use "Alauda OS" or "alauda os" instead` |
| 34 | + |
| 35 | +const getAttributeStringValue = ( |
| 36 | + value: MdxJsxAttribute['value'], |
| 37 | +): string | undefined => { |
| 38 | + if (typeof value === 'string') { |
| 39 | + return value |
| 40 | + } |
| 41 | + |
| 42 | + return (value as MdxJsxAttributeValueExpression).value |
| 43 | +} |
| 44 | + |
| 45 | +export const noLegacyOSNames = lintRule<Root>( |
| 46 | + 'doom-lint:no-legacy-os-names', |
| 47 | + (root, vfile) => { |
| 48 | + visitParents(root, (node, parents) => { |
| 49 | + if (!isStringValueNode(node)) { |
| 50 | + return |
| 51 | + } |
| 52 | + |
| 53 | + reportLegacyOSNames(node.value, (legacyName) => { |
| 54 | + vfile.message(createMessage(legacyName), { |
| 55 | + ancestors: [...parents, node], |
| 56 | + place: node.position, |
| 57 | + }) |
| 58 | + }) |
| 59 | + }) |
| 60 | + |
| 61 | + visitParents( |
| 62 | + root, |
| 63 | + ['mdxJsxFlowElement', 'mdxJsxTextElement'] as const, |
| 64 | + (element, parents) => { |
| 65 | + for (const attribute of element.attributes) { |
| 66 | + if ( |
| 67 | + attribute.type !== 'mdxJsxAttribute' || |
| 68 | + typeof attribute.value === 'boolean' || |
| 69 | + attribute.value == null |
| 70 | + ) { |
| 71 | + continue |
| 72 | + } |
| 73 | + |
| 74 | + const value = getAttributeStringValue(attribute.value) |
| 75 | + if (value == null) { |
| 76 | + continue |
| 77 | + } |
| 78 | + |
| 79 | + reportLegacyOSNames(value, (legacyName) => { |
| 80 | + vfile.message(createMessage(legacyName), { |
| 81 | + ancestors: [...parents, element], |
| 82 | + place: attribute.position, |
| 83 | + }) |
| 84 | + }) |
| 85 | + } |
| 86 | + }, |
| 87 | + ) |
| 88 | + }, |
| 89 | +) |
0 commit comments