This repository has been archived by the owner on Mar 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
59 lines (51 loc) · 1.41 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import * as fs from 'fs';
import sqlFormatter from 'sql-formatter';
import optimist from 'optimist';
let command = optimist
.usage('SQL formatter')
.default('i', '-')
.default('o', '-')
.default('s', 'sql')
.alias('i', 'file')
.alias('o', 'out')
.alias('s', 'sql')
.alias('h', 'help')
.describe('i', 'Load a file. "-" - stdin')
.describe('s', 'Sql dialect: "sql" Standard SQL, "n1ql" Couchbase N1QL, "db2" IBM DB2, "pl/sql" Oracle PL/SQL')
.describe('o', 'Output file name. "-" - stdout');
let argv = command.argv;
if (argv.h) {
command.showHelp();
process.exit();
}
const supportedDialects = ['sql', 'n1ql', 'db2', 'pl/sql'];
const dialect = argv.s;
if (!~supportedDialects.indexOf(dialect)) {
console.error(`Dialect "${dialect}" does not supported. Supported: ` + supportedDialects.join(', '));
process.exit(1);
}
let options = {
language: dialect
};
let inFile = argv.i;
let outFile = argv.o;
let data = '';
if (inFile == '-') {
let input = process.stdin;
input.resume();
input.setEncoding('utf8');
input.on('data', chunk => data += chunk);
input.on('end', () => {
format(data);
});
} else {
format(fs.readFileSync(inFile, 'utf8'));
}
function format(data) {
const formatted = sqlFormatter.format(data, options);
if (outFile == '-') {
console.log(formatted);
} else {
fs.writeFileSync(outFile, formatted, 'utf8');
}
}