Skip to content
Source
Sign inSign up
samwillis/one-million-boxes
Open History to see the last commit

format-sql.ts

75 lines2.8 KB

1import { spawnSync } from "node:child_process"
2import { readFile, readdir, writeFile } from "node:fs/promises"
3import { createRequire } from "node:module"
4import { dirname, join, resolve } from "node:path"
5​
6const root = resolve(import.meta.dirname, "..")
7const require = createRequire(import.meta.url)
8const executable = join(dirname(require.resolve("pg-formatter")), "pg-formatter/pg_format")
9type CaseStyle = "unchanged" | "lowercase" | "uppercase" | "capitalize"
10const caseOptions: Record<CaseStyle, number> = {
11 unchanged: 0,
12 lowercase: 1,
13 uppercase: 2,
14 capitalize: 3,
16const config: {
17 spaces: number
18 wrapLimit: number
19 keepNewline: boolean
20 noSpaceFunction: boolean
21 keywordCase: CaseStyle
22 functionCase: CaseStyle
23 noRcFile: boolean
24 stripComments: boolean
25 placeholder: string
26} = JSON.parse(await readFile(join(root, ".pg-format.json"), "utf8"))
27const mode = process.argv[2]
28if (mode !== "--write" && mode !== "--check") throw new Error("Use --write or --check")
29​
30// Invoke pgFormatter directly to check its exit status; the npm wrapper's
31// format() API also concatenates stderr into its result on a failed invocation.
32const args = [
33 executable,
34 "--spaces",
35 String(config.spaces),
36 "--keyword-case",
37 String(caseOptions[config.keywordCase]),
38 "--function-case",
39 String(caseOptions[config.functionCase]),
41if (config.noRcFile) args.push("--no-rcfile")
42if (config.stripComments) args.push("--nocomment")
43if (config.wrapLimit) args.push("--wrap-limit", String(config.wrapLimit))
44if (config.keepNewline) args.push("--keep-newline")
45if (config.noSpaceFunction) args.push("--no-space-function")
46// pgFormatter 5.5 misindents nested bare RAISE in exception handlers. Preserve
47// that small, manually indented block using its supported placeholder option.
48if (config.placeholder) args.push("--placeholder", config.placeholder)
49​
50let needsFormatting = false
51for (const name of (await readdir(join(root, "server")))
52 .filter((name) => name.endsWith(".sql"))
53 .sort()) {
54 const path = join(root, "server", name)
55 const source = await readFile(path, "utf8")
56 const result = spawnSync("perl", args, { input: source, encoding: "utf8" })
57 if (result.error) throw result.error
58 if (result.status !== 0) throw new Error(`pgFormatter failed for ${name}: ${result.stderr}`)
59 // Line wrapping in pgFormatter can emit leading tabs even in spaces mode.
60 const formatted = result.stdout.replace(/^[ \t]+/gm, (indent) => {
61 let width = 0
62 for (const character of indent) width += character === "\t" ? 8 - (width % 8) : 1
63 return " ".repeat(width)
64 })
65 if (source === formatted) continue
66 if (mode === "--write") {
67 await writeFile(path, formatted)
68 console.log(`Formatted server/${name}`)
69 } else {
70 console.error(`Needs formatting: server/${name}`)
71 needsFormatting = true
72 }
74if (needsFormatting) process.exitCode = 1
75else console.log("SQL formatting passed")