Skip to content

Commit

Permalink
feat: examples generator v1
Browse files Browse the repository at this point in the history
  • Loading branch information
lukasz.klejszta committed Jun 29, 2022
1 parent 1327dea commit fd7c463
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 1 deletion.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"version": "0.0.0",
"license": "MIT",
"scripts": {
"prepublish": "node ./scripts/example-generator.js ./packages/falso/src/lib/",
"build:docs": "npm run build && node ./docs-generator.js",
"start:docs": "npm run build:docs && npm run start --prefix docs",
"build": "nx build falso && npm run i18n && node ./post-build.js",
Expand Down
7 changes: 6 additions & 1 deletion packages/falso/src/lib/abbreviation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,12 @@ import { data } from './abbreviation.json';
* @example
*
* randAbbreviation({ length: 10 })
*
*
* @automaticallyGeneratedExamples
* @example
* SCSI
* SMTP
* ADP
*/
export function randAbbreviation<O extends FakeOptions = never>(options?: O) {
return fake(data, options);
Expand Down
39 changes: 39 additions & 0 deletions scripts/example-generator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
const fs = require('fs');

const [libDirectoryPath] = process.argv.slice(2);
const GENERATE_INDICATOR = "@automaticallyGeneratedExamples"
// https://regex101.com/r/rlqGTA/1
const regexp = new RegExp(`(${GENERATE_INDICATOR}).*\\/`,"gs");
const errors = [];

console.log('Generating examples...')
const filenames = fs
.readdirSync(libDirectoryPath)
.filter((jsonFilename, index, array) => jsonFilename.includes(".json") && array.find(tsFilename => tsFilename.replace('ts','json') === jsonFilename))

filenames.forEach(filename => {
try {
const tsFilepath = `${libDirectoryPath}${filename.replace('json','ts')}`
const tsFileContent = fs.readFileSync(tsFilepath).toString();
if(!tsFileContent.includes(GENERATE_INDICATOR)) {
console.log(`file is missing '${GENERATE_INDICATOR}' and will be ignored ${filename.replace('json','ts')}`);
return;
}
const jsonFilepath = `${libDirectoryPath}${filename}`
const jsonFileContent = JSON.parse(fs.readFileSync(jsonFilepath));
if(jsonFileContent.data === undefined) {
throw Error(`missing data field in file: ${filename}`);
}
if(!(jsonFileContent.data instanceof Array)) {
throw Error(`invalid data field, must be an array: ${filename}`);
}
fs.writeFileSync(tsFilepath, tsFileContent.replace(regexp, `${GENERATE_INDICATOR}\n * @example\n${jsonFileContent.data.slice(0,3).map(example => ` * ${example}\n`).join('')} */`));
} catch(error) {
errors.push({filename, error});
}
});

if(errors.length > 0) {
console.log(errors);
}
console.log(`Generating examples finished ${filenames.length - errors.length}/${filenames.length}`);

0 comments on commit fd7c463

Please sign in to comment.