From b8455d7930ed83c482fa29f408786a2f06e4f3e5 Mon Sep 17 00:00:00 2001 From: Rene Saarsoo Date: Sun, 21 Jan 2024 14:10:13 +0200 Subject: [PATCH] Allow defining inline JSON config object in command line Fixes #701 --- README.md | 2 +- bin/sql-formatter-cli.cjs | 29 +++++++++++++++++++---------- 2 files changed, 20 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index c557f19796..4102b98ff2 100644 --- a/README.md +++ b/README.md @@ -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 ``` diff --git a/bin/sql-formatter-cli.cjs b/bin/sql-formatter-cli.cjs index dd4ef52543..6eb8339067 100755 --- a/bin/sql-formatter-cli.cjs +++ b/bin/sql-formatter-cli.cjs @@ -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', { @@ -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 {