Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Upgrade to prettier 3 #11

Merged
merged 14 commits into from
Dec 10, 2023
2 changes: 1 addition & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ jobs:

strategy:
matrix:
node-version: [16.x]
node-version: [20.x]

steps:
- uses: actions/checkout@v3
Expand Down
9 changes: 5 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,22 +21,23 @@
"prepublishOnly": "yarn test && yarn build",
"clean": "rm -rf dist",
"build": "yarn clean && tsc",
"test": "jest"
"test": "yarn node --experimental-vm-modules $(yarn bin jest)",
"pretty": "prettier -w src/"
},
"keywords": [
"prettier",
"sql",
"plugin"
],
"dependencies": {
"prettier": "^2.8.2",
"prettier": "^3.0.3",
"sql-parser-cst": "^0.17.1"
},
"devDependencies": {
"@types/jest": "^29.2.5",
"dedent-js": "^1.0.1",
"jest": "^29.3.1",
"ts-jest": "^29.0.3",
"jest": "^29.7.0",
"ts-jest": "^29.1.1",
"typescript": "^4.9.4"
}
}
2 changes: 1 addition & 1 deletion src/CstToDocMap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export type ToDocFn<TNode> = (
print: PrintFn<TNode>,
node: TNode,
path: AstPath<TNode>,
options: AllPrettierOptions<TNode>
options: AllPrettierOptions<TNode>,
) => Doc;

export type CstToDocMap<TNode extends Node> = {
Expand Down
45 changes: 21 additions & 24 deletions src/embedJs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,8 @@ import {
} from "./node_utils";
import { hardline, indent, stripTrailingHardline } from "./print_utils";

export const embedJs: NonNullable<Printer<Node>["embed"]> = (
path,
print,
textToDoc,
options
) => {
const node = path.getValue();
export const embedJs: NonNullable<Printer<Node>["embed"]> = (path, options) => {
const node = path.getValue(); // TODO: Don't use deprecated method
const parent = path.getParentNode(0);
const grandParent = path.getParentNode(1);
if (
Expand All @@ -23,30 +18,32 @@ export const embedJs: NonNullable<Printer<Node>["embed"]> = (
isCreateFunctionStmt(grandParent) &&
grandParent.clauses.some(isJavaScriptLanguageClause)
) {
const quotes = detectQuotes(node.value);
if (!quotes) {
// Give up for now. Don't format JavaScript inside the string.
// Perhaps tackle this corner-case in the future.
return null;
}
return async (textToDoc) => {
const quotes = detectQuotes(node.value);
if (!quotes) {
// Give up for now. Don't format JavaScript inside the string.
// Perhaps tackle this corner-case in the future.
return undefined;
}

const js = textToDoc(node.value, {
...options,
parser: "babel",
});
const js = await textToDoc(node.value, {
...options,
parser: "babel",
});

return [
quotes[0],
indent([hardline, stripTrailingHardline(js)]),
hardline,
quotes[1],
];
return [
quotes[0],
indent([hardline, stripTrailingHardline(js)]),
hardline,
quotes[1],
];
};
}
return null;
};

const isJavaScriptLanguageClause = (
clause: CreateFunctionStmt["clauses"][0]
clause: CreateFunctionStmt["clauses"][0],
): boolean => isLanguageClause(clause) && clause.name.name === "js";

// Whether to quote the code with single- or double-quotes.
Expand Down
48 changes: 24 additions & 24 deletions src/embedJson.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,33 +10,33 @@ import {

export const embedJson: NonNullable<Printer<Node>["embed"]> = (
path,
print,
textToDoc,
options
options,
) => {
const node = path.getValue();
const node = path.getValue(); // TODO: Don't use deprecated method
const parent = path.getParentNode();
if (isStringLiteral(node) && isJsonLiteral(parent)) {
if (
containsTripleQuote(node.value) ||
containsBackslash(node.value) ||
isRawString(node)
) {
// Give up for now. Don't format JSON inside the string.
// Tackle these corner-case in the future.
return null;
}
const json = textToDoc(node.value, {
...options,
parser: "json",
});
const inlineQuote = containsSingleQuote(node.value) ? "'''" : "'";
return [
ifBreak("'''", inlineQuote),
indent([softline, stripTrailingHardline(json)]),
softline,
ifBreak("'''", inlineQuote),
];
return async (textToDoc) => {
if (
containsTripleQuote(node.value) ||
containsBackslash(node.value) ||
isRawString(node)
) {
// Give up for now. Don't format JSON inside the string.
// Tackle these corner-case in the future.
return undefined;
}
const json = await textToDoc(node.value, {
...options,
parser: "json",
});
const inlineQuote = containsSingleQuote(node.value) ? "'''" : "'";
return [
ifBreak("'''", inlineQuote),
indent([softline, stripTrailingHardline(json)]),
softline,
ifBreak("'''", inlineQuote),
];
};
}
return null;
};
Expand Down
4 changes: 2 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export const languages: SupportLanguage[] = [
];

const createParser = (dialect: DialectName): Parser<Node> => ({
parse: (text, parsers, options) =>
parse: (text, options) =>
transformCst(
parse(text, {
dialect,
Expand All @@ -32,7 +32,7 @@ const createParser = (dialect: DialectName): Parser<Node> => ({
filename: options.filepath,
paramTypes: (options as AllPrettierOptions<Node>).sqlParamTypes,
}),
text
text,
),
astFormat: "sql-cst",
locStart: (node) => node.range?.[0] as number,
Expand Down
16 changes: 12 additions & 4 deletions src/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,25 +13,33 @@ export const options: SupportOptions = {
sqlKeywordCase: {
type: "choice",
category: "SQL",
since: "0.1.0",
default: "upper",
description: "Enforces upper/lower case for SQL keywords",
choices: [
{
value: "preserve",
description: "preserves the existing case",
since: "0.1.0",
},
{
value: "upper",
description: "forces all keywords to uppercase",
since: "0.1.0",
},
{
value: "lower",
description: "forces all keywords to lowercase",
since: "0.1.0",
},
{ value: "upper", description: "forces all keywords to uppercase" },
{ value: "lower", description: "forces all keywords to lowercase" },
],
},
sqlParamTypes: {
type: "string",
array: true,
category: "SQL",
since: "0.7.0",
default: [{ value: [] }],
description: "Syntax for bound parameters",
// Since 0.7.0
// Possible values in array: "?" | "?nr" | ":name" | "$name" | "@name"
},
};
8 changes: 4 additions & 4 deletions src/printSql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { join } from "./print_utils";
export function printSql(
path: AstPath<Node>,
options: AllPrettierOptions,
oldPrint: OldPrintFn
oldPrint: OldPrintFn,
): Doc {
return printNode(path, options, createPrintFn(path, oldPrint));
}
Expand All @@ -20,7 +20,7 @@ let cachedPath: AstPath<Node>;

function createPrintFn(
path: AstPath<Node>,
oldPrint: OldPrintFn
oldPrint: OldPrintFn,
): PrintFn<Node> {
// The path parameter will reference the same AstPath instance
// during the whole printing cycle.
Expand All @@ -41,7 +41,7 @@ function createPrintFn(
}) as PrintFn<Node>;

cachedPrintFn.spaced = (
selector: PrintableKey<Node> | PrintableKey<Node>[]
selector: PrintableKey<Node> | PrintableKey<Node>[],
): Doc[] => {
const node = path.getValue();
const docs = arrayWrap(selector)
Expand All @@ -60,7 +60,7 @@ function createPrintFn(
function printNode(
path: AstPath<Node>,
options: AllPrettierOptions,
print: PrintFn<Node>
print: PrintFn<Node>,
): Doc {
const node = path.getValue();

Expand Down
8 changes: 4 additions & 4 deletions src/print_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,28 +24,28 @@ export const join = (sep: Doc, docs: Doc): Doc =>
/** True when the Node contains a newline in original source code */
export const containsNewline = (
node: Node,
opts: { originalText: string }
opts: { originalText: string },
): boolean => {
if (!node.range) {
throw new Error("containsNewline() expected a Node with range info");
}
return util.hasNewlineInRange(
opts.originalText,
node.range[0],
node.range[1]
node.range[1],
);
};

export const hasEmptyLineBetweenNodes = (
node1: Node,
node2: Node,
opts: { originalText: string }
opts: { originalText: string },
): boolean => {
if (!node1.range || !node2.range) {
throw new Error("emptyLineBetweenNodes() expects Nodes with range info");
}

return /\n[ \t]*\r?\n/.test(
opts.originalText.slice(node1.range[1], node2.range[0])
opts.originalText.slice(node1.range[1], node2.range[0]),
);
};
2 changes: 1 addition & 1 deletion src/syntax/constraint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export const constraintMap: Partial<CstToDocMap<AllConstraintNodes>> = {

const printUnnamedConstraint = <T>(
print: PrintFn<Constraint<T>>,
node: Constraint<T>
node: Constraint<T>,
): Doc => {
if (node.deferrable) {
return group([
Expand Down
2 changes: 1 addition & 1 deletion src/syntax/function.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export const functionMap: Partial<CstToDocMap<AllFunctionNodes>> = {
hardline,
join(
hardline,
print("clauses").map((cls) => group(cls))
print("clauses").map((cls) => group(cls)),
),
],
],
Expand Down
2 changes: 1 addition & 1 deletion src/syntax/procedure.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export const procedureMap: Partial<CstToDocMap<AllProcedureNodes>> = {
hardline,
join(
hardline,
print("clauses").map((clause) => group(clause))
print("clauses").map((clause) => group(clause)),
),
],
procedure_param: (print) => print.spaced(["mode", "name", "dataType"]),
Expand Down
4 changes: 2 additions & 2 deletions src/syntax/program.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,15 @@ import { AllPrettierOptions } from "src/options";
export const programMap: CstToDocMap<Program> = {
program: (print, node, path, options) =>
print("statements").map((doc, i) =>
printStatement(doc, i, node.statements, options)
printStatement(doc, i, node.statements, options),
),
};

const printStatement = (
doc: Doc,
i: number,
statements: Node[],
options: AllPrettierOptions<Program>
options: AllPrettierOptions<Program>,
): Doc => {
const prevNode = statements[i - 1];
const node = statements[i];
Expand Down
12 changes: 6 additions & 6 deletions src/syntax/select.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export const selectMap: Partial<CstToDocMap<AllSelectNodes>> = {
? indent([line, print(["specification"])])
: [],
],
])
]),
),
];
}
Expand All @@ -74,7 +74,7 @@ export const selectMap: Partial<CstToDocMap<AllSelectNodes>> = {
group(print("aggregations")),
print.spaced(["forKw", "inputColumn"]),
print.spaced(["inKw", "pivotColumns"]),
])
]),
),
unpivot_expr: (print, node) => [
print("left"),
Expand All @@ -91,7 +91,7 @@ export const selectMap: Partial<CstToDocMap<AllSelectNodes>> = {
print("valuesColumn"),
print.spaced(["forKw", "nameColumn"]),
print.spaced(["inKw", "unpivotColumns"]),
])
]),
),
tablesample_expr: (print) =>
group([print("left"), line, print.spaced(["tablesampleKw", "args"])]),
Expand Down Expand Up @@ -141,15 +141,15 @@ export const selectMap: Partial<CstToDocMap<AllSelectNodes>> = {
return group(
join(
lineType,
print(["baseWindowName", "partitionBy", "orderBy", "frame"])
)
print(["baseWindowName", "partitionBy", "orderBy", "frame"]),
),
);
},
};

const printLimitValues = (
print: PrintFn<LimitClause>,
node: LimitClause
node: LimitClause,
): Doc => {
if (node.offsetKw) {
return print.spaced(["count", "offsetKw", "offset"]);
Expand Down
2 changes: 1 addition & 1 deletion src/transform/addFinalSemicolon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { last } from "../utils";

export const addFinalSemicolon = (
program: Program,
originalText: string
originalText: string,
): Program => {
if (!isEmpty(last(program.statements))) {
const end = originalText.length;
Expand Down
Loading