2021-04-13 10:57:08 +02:00
|
|
|
// Copyright: Ankitects Pty Ltd and contributors
|
|
|
|
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
|
|
|
|
|
2021-01-09 05:16:26 +01:00
|
|
|
import sqlFormatter from "@sqltools/formatter";
|
2021-04-22 18:43:35 +02:00
|
|
|
import { createPatch } from "diff";
|
2021-01-09 05:16:26 +01:00
|
|
|
import process from "process";
|
|
|
|
import path from "path";
|
|
|
|
import fs from "fs";
|
|
|
|
|
|
|
|
const workspace = process.env.BUILD_WORKSPACE_DIRECTORY;
|
|
|
|
const wantFix = workspace !== undefined;
|
|
|
|
|
|
|
|
function fixFile(relpath: string, newText: string): void {
|
|
|
|
const workspacePath = path.join(workspace!, relpath);
|
|
|
|
fs.writeFileSync(workspacePath, newText);
|
|
|
|
}
|
|
|
|
|
|
|
|
function formatText(text: string): string {
|
2021-09-07 02:22:22 +02:00
|
|
|
let newText: string = sqlFormatter.format(text, {
|
2021-01-09 05:16:26 +01:00
|
|
|
indent: " ",
|
|
|
|
reservedWordCase: "upper",
|
|
|
|
});
|
2021-09-07 02:22:22 +02:00
|
|
|
// downcase some keywords that Anki uses in tables/columns
|
|
|
|
for (const keyword of ["type", "fields"]) {
|
|
|
|
newText = newText.replace(
|
|
|
|
new RegExp(`\\b${keyword.toUpperCase()}\\b`, "g"),
|
2021-10-19 01:06:00 +02:00
|
|
|
keyword,
|
2021-09-07 02:22:22 +02:00
|
|
|
);
|
|
|
|
}
|
|
|
|
return newText;
|
2021-01-09 05:16:26 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
let errorFound = false;
|
|
|
|
for (const path of process.argv.slice(2)) {
|
|
|
|
const orig = fs.readFileSync(path).toString();
|
|
|
|
const formatted = formatText(orig);
|
|
|
|
if (orig !== formatted) {
|
|
|
|
if (wantFix) {
|
|
|
|
fixFile(path, formatted);
|
|
|
|
console.log(`Fixed ${path}`);
|
|
|
|
} else {
|
|
|
|
if (!errorFound) {
|
|
|
|
errorFound = true;
|
|
|
|
console.log("SQL formatting issues found:");
|
|
|
|
}
|
2021-04-22 18:43:35 +02:00
|
|
|
console.log(createPatch(path, orig, formatted));
|
2021-01-09 05:16:26 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (errorFound) {
|
|
|
|
console.log("Use 'bazel run //rslib:sql_format' to fix.");
|
|
|
|
console.log(process.env.BUILD_WORKSPACE_DIRECTORY);
|
|
|
|
process.exit(1);
|
|
|
|
}
|