2020-11-18 17:53:37 +00:00
/* eslint-env node */
const fs = require ( 'fs' )
const path = require ( 'path' )
2022-01-25 14:54:59 +00:00
const yaml = require ( 'js-yaml' )
2020-11-18 17:53:37 +00:00
const publicodesDir = path . resolve ( _ _dirname , './règles' )
const outDir = path . resolve ( _ _dirname , './dist' )
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 14:54:59 +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 ) => {
const newRules = yaml . load ( fs . readFileSync ( filePath , 'utf-8' ) , { filename : filePath } )
const duplicatedRule = Object . keys ( newRules ) . find ( ruleName => ruleName in rules )
if ( duplicatedRule ) {
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 ` )
}
return Object . assign ( rules , newRules )
} , { } )
2020-11-18 17:53:37 +00:00
}
// Note: we can't put the output file in the fs.watched directory
function writeJSFile ( ) {
const rules = readRules ( )
const names = Object . keys ( rules )
const jsString = ` module.exports = ${ JSON . stringify ( rules , null , 2 ) } `
fs . writeFileSync ( path . resolve ( outDir , 'index.js' ) , jsString )
fs . writeFileSync (
path . resolve ( outDir , 'names.ts' ) ,
` \n export type Names = ${ names . map ( ( name ) => ` " ${ name } " ` ) . join ( '\n | ' ) } \n `
)
}
writeJSFile ( )
exports . watchDottedNames = ( ) => fs . watch ( publicodesDir , writeJSFile )