Skip to content

Commit b8455d7

Browse files
committed
Allow defining inline JSON config object in command line
Fixes #701
1 parent edffcbb commit b8455d7

File tree

2 files changed

+20
-11
lines changed

2 files changed

+20
-11
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ optional arguments:
110110
-l, --language {bigquery,db2,db2i,hive,mariadb,mysql,n1ql,plsql,postgresql,redshift,singlestoredb,snowflake,spark,sql,sqlite,trino,tsql}
111111
SQL dialect (defaults to basic sql)
112112
-c, --config CONFIG
113-
Path to config json file (will use default configs if unspecified)
113+
Path to config JSON file or json string (will use default configs if unspecified)
114114
--version show program's version number and exit
115115
```
116116

bin/sql-formatter-cli.cjs

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ class SqlFormatterCli {
5252
});
5353

5454
parser.add_argument('-c', '--config', {
55-
help: 'Path to config json file (will use default configs if unspecified)',
55+
help: 'Path to config JSON file or json string (will use default configs if unspecified)',
5656
});
5757

5858
parser.add_argument('--version', {
@@ -73,19 +73,28 @@ class SqlFormatterCli {
7373
}
7474

7575
if (this.args.config) {
76+
// First, try to parse --config value as a JSON string
7677
try {
77-
const configFile = await this.readFile(this.args.config);
78-
const configJson = JSON.parse(configFile);
78+
const configJson = JSON.parse(this.args.config);
7979
return { language: this.args.language, ...configJson };
8080
} catch (e) {
81-
if (e instanceof SyntaxError) {
82-
console.error(`Error: unable to parse JSON at file ${this.args.config}`);
83-
process.exit(1);
81+
// If that fails, try to read the --config value as a file
82+
try {
83+
const configFile = await this.readFile(this.args.config);
84+
const configJson = JSON.parse(configFile);
85+
return { language: this.args.language, ...configJson };
86+
} catch (e) {
87+
if (e instanceof SyntaxError) {
88+
console.error(
89+
`Error: unable to parse as JSON or treat as JSON file: ${this.args.config}`
90+
);
91+
process.exit(1);
92+
}
93+
this.exitWhenIOError(e);
94+
console.error('An unknown error has occurred, please file a bug report at:');
95+
console.log('https://github.com/sql-formatter-org/sql-formatter/issues\n');
96+
throw e;
8497
}
85-
this.exitWhenIOError(e);
86-
console.error('An unknown error has occurred, please file a bug report at:');
87-
console.log('https://github.com/sql-formatter-org/sql-formatter/issues\n');
88-
throw e;
8998
}
9099
}
91100
return {

0 commit comments

Comments
 (0)