2020-11-18 17:53:37 +00:00
|
|
|
/* eslint-env node */
|
2021-12-07 12:46:03 +00:00
|
|
|
import fs from 'fs'
|
2022-05-24 17:00:18 +00:00
|
|
|
import path from 'path'
|
2023-06-15 13:57:48 +00:00
|
|
|
|
|
|
|
import yaml from 'js-yaml'
|
2022-05-24 17:00:18 +00:00
|
|
|
import Engine from 'publicodes'
|
2020-11-18 17:53:37 +00:00
|
|
|
|
2022-01-27 17:28:48 +00:00
|
|
|
const publicodesDir = './règles'
|
|
|
|
const outDir = './dist'
|
2020-11-18 17:53:37 +00:00
|
|
|
|
|
|
|
if (!fs.existsSync(outDir)) {
|
|
|
|
fs.mkdirSync(outDir)
|
|
|
|
}
|
|
|
|
|
2022-01-25 14:54:59 +00:00
|
|
|
function recursiveFindYamlFile(dirPath = publicodesDir) {
|
2020-11-18 17:53:37 +00:00
|
|
|
return fs
|
|
|
|
.readdirSync(dirPath)
|
2022-01-25 14:54:59 +00:00
|
|
|
.flatMap((filename) => {
|
2020-11-18 17:53:37 +00:00
|
|
|
const fullpath = path.join(dirPath, filename)
|
|
|
|
if (fs.statSync(fullpath).isDirectory()) {
|
2022-01-25 14:54:59 +00:00
|
|
|
return recursiveFindYamlFile(fullpath)
|
2020-11-18 17:53:37 +00:00
|
|
|
} else {
|
2022-01-25 14:54:59 +00:00
|
|
|
return filename.endsWith('.yaml') ? fullpath : false
|
2020-11-18 17:53:37 +00:00
|
|
|
}
|
2022-01-25 15:03:20 +00:00
|
|
|
})
|
|
|
|
.filter(Boolean)
|
2020-11-18 17:53:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
function readRules() {
|
2022-01-25 14:54:59 +00:00
|
|
|
return recursiveFindYamlFile().reduce((rules, filePath) => {
|
2022-01-25 15:03:20 +00:00
|
|
|
const newRules = yaml.load(fs.readFileSync(filePath, 'utf-8'), {
|
|
|
|
filename: filePath,
|
|
|
|
})
|
|
|
|
const duplicatedRule = Object.keys(newRules).find(
|
|
|
|
(ruleName) => ruleName in rules
|
|
|
|
)
|
2022-01-25 14:54:59 +00:00
|
|
|
if (duplicatedRule) {
|
2022-01-25 15:03:20 +00:00
|
|
|
throw new Error(
|
|
|
|
`La règle ${duplicatedRule} a été redéfinie dans dans le fichier ${filePath}, alors qu'elle avait déjà été définie auparavant dans un autre fichier`
|
|
|
|
)
|
2022-01-25 14:54:59 +00:00
|
|
|
}
|
|
|
|
return Object.assign(rules, newRules)
|
|
|
|
}, {})
|
2020-11-18 17:53:37 +00:00
|
|
|
}
|
|
|
|
|
2022-02-14 16:57:18 +00:00
|
|
|
export default function writeJSFile() {
|
2020-11-18 17:53:37 +00:00
|
|
|
const rules = readRules()
|
2022-05-24 17:00:18 +00:00
|
|
|
const names = Object.keys(new Engine(rules).getParsedRules())
|
2023-09-25 18:02:13 +00:00
|
|
|
const json = JSON.stringify(JSON.stringify(rules))
|
|
|
|
const jsString = `export const json = /*@__PURE__*/ ${json};\nexport default /*@__PURE__*/ JSON.parse(json);`
|
2020-11-18 17:53:37 +00:00
|
|
|
fs.writeFileSync(path.resolve(outDir, 'index.js'), jsString)
|
|
|
|
fs.writeFileSync(
|
|
|
|
path.resolve(outDir, 'names.ts'),
|
|
|
|
`\nexport type Names = ${names.map((name) => `"${name}"`).join('\n | ')}\n`
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
writeJSFile()
|