Handle conditional arguments

This commit is contained in:
Adria Navarro 2025-02-27 14:16:52 +01:00
parent 56e143625d
commit 78e558c4aa
2 changed files with 96 additions and 1 deletions

View File

@ -94,7 +94,15 @@ export function validateHbsTemplate(
providedParamsCount++ providedParamsCount++
} }
if (providedParamsCount !== expectedArguments.length) { const optionalArgMatcher = new RegExp(/^\[(.+)\]$/)
const optionalArgs = expectedArguments.filter(a =>
optionalArgMatcher.test(a)
)
if (
!optionalArgs.length &&
providedParamsCount !== expectedArguments.length
) {
diagnostics.push({ diagnostics.push({
from, from,
to, to,
@ -105,6 +113,29 @@ export function validateHbsTemplate(
", " ", "
)}), but got ${providedParamsCount}.`, )}), but got ${providedParamsCount}.`,
}) })
} else if (optionalArgs.length) {
const maxArgs = expectedArguments.length
const minArgs = maxArgs - optionalArgs.length
const parameters = expectedArguments
.map(a => {
const test = optionalArgMatcher.exec(a)
if (!test?.[1]) {
return a
}
return `${test[1]} (optional)`
})
.join(", ")
if (
minArgs > providedParamsCount ||
maxArgs < providedParamsCount
) {
diagnostics.push({
from,
to,
severity: "error",
message: `Helper "${helperName}" expects between ${minArgs} to ${expectedArguments.length} parameters (${parameters}), but got ${providedParamsCount}.`,
})
}
} }
} }

View File

@ -138,5 +138,69 @@ describe("hbs validator", () => {
}, },
]) ])
}) })
describe("optional parameters", () => {
it("supports empty parameters", () => {
const validators: CodeValidator = {
helperFunction: {
arguments: ["a", "b", "[c]"],
},
}
const text = "{{ helperFunction 1 99 }}"
const result = validateHbsTemplate(text, validators)
expect(result).toHaveLength(0)
})
it("supports valid parameters", () => {
const validators: CodeValidator = {
helperFunction: {
arguments: ["a", "b", "[c]"],
},
}
const text = "{{ helperFunction 1 99 'a' }}"
const result = validateHbsTemplate(text, validators)
expect(result).toHaveLength(0)
})
it("returns a valid message on missing parameters", () => {
const validators: CodeValidator = {
helperFunction: {
arguments: ["a", "b", "[c]"],
},
}
const text = "{{ helperFunction 1 }}"
const result = validateHbsTemplate(text, validators)
expect(result).toEqual([
{
from: 0,
message: `Helper "helperFunction" expects between 2 to 3 parameters (a, b, c (optional)), but got 1.`,
severity: "error",
to: 22,
},
])
})
it("returns a valid message on too many parameters", () => {
const validators: CodeValidator = {
helperFunction: {
arguments: ["a", "b", "[c]"],
},
}
const text = "{{ helperFunction 1 2 3 4 }}"
const result = validateHbsTemplate(text, validators)
expect(result).toEqual([
{
from: 0,
message: `Helper "helperFunction" expects between 2 to 3 parameters (a, b, c (optional)), but got 4.`,
severity: "error",
to: 28,
},
])
})
})
}) })
}) })