update plugin to support prettier v3

This commit is contained in:
davidodenwald 2023-08-12 20:32:28 +02:00
parent ac512dd0b3
commit be28ec949f
6 changed files with 1107 additions and 1059 deletions

1980
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -25,19 +25,19 @@
"scripts": {
"build": "tsc",
"watch": "npm run build -- --watch",
"test": "jest --verbose",
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js --verbose",
"test:watch": "jest --watch --verbose",
"publish:release": "npm run test && npm run build && npm publish"
},
"devDependencies": {
"@babel/preset-typescript": "^7.21.5",
"@types/jest": "^29.5.1",
"jest": "^29.5.0",
"prettier": "^2.8.8",
"ts-jest": "^29.1.0",
"typescript": "^5.0.4"
"@babel/preset-typescript": "^7.22.5",
"@types/jest": "^29.5.3",
"jest": "^29.6.2",
"prettier": "^3.0.1",
"ts-jest": "^29.1.1",
"typescript": "^5.1.6"
},
"peerDependencies": {
"prettier": "^2.0.0"
"prettier": "^3.0.0"
}
}

View file

@ -1,6 +1,6 @@
import { Node } from "./jinja";
import { parse } from "./parser";
import { print, embed } from "./printer";
import { print, embed, getVisitorKeys } from "./printer";
import { Parser, Printer, SupportLanguage } from "prettier";
const PLUGIN_KEY = "jinja-template";
@ -27,5 +27,6 @@ export const printers = {
[PLUGIN_KEY]: <Printer<Node>>{
print,
embed,
getVisitorKeys,
},
};

View file

@ -1,4 +1,4 @@
import { AstPath, Printer } from "prettier";
import { AstPath, Printer, Options, Doc } from "prettier";
import { builders, utils } from "prettier/doc";
import { Placeholder, Node, Expression, Statement, Block } from "./jinja";
@ -6,6 +6,19 @@ const NOT_FOUND = -1;
process.env.PRETTIER_DEBUG = "true";
export const getVisitorKeys = (
ast: Node | { [id: string]: Node },
): string[] => {
if ("type" in ast) {
return ast.type === "root" ? ["nodes"] : [];
}
return Object.values(ast)
.filter((node) => {
return node.type === "block";
})
.map((e) => e.id);
};
export const print: Printer<Node>["print"] = (path) => {
const node = path.getNode();
if (!node) {
@ -40,7 +53,7 @@ const printExpression = (node: Expression): builders.Doc => {
]),
{
shouldBreak: node.preNewLines > 0,
}
},
);
return node.preNewLines > 1
@ -61,7 +74,7 @@ const printStatement = (node: Statement): builders.Doc => {
? [builders.hardline, node.delimiter, "%}"]
: [node.delimiter, "%}"],
]),
{ shouldBreak: node.preNewLines > 0 }
{ shouldBreak: node.preNewLines > 0 },
);
if (
@ -87,28 +100,31 @@ const printIgnoreBlock = (node: Node): builders.Doc => {
return node.content;
};
export const embed: Printer<Node>["embed"] = (
path,
print,
textToDoc,
options
) => {
export const embed: Printer<Node>["embed"] = () => {
return _embed;
};
const _embed = async (
textToDoc: (text: string, options: Options) => Promise<Doc>,
print: (selector?: string | number | Array<string | number> | AstPath) => Doc,
path: AstPath,
options: Options,
): Promise<Doc | undefined> => {
const node = path.getNode();
if (!node || !["root", "block"].includes(node.type)) {
return null;
return undefined;
}
const mapped = splitAtElse(node).map((content) => {
const mapped = await Promise.all(
splitAtElse(node).map(async (content) => {
let doc;
if (content in node.nodes) {
doc = content;
} else {
doc = utils.stripTrailingHardline(
textToDoc(content, {
doc = await textToDoc(content, {
...options,
parser: "html",
})
);
});
}
let ignoreDoc = false;
@ -124,7 +140,7 @@ export const embed: Printer<Node>["embed"] = (
}
const idxs = findPlaceholders(currentDoc).filter(
([start, end]) => currentDoc.slice(start, end + 1) in node.nodes
([start, end]) => currentDoc.slice(start, end + 1) in node.nodes,
);
if (!idxs.length) {
ignoreDoc = false;
@ -156,7 +172,8 @@ export const embed: Printer<Node>["embed"] = (
ignoreDoc = false;
return res;
});
});
}),
);
if (node.type === "block") {
const block = buildBlock(path, print, node as Block, mapped);
@ -172,7 +189,7 @@ const getMultilineGroup = (content: String): builders.Group => {
return builders.group(
content.split("\n").map((line, i) => {
return [builders.hardline, line.trim()];
})
}),
);
};
@ -181,7 +198,7 @@ const splitAtElse = (node: Node): string[] => {
(n) =>
n.type === "statement" &&
["else", "elif"].includes((n as Statement).keyword) &&
node.content.search(n.id) !== NOT_FOUND
node.content.search(n.id) !== NOT_FOUND,
);
if (!elseNodes.length) {
return [node.content];
@ -218,7 +235,7 @@ export const findPlaceholders = (text: string): [number, number][] => {
export const surroundingBlock = (node: Node): Block | undefined => {
return Object.values(node.nodes).find(
(n) => n.type === "block" && n.content.search(node.id) !== NOT_FOUND
(n) => n.type === "block" && n.content.search(node.id) !== NOT_FOUND,
) as Block;
};
@ -226,7 +243,7 @@ const buildBlock = (
path: AstPath<Node>,
print: (path: AstPath<Node>) => builders.Doc,
block: Block,
mapped: (string | builders.Doc[] | builders.DocCommand)[]
mapped: (string | builders.Doc[] | builders.DocCommand)[],
): builders.Doc => {
// if the content is empty or whitespace only.
if (block.content.match(/^\s*$/)) {
@ -239,14 +256,14 @@ const buildBlock = (
if (block.containsNewLines) {
return builders.group([
path.call(print, "nodes", block.start.id),
builders.indent([builders.softline, utils.stripTrailingHardline(mapped)]),
builders.indent([builders.softline, mapped]),
builders.hardline,
path.call(print, "nodes", block.end.id),
]);
}
return builders.group([
path.call(print, "nodes", block.start.id),
utils.stripTrailingHardline(mapped),
mapped,
path.call(print, "nodes", block.end.id),
]);
};

View file

@ -17,7 +17,7 @@ tests.forEach((test) => {
if (test.startsWith("_")) {
return;
}
return it(test, () => {
return it(test, async () => {
const path = join(testFolder, test);
const input = readFileSync(join(path, "input.html")).toString();
const expected = readFileSync(join(path, "expected.html")).toString();
@ -34,11 +34,11 @@ tests.forEach((test) => {
if (expectedError) {
jest.spyOn(console, "error").mockImplementation(() => {});
expect(format).toThrow(expectedError);
await expect(format()).rejects.toThrow(expectedError);
} else {
const result = format();
const result = await format();
expect(result).toEqual(expected);
expect(prettify(result, configObject)).toEqual(expected);
expect(await prettify(result, configObject)).toEqual(expected);
}
});
});

View file

@ -1,8 +1,8 @@
{
"compilerOptions": {
"outDir": "./lib",
"target": "ES6",
"module": "commonjs",
"target": "esnext",
"module": "NodeNext",
"moduleResolution": "node",
"lib": ["esnext"],
"declaration": true,