gajus / pg-formatter

A PostgreSQL SQL syntax beautifier.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Create a CLI interface

gajus opened this issue ยท comments

Create a CLI interface.

Hi! I rolled my own CLI for a project. I'd be happy to work on this.

Could the configuration options be set using something like cosmiconfig? It's easier to maintain in this repo than a bunch of CLI flags, and arguably more convenient for users to specify.

For consistency, I use https://www.npmjs.com/package/yargs in all my open-source projects. It looks interchangeable with cosmiconfig.

I don't think yargs handles config files, only command-line arguments, so what I'm suggesting is using them in combination. The CLI flags could handle things like the filenames, and maybe anonymize which might be on or off for different invocations, while the more extensive and expressive part of the config, like which formatting options to use, could live in the config file.

yargs could be integrated with cosmiconfig using yargs.config() or similar (see saffron for an example)

Interesting. I've never used any of those libraries so it might be a lot to dig through. Though I'm game to give it a shot.

Just for reference, here's what I currently use:

import { format } from "pg-formatter";
import * as fs from "fs";
const files = process.argv.slice(2);
const fix = !!process.env.fix;

const errors: string[] = [];
for (const file of files) {
	const content = fs.readFileSync(file, "utf8");
	// console.time("checking file " + file);
	const content2 = format(content, {
		keywordCase: "lowercase",
		noGrouping: true,
		tabs: false // because pasting tabs into psql prompt causes autocomplete
	});

	// console.timeEnd("checking file " + file);
	if (content !== content2) {
		if (fix) fs.writeFileSync(file, content2);
		else errors.push(file);
	}
}

if (errors.length > 0) {
	console.error("The following SQL files are not formatted. Please use `fix=1 ts-node check-pg-format.ts` to fix.");
	console.error(errors.join("\n"));
	process.exit(1);
}

It's not general enough to make a PR, but works for me.

I run this in CI in parallel using:

git ls-files '*.sql' | xargs -n1 -P8 yarn ts-node --transpile-only util/check-pg-format.ts

It can fix all by prefixing with fix=1

๐ŸŽ‰ This issue has been resolved in version 1.3.0 ๐ŸŽ‰

The release is available on:

Your semantic-release bot ๐Ÿ“ฆ๐Ÿš€