keycloak_theme/src/bin/tools/transformCodebase.ts

48 lines
1.6 KiB
TypeScript
Raw Normal View History

2021-02-21 17:38:59 +01:00
import * as fs from "fs";
import * as path from "path";
2021-02-21 23:40:10 +01:00
import { crawl } from "./crawl";
import { id } from "tsafe/id";
2023-08-24 08:58:00 +02:00
type TransformSourceCode = (params: { sourceCode: Buffer; filePath: string; fileRelativePath: string }) =>
| {
modifiedSourceCode: Buffer;
newFileName?: string;
}
| undefined;
2021-03-03 02:31:02 +01:00
/** Apply a transformation function to every file of directory */
export function transformCodebase(params: { srcDirPath: string; destDirPath: string; transformSourceCode?: TransformSourceCode }) {
const {
srcDirPath,
destDirPath,
transformSourceCode = id<TransformSourceCode>(({ sourceCode }) => ({
"modifiedSourceCode": sourceCode
}))
2021-03-03 02:31:02 +01:00
} = params;
2021-02-21 17:38:59 +01:00
2023-08-24 08:58:00 +02:00
for (const fileRelativePath of crawl({ "dirPath": srcDirPath, "returnedPathsType": "relative to dirPath" })) {
const filePath = path.join(srcDirPath, fileRelativePath);
2021-02-21 17:38:59 +01:00
2021-03-03 02:31:02 +01:00
const transformSourceCodeResult = transformSourceCode({
2021-02-21 17:38:59 +01:00
"sourceCode": fs.readFileSync(filePath),
2023-08-24 08:58:00 +02:00
filePath,
fileRelativePath
2021-02-21 17:38:59 +01:00
});
2021-03-03 02:31:02 +01:00
if (transformSourceCodeResult === undefined) {
2021-02-21 17:38:59 +01:00
continue;
}
2023-08-24 08:58:00 +02:00
fs.mkdirSync(path.dirname(path.join(destDirPath, fileRelativePath)), {
"recursive": true
});
2021-02-21 17:38:59 +01:00
2021-03-03 02:31:02 +01:00
const { newFileName, modifiedSourceCode } = transformSourceCodeResult;
2021-02-21 17:38:59 +01:00
fs.writeFileSync(
2023-08-24 08:58:00 +02:00
path.join(path.dirname(path.join(destDirPath, fileRelativePath)), newFileName ?? path.basename(fileRelativePath)),
modifiedSourceCode
2021-02-21 17:38:59 +01:00
);
}
}