Skip to content

Commit

Permalink
feat: Add support for enum key name prefix
Browse files Browse the repository at this point in the history
  • Loading branch information
alkalinecoffee committed Oct 1, 2024
1 parent b9f1bda commit 5d458b6
Show file tree
Hide file tree
Showing 6 changed files with 37 additions and 35 deletions.
9 changes: 2 additions & 7 deletions languages/c/src/types/NativeHelpers.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ const getNativeType = (json, fireboltString = false) => {
}
else if (jsonType === 'null' ) {
type = 'void'
}
}
return type
}

Expand Down Expand Up @@ -125,18 +125,13 @@ const getArrayAccessors = (arrayName, propertyType, valueType) => {
return res
}

const enumValue = (val,prefix) => {
const keyName = getSafeEnumKeyName(val)
return ` ${prefix.toUpperCase()}_${keyName.toUpperCase()}`
}

const generateEnum = (schema, prefix)=> {
if (!schema.enum) {
return ''
}
else {
let str = `typedef enum {\n`
str += schema.enum.map(e => enumValue(e, prefix)).join(',\n')
str += schema.enum.map(e => getSafeEnumKeyName(val, prefix)).join(',\n')
str += `\n} ${prefix};\n`
return str
}
Expand Down
12 changes: 6 additions & 6 deletions src/macrofier/engine.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -618,7 +618,7 @@ const insertAggregateMacros = (fContents = '', aggregateMacros = {}) => {
fContents = fContents.replace(/[ \t]*\/\* \$\{MOCK_OBJECTS\} \*\/[ \t]*\n/, aggregateMacros.mockObjects)
fContents = fContents.replace(/\$\{readable\}/g, aggregateMacros.version.readable)
fContents = fContents.replace(/\$\{package.name\}/g, aggregateMacros.library)

return fContents
}

Expand Down Expand Up @@ -1319,7 +1319,7 @@ function insertMethodMacros(template, methodObj, json, templates, type = '', exa
const subscriberName = subscriber.name.toLowerCase();
return subscriberName && strippedEventName === subscriberName;
})

result.schema = JSON.parse(JSON.stringify(getPayloadFromEvent(methodObj)))
event.result.schema = getPayloadFromEvent(event)
event.params = event.params.filter(p => p.name !== 'listen')
Expand Down Expand Up @@ -1407,7 +1407,7 @@ function insertMethodMacros(template, methodObj, json, templates, type = '', exa
}

let signature

if (Object.keys(languages).length && template.indexOf('${method.signature}') >= 0) {
const lang = languages[Object.keys(languages)[0]]
signature = getTemplateForDeclaration(methodObj, templates, 'declarations')
Expand Down Expand Up @@ -1749,7 +1749,7 @@ function insertParameterMacros(template, param, method, module) {
.replace(/\$\{method.param.constraints\}/g, constraints) //getType(param))

return template

}

function insertCapabilityMacros(template, capabilities, method, module) {
Expand Down Expand Up @@ -1883,9 +1883,9 @@ function insertProviderInterfaceMacros(template, capability, moduleJson = {}, te
let name = getProviderInterfaceName(iface, capability, moduleJson)
let xValues
const suffix = state.destination ? state.destination.split('.').pop() : ''

// Determine if any method has the 'x-allow-focus' tag set to true
const hasFocusableMethods = iface.some(method =>
const hasFocusableMethods = iface.some(method =>
method.tags.some(tag => tag['x-allow-focus'] === true)
)

Expand Down
4 changes: 2 additions & 2 deletions src/macrofier/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -196,14 +196,14 @@ const macrofy = async (
templatesPerModule.forEach(t => {
const macros = engine.generateMacros(module, templates, exampleTemplates, {hideExcluded: hideExcluded, copySchemasIntoModules: copySchemasIntoModules, createPolymorphicMethods: createPolymorphicMethods, destination: t, type: 'methods'})
let content = getTemplateForModule(module.info.title, t, templates)

// NOTE: whichever insert is called first also needs to be called again last, so each phase can insert recursive macros from the other
content = engine.insertAggregateMacros(content, aggregateMacros)
content = engine.insertMacros(content, macros)
content = engine.insertAggregateMacros(content, aggregateMacros)

const location = createModuleDirectories ? path.join(output, module.info.title, t) : path.join(output, t.replace(/module/, module.info.title.toLowerCase()).replace(/index/, module.info.title))

outputFiles[location] = content
logSuccess(`Generated macros for module ${path.relative(output, location)}`)
})
Expand Down
8 changes: 4 additions & 4 deletions src/macrofier/types.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -228,8 +228,8 @@ const insertEnumMacros = (content, schema, module, name, suffix, templateDir = "
schema.enum.map(value => {
if (!value) {
value = getTemplate(path.join(templateDir, 'unset' + suffix))
}
value ? values.push(template[i].replace(/\$\{key\}/g, getSafeEnumKeyName(value))
}
value ? values.push(template[i].replace(/\$\{key\}/g, getSafeEnumKeyName(value, schema.enumKeyPrefix))
.replace(/\$\{value\}/g, value)) : ''
})
template[i] = values.map((value, id) => {
Expand Down Expand Up @@ -549,7 +549,7 @@ function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', paren
const suffix = destination && ('.' + destination.split('.').pop()) || ''
const theTitle = insertSchemaMacros(getTemplate(path.join(templateDir, 'title' + suffix)), schema, module, { name: schema.title, parent, property, required, recursive: false })

let result = getTemplate(path.join(templateDir, 'default' + suffix)) || '${shape}'
let result = getTemplate(path.join(templateDir, 'default' + suffix)) || '${shape}'

let genericTemplate = getTemplate(path.join(templateDir, 'generic' + suffix))
if (enums && level === 0 && Array.isArray(schema.enum) && ((schema.type === "string") || (schema.type[0] === "string"))) {
Expand Down Expand Up @@ -862,7 +862,7 @@ function getSchemaType(schema, module, { destination, templateDir = 'types', lin
const shape = insertAnyOfMacros(getTemplate(path.join(templateDir, 'anyOf' + suffix)), schema, module, theTitle)
return insertSchemaMacros(shape, schema, module, { name: theTitle, recursive: false })


// if (event) {
// return getSchemaType((schema.oneOf || schema.anyOf)[0], module, { destination, link, title, code, asPath, baseUrl })
// }
Expand Down
31 changes: 19 additions & 12 deletions src/shared/json-schema.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ const objectPaths = obj => {
return isObject(value) ?
product.concat(paths(value, fullPath))
: product.concat(fullPath)
}, []) : []
}, []) : []
}
return paths(obj);
}
Expand Down Expand Up @@ -100,7 +100,7 @@ const replaceUri = (existing, replacement, schema) => {
Object.keys(schema).forEach(key => {
replaceUri(existing, replacement, schema[key])
})
}
}
}

const replaceRef = (existing, replacement, schema) => {
Expand Down Expand Up @@ -206,7 +206,7 @@ const getPropertiesInSchema = (json, document) => {

return props
}

return null
}

Expand Down Expand Up @@ -244,7 +244,7 @@ function getSchemaConstraints(schema, module, options = { delimiter: '\n' }) {
typeof schema.exclusiveMinimum === 'number' ? constraints.push(`exclusiveMinimum: ${schema.exclusiveMinimum}`) : null
typeof schema.multipleOf === 'number' ? constraints.push(`multipleOf: ${schema.multipleOf}`) : null

return constraints.join(options.delimiter)
return constraints.join(options.delimiter)
}
else if (schema.type === 'array' && schema.items) {
let constraints = []
Expand All @@ -256,7 +256,7 @@ function getSchemaConstraints(schema, module, options = { delimiter: '\n' }) {
constraints = [getSchemaConstraints(schema.items, module, options)]
}

return constraints.join(options.delimiter)
return constraints.join(options.delimiter)
}
else if (schema.oneOf || schema.anyOf) {
return '' //See OpenRPC Schema for `oneOf` and `anyOf` details'
Expand Down Expand Up @@ -524,12 +524,19 @@ const getSafeKeyName = (value) => value.split(':').pop()
.replace(/[\.\-]/g, '_') // replace dots and dashes
.replace(/\+/g, '_plus') // change + to _plus

const getSafeEnumKeyName = (value) => value.split(':').pop() // use last portion of urn:style:values
.replace(/[\.\-]/g, '_') // replace dots and dashes
.replace(/\+/g, '_plus') // change + to _plus
.replace(/([a-z])([A-Z0-9])/g, '$1_$2') // camel -> snake case
.replace(/^([0-9]+(\.[0-9]+)?)/, 'v$1') // insert `v` in front of things that look like version numbers
.toUpperCase()
const getSafeEnumKeyName = function(value, keyPrefix = '') {
if (keyPrefix != '') {
value = keyPrefix + '_' + value
}

let key = value.split(':').pop() // use last portion of urn:style:values
.replace(/\+/g, '_plus') // change + to _plus
.replace(/[\.\-\/\;]/g, '_') // replace special characters
.replace(/([a-z])([A-Z0-9])/g, '$1_$2') // camel -> snake case
.replace(/^([0-9]+\_([0-9]+)?)/, 'v$1') // insert `v` in front of things that look like version numbers

return key.toUpperCase()
}

export {
getSchemaConstraints,
Expand All @@ -552,4 +559,4 @@ export {
mergeAnyOf,
mergeOneOf,
dereferenceAndMergeAllOfs
}
}
8 changes: 4 additions & 4 deletions src/validate/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ const run = async ({

addFormats(ajv)
// explicitly add our custom extensions so we can keep strict mode on (TODO: put these in a JSON config?)
ajv.addVocabulary(['x-method', 'x-this-param', 'x-additional-params', 'x-schemas', 'components', 'x-property'])
ajv.addVocabulary(['x-method', 'x-this-param', 'x-additional-params', 'x-schemas', 'components', 'x-property', 'enumKeyPrefix'])

const firebolt = ajv.compile(fireboltOpenRpcSpec)
const jsonschema = ajv.compile(jsonSchemaSpec)
Expand Down Expand Up @@ -153,7 +153,7 @@ const run = async ({
}
})

const examples = ajv.compile(exampleSpec)
const examples = ajv.compile(exampleSpec)

let result = validate(json, {}, ajv, jsonschema)
let exampleResult = validate(json, {}, ajv, examples)
Expand Down Expand Up @@ -293,7 +293,7 @@ const run = async ({
if (passThroughs) {
const passthroughResult = validatePasshtroughs(json)
printResult(passthroughResult, "Firebolt App pass-through")
}
}
}
catch (error) {
throw error
Expand All @@ -307,4 +307,4 @@ const run = async ({
return Promise.resolve()
}

export default run
export default run

0 comments on commit 5d458b6

Please sign in to comment.