Repository: dbt-labs/dbt-core

Issue:
[CT-1926] Add support for --version to click cli
Using [click's options and callbacks](https://click.palletsprojects.com/en/8.1.x/options/#callbacks-and-eager-options), add support for `--version` to the new click cli.

NOTE: We use dbt --version as part of the Code Quality check in GHA.  Since it's not working currently that has been disabled [here](https://github.com/dbt-labs/dbt-core/commit/1ead5ac2b29220d6a06d2425f1aabeeead51db60).  Please un-comment that part of the workflow when this ticket is ready to go.


Discussion:

Resolving patch:
diff --git a/core/dbt/cli/main.py b/core/dbt/cli/main.py
--- a/core/dbt/cli/main.py
+++ b/core/dbt/cli/main.py
@@ -1,5 +1,4 @@
 from copy import copy
-from pprint import pformat as pf  # This is temporary for RAT-ing
 from typing import List, Tuple, Optional
 
 import click
@@ -22,6 +21,7 @@
 from dbt.task.build import BuildTask
 from dbt.task.generate import GenerateTask
 from dbt.task.init import InitTask
+from dbt.version import __version__, get_version_information
 
 
 # CLI invocation
@@ -34,6 +34,10 @@ class dbtUsageException(Exception):
     pass
 
 
+class dbtInternalException(Exception):
+    pass
+
+
 # Programmatic invocation
 class dbtRunner:
     def __init__(
@@ -52,6 +56,11 @@ def invoke(self, args: List[str]) -> Tuple[Optional[List], bool]:
                 "manifest": self.manifest,
             }
             return cli.invoke(dbt_ctx)
+        except click.exceptions.Exit as e:
+            # 0 exit code, expected for --version early exit
+            if str(e) == "0":
+                return [], True
+            raise dbtInternalException(f"unhandled exit code {str(e)}")
         except (click.NoSuchOption, click.UsageError) as e:
             raise dbtUsageException(e.message)
 
@@ -64,6 +73,7 @@ def invoke(self, args: List[str]) -> Tuple[Optional[List], bool]:
     epilog="Specify one of these sub-commands and you can find more help from there.",
 )
 @click.pass_context
+@click.version_option(version=__version__, message=get_version_information())
 @p.anonymous_usage_stats
 @p.cache_selected_only
 @p.debug
@@ -82,7 +92,6 @@ def invoke(self, args: List[str]) -> Tuple[Optional[List], bool]:
 @p.static_parser
 @p.use_colors
 @p.use_experimental_parser
-@p.version
 @p.version_check
 @p.warn_error
 @p.warn_error_options
@@ -91,10 +100,6 @@ def cli(ctx, **kwargs):
     """An ELT tool for managing your SQL transformations and data models.
     For more documentation on these commands, visit: docs.getdbt.com
     """
-    # Version info
-    if ctx.params["version"]:
-        click.echo(f"`version` called\n ctx.params: {pf(ctx.params)}")
-        return
 
 
 # dbt build
diff --git a/core/dbt/cli/params.py b/core/dbt/cli/params.py
--- a/core/dbt/cli/params.py
+++ b/core/dbt/cli/params.py
@@ -377,12 +377,6 @@
     default="{}",
 )
 
-version = click.option(
-    "--version",
-    envvar=None,
-    help="Show version information",
-    is_flag=True,
-)
 
 version_check = click.option(
     "--version-check/--no-version-check",


Test patch:
diff --git a/tests/unit/test_cli_flags.py b/tests/unit/test_cli_flags.py
--- a/tests/unit/test_cli_flags.py
+++ b/tests/unit/test_cli_flags.py
@@ -34,6 +34,8 @@ def test_mp_context(self, run_context):
     @pytest.mark.parametrize("param", cli.params)
     def test_cli_group_flags_from_params(self, run_context, param):
         flags = Flags(run_context)
+        if param.name.upper() == "VERSION":
+            return
         assert hasattr(flags, param.name.upper())
         assert getattr(flags, param.name.upper()) == run_context.params[param.name.lower()]