Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add match regex attribute #1760

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/locales/src/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
"integer.between": "an integer between %0% and %1%",
"invalid-key-combination": "Invalid combination of keys %0%",
"invalid-regex-pattern": "Invalid regex pattern: %0%",
"mismatching-regex-pattern": "Value does not match regex: %0%",
"java-edition.binder.wrong-folder": "Files in the %0% folder are not recognized in loaded version %1%, did you meant to use the %2% folder?",
"java-edition.binder.wrong-version": "Files in the %0% folder are not recognized in loaded version %1%",
"java-edition.pack-format.unsupported": "Pack format %0% does not have a corresponding release version. Snapshot versions are unsupported.",
Expand Down
44 changes: 44 additions & 0 deletions packages/mcdoc/src/runtime/attribute/builtin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,19 @@ const idValidator = validator.alternatives<IdConfig>(
() => ({}),
)

interface RegexConfig {
regex: string
error?: string
}

const regexMatchValidator = validator.alternatives<RegexConfig>(
validator.map(validator.string, v => ({ regex: v })),
validator.tree({
regex: validator.string,
error: validator.optional(validator.string),
}),
)

function getResourceLocationOptions(
{ registry, tags, definition, path }: IdConfig,
requireCanonical: boolean,
Expand Down Expand Up @@ -277,4 +290,35 @@ export function registerBuiltinAttributes(meta: core.MetaRegistry) {
}
},
})
registerAttribute(meta, 'match_regex', regexMatchValidator, {
checker: (config, typeDef, _) => {
if (typeDef.kind !== 'literal' || typeDef.value.kind !== 'string') {
return undefined
}
const pattern = config.regex
const value = typeDef.value.value
return (node, ctx) => {
try {
const regex = RegExp(pattern)
if (!regex.test(value)) {
if (config.error) {
ctx.err.report(config.error, node, 2)
} else {
ctx.err.report(
localize('mismatching-regex-pattern', typeDef.value.value),
node,
2,
)
}
}
} catch (e) {
const message = e instanceof Error ? e.message : `${e}`
const error = message
.replace(/^Invalid regular expression: /, '')
.replace(/^\/.+\/: /, '')
ctx.err.report(localize('invalid-regex-pattern', error), node, 2)
}
}
},
})
}