-
Notifications
You must be signed in to change notification settings - Fork 2
/
create-new-variant.mjs
78 lines (64 loc) · 2.35 KB
/
create-new-variant.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import { readFileSync, writeFileSync } from "fs";
import nunjucks from "nunjucks";
import path from "path";
/* global console */
/* global process */
// Function to replace templates
function replaceTemplates(sourcePath, targetPath, variantName) {
// Read the source file
let content = readFileSync(sourcePath, "utf-8");
// Use Nunjucks to render the template
content = nunjucks.renderString(content, {
namePascal: snakeToPascal(variantName),
nameSnake: variantName,
nameCamel: snakeToCamel(variantName),
});
// Write the rendered content to the target file
writeFileSync(targetPath, content);
}
// convert snake_case string to PascalCase
function snakeToPascal(snakeCase) {
// Split the string into an array of words
const words = snakeCase.split("_");
// Capitalize the first letter of each word
const pascalWords = words.map(
(word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(),
);
// Join the words back together
return pascalWords.join("");
}
// convert snake_case string to camelCase
function snakeToCamel(snakeCase) {
// Split the string into an array of words
const words = snakeCase.split("_");
// Capitalize the first letter of each word
const capitalizedWords = words.map(
(word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(),
);
return [words[0], ...capitalizedWords.slice(1)].join("");
}
// Get the variant name
if (process.argv.length !== 3) {
console.log("Usage: node create-new-variant.mjs [variant name]");
process.exit(1);
}
const variantName = process.argv[2];
if (!/^[a-z_]*$/.test(variantName)) {
console.error(
"Please use snake_case (only lower case letters and underscores)",
);
process.exit(1);
}
// Define source and target directories
const variantsDir = path.join(process.cwd(), "src/variants");
const sourceFileTemplate = path.join(variantsDir, "template/variant.ts.njk");
const sourceFileOutput = path.join(variantsDir, `${variantName}.ts`);
const testFileTemplate = path.join(variantsDir, "template/variant.test.ts.njk");
const testFileOutput = path.join(
variantsDir,
`__tests__/${variantName}.test.ts`,
);
// Call the copy directory function
replaceTemplates(sourceFileTemplate, sourceFileOutput, variantName);
replaceTemplates(testFileTemplate, testFileOutput, variantName);
console.log("Directory copied and templates replaced successfully.");