Skip to content

Commit 3e861a7

Browse files
committed
Use widget prettier config and base config as fallback
1 parent 89f169b commit 3e861a7

2 files changed

Lines changed: 31 additions & 8 deletions

File tree

packages/pluggable-widgets-tools/src/typings-generator/index.ts

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,13 @@
1-
import { readFileSync, promises } from "fs";
1+
import { promises } from "fs";
22
import { join } from "path";
33
import { parseStringPromise } from "xml2js";
44
import { PackageXml } from "./PackageXml";
55
import { WidgetXml } from "./WidgetXml";
66
import { generateForWidget } from "./generate";
7-
import { format } from "prettier";
7+
import { formatTypeScript } from "../utils/formatting";
88

99
const { mkdir, readFile, stat, writeFile } = promises;
1010

11-
const prettierConfig = {
12-
parser: "babel-ts",
13-
...JSON.parse(readFileSync(join(__dirname, "../../configs/prettier.base.json"), "utf-8"))
14-
};
15-
1611
export async function transformPackage(content: string, basePath: string) {
1712
const contentXml = (await parseStringPromise(content)) as PackageXml;
1813
if (!contentXml) {
@@ -45,7 +40,7 @@ export async function transformPackage(content: string, basePath: string) {
4540
);
4641
}
4742

48-
const formattedContent = await format(generatedContent, prettierConfig);
43+
const formattedContent = await formatTypeScript(generatedContent);
4944
const resultPath = sourcePath.replace(/(\.xml)?$/, "Props.d.ts");
5045
await writeFile(join(resultBasePath, resultPath), formattedContent);
5146
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { readFile } from "fs/promises";
2+
import { join } from "path";
3+
import { resolveConfig, format, Options } from "prettier";
4+
import { cwd } from "process";
5+
6+
const prettierConfigBasePath = join(__dirname, "../../configs/prettier.base.json");
7+
8+
let prettierTypescriptConfig: Options | undefined;
9+
10+
/**
11+
* Uses prettier to format the given TypeScript sourcecode.
12+
* @param source The TypeScript snippet that needs to be formatted
13+
*/
14+
export async function formatTypeScript(source: string): Promise<string> {
15+
if (prettierTypescriptConfig === undefined) {
16+
const fakeFilename = join(cwd(), "./src/widget.ts");
17+
// If the widget does not have a prettier config, fall back to packaged base config
18+
const prettierConfig =
19+
(await resolveConfig(fakeFilename)) ?? JSON.parse(await readFile(prettierConfigBasePath, "utf-8"));
20+
21+
prettierTypescriptConfig = {
22+
...prettierConfig,
23+
parser: "babel-ts"
24+
};
25+
}
26+
27+
return await format(source, prettierTypescriptConfig);
28+
}

0 commit comments

Comments
 (0)