Skip to content

Commit

Permalink
Allow defining inline JSON config object in command line
Browse files Browse the repository at this point in the history
Fixes #701
  • Loading branch information
nene committed Jan 21, 2024
1 parent edffcbb commit b8455d7
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 11 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ optional arguments:
-l, --language {bigquery,db2,db2i,hive,mariadb,mysql,n1ql,plsql,postgresql,redshift,singlestoredb,snowflake,spark,sql,sqlite,trino,tsql}
SQL dialect (defaults to basic sql)
-c, --config CONFIG
Path to config json file (will use default configs if unspecified)
Path to config JSON file or json string (will use default configs if unspecified)
--version show program's version number and exit
```

Expand Down
29 changes: 19 additions & 10 deletions bin/sql-formatter-cli.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ class SqlFormatterCli {
});

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

parser.add_argument('--version', {
Expand All @@ -73,19 +73,28 @@ class SqlFormatterCli {
}

if (this.args.config) {
// First, try to parse --config value as a JSON string
try {
const configFile = await this.readFile(this.args.config);
const configJson = JSON.parse(configFile);
const configJson = JSON.parse(this.args.config);
return { language: this.args.language, ...configJson };
} catch (e) {
if (e instanceof SyntaxError) {
console.error(`Error: unable to parse JSON at file ${this.args.config}`);
process.exit(1);
// If that fails, try to read the --config value as a file
try {
const configFile = await this.readFile(this.args.config);
const configJson = JSON.parse(configFile);
return { language: this.args.language, ...configJson };
} catch (e) {
if (e instanceof SyntaxError) {
console.error(
`Error: unable to parse as JSON or treat as JSON file: ${this.args.config}`
);
process.exit(1);
}
this.exitWhenIOError(e);
console.error('An unknown error has occurred, please file a bug report at:');
console.log('https://github.com/sql-formatter-org/sql-formatter/issues\n');
throw e;
}
this.exitWhenIOError(e);
console.error('An unknown error has occurred, please file a bug report at:');
console.log('https://github.com/sql-formatter-org/sql-formatter/issues\n');
throw e;
}
}
return {
Expand Down

0 comments on commit b8455d7

Please sign in to comment.