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";
|
2021-10-11 21:35:40 +02:00
|
|
|
import { id } from "tsafe/id";
|
|
|
|
|
|
|
|
type TransformSourceCode = (params: {
|
|
|
|
sourceCode: Buffer;
|
|
|
|
filePath: string;
|
|
|
|
}) =>
|
|
|
|
| {
|
|
|
|
modifiedSourceCode: Buffer;
|
|
|
|
newFileName?: string;
|
|
|
|
}
|
|
|
|
| undefined;
|
2021-03-03 02:31:02 +01:00
|
|
|
|
|
|
|
/** Apply a transformation function to every file of directory */
|
2021-10-11 21:35:40 +02:00
|
|
|
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
|
|
|
|
|
|
|
for (const file_relative_path of crawl(srcDirPath)) {
|
|
|
|
const filePath = path.join(srcDirPath, file_relative_path);
|
|
|
|
|
2021-03-03 02:31:02 +01:00
|
|
|
const transformSourceCodeResult = transformSourceCode({
|
2021-02-21 17:38:59 +01:00
|
|
|
"sourceCode": fs.readFileSync(filePath),
|
2021-10-11 21:35:40 +02:00
|
|
|
"filePath": path.join(srcDirPath, file_relative_path),
|
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;
|
|
|
|
}
|
|
|
|
|
2021-10-11 21:35:40 +02:00
|
|
|
fs.mkdirSync(path.dirname(path.join(destDirPath, file_relative_path)), {
|
|
|
|
"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(
|
|
|
|
path.join(
|
|
|
|
path.dirname(path.join(destDirPath, file_relative_path)),
|
2021-10-11 21:35:40 +02:00
|
|
|
newFileName ?? path.basename(file_relative_path),
|
2021-02-21 17:38:59 +01:00
|
|
|
),
|
2021-10-11 21:35:40 +02:00
|
|
|
modifiedSourceCode,
|
2021-02-21 17:38:59 +01:00
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|