We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
feature: `--cwd` CLI option
### Feature scope

CLI (options, error messages, logging, etc.)

### Description

As seen in some other CLIs, it'd be nice to have a `--cwd` option which takes a path to a directory as an argument, and runs the program as-if it were invoked from that directory. This could be implemented by calling [`os.chdir`](https://docs.python.org/3/library/os.html#os.chdir) right after the CLI options are parsed if the `--cwd` option is provided.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `src/meltano/cli/cli.py`
Content:
```
1 """Definition of the top-level Click group for the Meltano CLI."""
2 
3 from __future__ import annotations
4 
5 import logging
6 import sys
7 from typing import NoReturn
8 
9 import click
10 
11 import meltano
12 from meltano.cli.utils import InstrumentedGroup
13 from meltano.core.behavior.versioned import IncompatibleVersionError
14 from meltano.core.error import MeltanoConfigurationError
15 from meltano.core.logging import LEVELS, setup_logging
16 from meltano.core.project import Project, ProjectNotFound
17 from meltano.core.project_settings_service import ProjectSettingsService
18 from meltano.core.tracking import CliContext, Tracker
19 from meltano.core.utils import get_no_color_flag
20 
21 logger = logging.getLogger(__name__)
22 
23 
24 class NoWindowsGlobbingGroup(InstrumentedGroup):
25     """A instrumented Click group that does not perform glob expansion on Windows.
26 
27     This restores the behaviour of Click's globbing to how it was before v8.
28     Click (as of version 8.1.3) ignores quotes around an asterisk, which makes
29     it behave differently than most shells that support globbing, and make some
30     typical Meltano commands fail, e.g. `meltano select tap-gitlab tags "*"`.
31     """
32 
33     def main(self, *args, **kwargs) -> NoReturn:
34         """Invoke the Click CLI with Windows globbing disabled.
35 
36         Args:
37             args: Positional arguments for the Click group.
38             kwargs: Keyword arguments for the Click group.
39         """
40         return super().main(*args, windows_expand_args=False, **kwargs)
41 
42 
43 @click.group(
44     cls=NoWindowsGlobbingGroup, invoke_without_command=True, no_args_is_help=True
45 )
46 @click.option("--log-level", type=click.Choice(LEVELS.keys()))
47 @click.option(
48     "--log-config", type=str, help="Path to a python logging yaml config file."
49 )
50 @click.option("-v", "--verbose", count=True, help="Not used.")
51 @click.option(
52     "--environment",
53     envvar="MELTANO_ENVIRONMENT",
54     help="Meltano environment name.",
55 )
56 @click.option(
57     "--no-environment", is_flag=True, default=False, help="Don't use any environment."
58 )
59 @click.version_option(version=meltano.__version__, prog_name="meltano")
60 @click.pass_context
61 def cli(  # noqa: WPS231
62     ctx: click.Context,
63     log_level: str,
64     log_config: str,
65     verbose: int,
66     environment: str,
67     no_environment: bool,
68 ):  # noqa: WPS231
69     """
70     ELT for the DataOps era.
71 
72     \b\nRead more at https://docs.meltano.com/reference/command-line-interface
73     """
74     ctx.ensure_object(dict)
75 
76     if log_level:
77         ProjectSettingsService.config_override["cli.log_level"] = log_level
78 
79     if log_config:
80         ProjectSettingsService.config_override["cli.log_config"] = log_config
81 
82     ctx.obj["verbosity"] = verbose
83 
84     no_color = get_no_color_flag()
85     if no_color:
86         ctx.color = False
87 
88     try:  # noqa: WPS229
89         project = Project.find()
90         setup_logging(project)
91         project_setting_service = ProjectSettingsService(project)
92 
93         readonly = project_setting_service.get("project_readonly")
94         if readonly:
95             project.readonly = True
96         if project.readonly:
97             logger.debug("Project is read-only.")
98 
99         # detect active environment
100         selected_environment = None
101         is_default_environment = False
102         if no_environment or (environment and environment.lower() == "null"):
103             logger.info("No environment is active")
104         elif environment:
105             selected_environment = environment
106         elif project_setting_service.get("default_environment"):
107             selected_environment = project_setting_service.get("default_environment")
108             is_default_environment = True
109         ctx.obj["selected_environment"] = selected_environment
110         ctx.obj["is_default_environment"] = is_default_environment
111         ctx.obj["project"] = project
112         ctx.obj["tracker"] = Tracker(project)
113         ctx.obj["tracker"].add_contexts(
114             CliContext.from_click_context(ctx)
115         )  # backfill the `cli` CliContext
116     except ProjectNotFound:
117         ctx.obj["project"] = None
118     except IncompatibleVersionError:
119         click.secho(
120             "This Meltano project is incompatible with this version of `meltano`.",
121             fg="yellow",
122         )
123         click.echo(
124             "For more details, visit https://docs.meltano.com/guide/installation#upgrading-meltano-version"
125         )
126         sys.exit(3)
127 
128 
129 def activate_environment(
130     ctx: click.Context, project: Project, required: bool = False
131 ) -> None:
132     """Activate the selected environment.
133 
134     The selected environment is whatever was selected with the `--environment`
135     option, or the default environment (set in `meltano.yml`) otherwise.
136 
137     Args:
138         ctx: The Click context, used to determine the selected environment.
139         project: The project for which the environment will be activated.
140     """
141     if ctx.obj["selected_environment"]:
142         project.activate_environment(ctx.obj["selected_environment"])
143     elif required:
144         raise MeltanoConfigurationError(
145             reason="A Meltano environment must be specified",
146             instruction="Set the `default_environment` option in "
147             "`meltano.yml`, or the `--environment` CLI option",
148         )
149 
150 
151 def activate_explicitly_provided_environment(
152     ctx: click.Context, project: Project
153 ) -> None:
154     """Activate the selected environment if it has been explicitly set.
155 
156     Some commands (e.g. `config`, `job`, etc.) do not respect the configured
157     `default_environment`, and will only run with an environment active if it
158     has been explicitly set (e.g. with the `--environment` CLI option).
159 
160     Args:
161         ctx: The Click context, used to determine the selected environment.
162         project: The project for which the environment will be activated.
163     """
164     if ctx.obj["is_default_environment"]:
165         logger.info(
166             f"The default environment {ctx.obj['selected_environment']!r} will "
167             f"be ignored for `meltano {ctx.command.name}`. To configure a specific "
168             "environment, please use the option `--environment=<environment name>`."
169         )
170         project.deactivate_environment()
171     else:
172         activate_environment(ctx, project)
173
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/src/meltano/cli/cli.py b/src/meltano/cli/cli.py
--- a/src/meltano/cli/cli.py
+++ b/src/meltano/cli/cli.py
@@ -3,7 +3,9 @@
 from __future__ import annotations
 
 import logging
+import os
 import sys
+from pathlib import Path
 from typing import NoReturn
 
 import click
@@ -56,6 +58,11 @@
 @click.option(
     "--no-environment", is_flag=True, default=False, help="Don't use any environment."
 )
+@click.option(
+    "--cwd",
+    type=click.Path(exists=True, file_okay=False, resolve_path=True, path_type=Path),
+    help="Run Meltano as if it had been started in the specified directory.",
+)
 @click.version_option(version=meltano.__version__, prog_name="meltano")
 @click.pass_context
 def cli(  # noqa: WPS231
@@ -65,6 +72,7 @@
     verbose: int,
     environment: str,
     no_environment: bool,
+    cwd: Path | None,
 ):  # noqa: WPS231
     """
     ELT for the DataOps era.
@@ -85,6 +93,12 @@
     if no_color:
         ctx.color = False
 
+    if cwd:
+        try:
+            os.chdir(cwd)
+        except OSError as ex:
+            raise Exception(f"Unable to run Meltano from {cwd!r}") from ex
+
     try:  # noqa: WPS229
         project = Project.find()
         setup_logging(project)

{"golden_diff": "diff --git a/src/meltano/cli/cli.py b/src/meltano/cli/cli.py\n--- a/src/meltano/cli/cli.py\n+++ b/src/meltano/cli/cli.py\n@@ -3,7 +3,9 @@\n from __future__ import annotations\n \n import logging\n+import os\n import sys\n+from pathlib import Path\n from typing import NoReturn\n \n import click\n@@ -56,6 +58,11 @@\n @click.option(\n     \"--no-environment\", is_flag=True, default=False, help=\"Don't use any environment.\"\n )\n+@click.option(\n+    \"--cwd\",\n+    type=click.Path(exists=True, file_okay=False, resolve_path=True, path_type=Path),\n+    help=\"Run Meltano as if it had been started in the specified directory.\",\n+)\n @click.version_option(version=meltano.__version__, prog_name=\"meltano\")\n @click.pass_context\n def cli(  # noqa: WPS231\n@@ -65,6 +72,7 @@\n     verbose: int,\n     environment: str,\n     no_environment: bool,\n+    cwd: Path | None,\n ):  # noqa: WPS231\n     \"\"\"\n     ELT for the DataOps era.\n@@ -85,6 +93,12 @@\n     if no_color:\n         ctx.color = False\n \n+    if cwd:\n+        try:\n+            os.chdir(cwd)\n+        except OSError as ex:\n+            raise Exception(f\"Unable to run Meltano from {cwd!r}\") from ex\n+\n     try:  # noqa: WPS229\n         project = Project.find()\n         setup_logging(project)\n", "issue": "feature: `--cwd` CLI option\n### Feature scope\n\nCLI (options, error messages, logging, etc.)\n\n### Description\n\nAs seen in some other CLIs, it'd be nice to have a `--cwd` option which takes a path to a directory as an argument, and runs the program as-if it were invoked from that directory. This could be implemented by calling [`os.chdir`](https://docs.python.org/3/library/os.html#os.chdir) right after the CLI options are parsed if the `--cwd` option is provided.\n", "before_files": [{"content": "\"\"\"Definition of the top-level Click group for the Meltano CLI.\"\"\"\n\nfrom __future__ import annotations\n\nimport logging\nimport sys\nfrom typing import NoReturn\n\nimport click\n\nimport meltano\nfrom meltano.cli.utils import InstrumentedGroup\nfrom meltano.core.behavior.versioned import IncompatibleVersionError\nfrom meltano.core.error import MeltanoConfigurationError\nfrom meltano.core.logging import LEVELS, setup_logging\nfrom meltano.core.project import Project, ProjectNotFound\nfrom meltano.core.project_settings_service import ProjectSettingsService\nfrom meltano.core.tracking import CliContext, Tracker\nfrom meltano.core.utils import get_no_color_flag\n\nlogger = logging.getLogger(__name__)\n\n\nclass NoWindowsGlobbingGroup(InstrumentedGroup):\n    \"\"\"A instrumented Click group that does not perform glob expansion on Windows.\n\n    This restores the behaviour of Click's globbing to how it was before v8.\n    Click (as of version 8.1.3) ignores quotes around an asterisk, which makes\n    it behave differently than most shells that support globbing, and make some\n    typical Meltano commands fail, e.g. `meltano select tap-gitlab tags \"*\"`.\n    \"\"\"\n\n    def main(self, *args, **kwargs) -> NoReturn:\n        \"\"\"Invoke the Click CLI with Windows globbing disabled.\n\n        Args:\n            args: Positional arguments for the Click group.\n            kwargs: Keyword arguments for the Click group.\n        \"\"\"\n        return super().main(*args, windows_expand_args=False, **kwargs)\n\n\n@click.group(\n    cls=NoWindowsGlobbingGroup, invoke_without_command=True, no_args_is_help=True\n)\n@click.option(\"--log-level\", type=click.Choice(LEVELS.keys()))\n@click.option(\n    \"--log-config\", type=str, help=\"Path to a python logging yaml config file.\"\n)\n@click.option(\"-v\", \"--verbose\", count=True, help=\"Not used.\")\n@click.option(\n    \"--environment\",\n    envvar=\"MELTANO_ENVIRONMENT\",\n    help=\"Meltano environment name.\",\n)\n@click.option(\n    \"--no-environment\", is_flag=True, default=False, help=\"Don't use any environment.\"\n)\n@click.version_option(version=meltano.__version__, prog_name=\"meltano\")\n@click.pass_context\ndef cli(  # noqa: WPS231\n    ctx: click.Context,\n    log_level: str,\n    log_config: str,\n    verbose: int,\n    environment: str,\n    no_environment: bool,\n):  # noqa: WPS231\n    \"\"\"\n    ELT for the DataOps era.\n\n    \\b\\nRead more at https://docs.meltano.com/reference/command-line-interface\n    \"\"\"\n    ctx.ensure_object(dict)\n\n    if log_level:\n        ProjectSettingsService.config_override[\"cli.log_level\"] = log_level\n\n    if log_config:\n        ProjectSettingsService.config_override[\"cli.log_config\"] = log_config\n\n    ctx.obj[\"verbosity\"] = verbose\n\n    no_color = get_no_color_flag()\n    if no_color:\n        ctx.color = False\n\n    try:  # noqa: WPS229\n        project = Project.find()\n        setup_logging(project)\n        project_setting_service = ProjectSettingsService(project)\n\n        readonly = project_setting_service.get(\"project_readonly\")\n        if readonly:\n            project.readonly = True\n        if project.readonly:\n            logger.debug(\"Project is read-only.\")\n\n        # detect active environment\n        selected_environment = None\n        is_default_environment = False\n        if no_environment or (environment and environment.lower() == \"null\"):\n            logger.info(\"No environment is active\")\n        elif environment:\n            selected_environment = environment\n        elif project_setting_service.get(\"default_environment\"):\n            selected_environment = project_setting_service.get(\"default_environment\")\n            is_default_environment = True\n        ctx.obj[\"selected_environment\"] = selected_environment\n        ctx.obj[\"is_default_environment\"] = is_default_environment\n        ctx.obj[\"project\"] = project\n        ctx.obj[\"tracker\"] = Tracker(project)\n        ctx.obj[\"tracker\"].add_contexts(\n            CliContext.from_click_context(ctx)\n        )  # backfill the `cli` CliContext\n    except ProjectNotFound:\n        ctx.obj[\"project\"] = None\n    except IncompatibleVersionError:\n        click.secho(\n            \"This Meltano project is incompatible with this version of `meltano`.\",\n            fg=\"yellow\",\n        )\n        click.echo(\n            \"For more details, visit https://docs.meltano.com/guide/installation#upgrading-meltano-version\"\n        )\n        sys.exit(3)\n\n\ndef activate_environment(\n    ctx: click.Context, project: Project, required: bool = False\n) -> None:\n    \"\"\"Activate the selected environment.\n\n    The selected environment is whatever was selected with the `--environment`\n    option, or the default environment (set in `meltano.yml`) otherwise.\n\n    Args:\n        ctx: The Click context, used to determine the selected environment.\n        project: The project for which the environment will be activated.\n    \"\"\"\n    if ctx.obj[\"selected_environment\"]:\n        project.activate_environment(ctx.obj[\"selected_environment\"])\n    elif required:\n        raise MeltanoConfigurationError(\n            reason=\"A Meltano environment must be specified\",\n            instruction=\"Set the `default_environment` option in \"\n            \"`meltano.yml`, or the `--environment` CLI option\",\n        )\n\n\ndef activate_explicitly_provided_environment(\n    ctx: click.Context, project: Project\n) -> None:\n    \"\"\"Activate the selected environment if it has been explicitly set.\n\n    Some commands (e.g. `config`, `job`, etc.) do not respect the configured\n    `default_environment`, and will only run with an environment active if it\n    has been explicitly set (e.g. with the `--environment` CLI option).\n\n    Args:\n        ctx: The Click context, used to determine the selected environment.\n        project: The project for which the environment will be activated.\n    \"\"\"\n    if ctx.obj[\"is_default_environment\"]:\n        logger.info(\n            f\"The default environment {ctx.obj['selected_environment']!r} will \"\n            f\"be ignored for `meltano {ctx.command.name}`. To configure a specific \"\n            \"environment, please use the option `--environment=<environment name>`.\"\n        )\n        project.deactivate_environment()\n    else:\n        activate_environment(ctx, project)\n", "path": "src/meltano/cli/cli.py"}], "after_files": [{"content": "\"\"\"Definition of the top-level Click group for the Meltano CLI.\"\"\"\n\nfrom __future__ import annotations\n\nimport logging\nimport os\nimport sys\nfrom pathlib import Path\nfrom typing import NoReturn\n\nimport click\n\nimport meltano\nfrom meltano.cli.utils import InstrumentedGroup\nfrom meltano.core.behavior.versioned import IncompatibleVersionError\nfrom meltano.core.error import MeltanoConfigurationError\nfrom meltano.core.logging import LEVELS, setup_logging\nfrom meltano.core.project import Project, ProjectNotFound\nfrom meltano.core.project_settings_service import ProjectSettingsService\nfrom meltano.core.tracking import CliContext, Tracker\nfrom meltano.core.utils import get_no_color_flag\n\nlogger = logging.getLogger(__name__)\n\n\nclass NoWindowsGlobbingGroup(InstrumentedGroup):\n    \"\"\"A instrumented Click group that does not perform glob expansion on Windows.\n\n    This restores the behaviour of Click's globbing to how it was before v8.\n    Click (as of version 8.1.3) ignores quotes around an asterisk, which makes\n    it behave differently than most shells that support globbing, and make some\n    typical Meltano commands fail, e.g. `meltano select tap-gitlab tags \"*\"`.\n    \"\"\"\n\n    def main(self, *args, **kwargs) -> NoReturn:\n        \"\"\"Invoke the Click CLI with Windows globbing disabled.\n\n        Args:\n            args: Positional arguments for the Click group.\n            kwargs: Keyword arguments for the Click group.\n        \"\"\"\n        return super().main(*args, windows_expand_args=False, **kwargs)\n\n\n@click.group(\n    cls=NoWindowsGlobbingGroup, invoke_without_command=True, no_args_is_help=True\n)\n@click.option(\"--log-level\", type=click.Choice(LEVELS.keys()))\n@click.option(\n    \"--log-config\", type=str, help=\"Path to a python logging yaml config file.\"\n)\n@click.option(\"-v\", \"--verbose\", count=True, help=\"Not used.\")\n@click.option(\n    \"--environment\",\n    envvar=\"MELTANO_ENVIRONMENT\",\n    help=\"Meltano environment name.\",\n)\n@click.option(\n    \"--no-environment\", is_flag=True, default=False, help=\"Don't use any environment.\"\n)\n@click.option(\n    \"--cwd\",\n    type=click.Path(exists=True, file_okay=False, resolve_path=True, path_type=Path),\n    help=\"Run Meltano as if it had been started in the specified directory.\",\n)\n@click.version_option(version=meltano.__version__, prog_name=\"meltano\")\n@click.pass_context\ndef cli(  # noqa: WPS231\n    ctx: click.Context,\n    log_level: str,\n    log_config: str,\n    verbose: int,\n    environment: str,\n    no_environment: bool,\n    cwd: Path | None,\n):  # noqa: WPS231\n    \"\"\"\n    ELT for the DataOps era.\n\n    \\b\\nRead more at https://docs.meltano.com/reference/command-line-interface\n    \"\"\"\n    ctx.ensure_object(dict)\n\n    if log_level:\n        ProjectSettingsService.config_override[\"cli.log_level\"] = log_level\n\n    if log_config:\n        ProjectSettingsService.config_override[\"cli.log_config\"] = log_config\n\n    ctx.obj[\"verbosity\"] = verbose\n\n    no_color = get_no_color_flag()\n    if no_color:\n        ctx.color = False\n\n    if cwd:\n        try:\n            os.chdir(cwd)\n        except OSError as ex:\n            raise Exception(f\"Unable to run Meltano from {cwd!r}\") from ex\n\n    try:  # noqa: WPS229\n        project = Project.find()\n        setup_logging(project)\n        project_setting_service = ProjectSettingsService(project)\n\n        readonly = project_setting_service.get(\"project_readonly\")\n        if readonly:\n            project.readonly = True\n        if project.readonly:\n            logger.debug(\"Project is read-only.\")\n\n        # detect active environment\n        selected_environment = None\n        is_default_environment = False\n        if no_environment or (environment and environment.lower() == \"null\"):\n            logger.info(\"No environment is active\")\n        elif environment:\n            selected_environment = environment\n        elif project_setting_service.get(\"default_environment\"):\n            selected_environment = project_setting_service.get(\"default_environment\")\n            is_default_environment = True\n        ctx.obj[\"selected_environment\"] = selected_environment\n        ctx.obj[\"is_default_environment\"] = is_default_environment\n        ctx.obj[\"project\"] = project\n        ctx.obj[\"tracker\"] = Tracker(project)\n        ctx.obj[\"tracker\"].add_contexts(\n            CliContext.from_click_context(ctx)\n        )  # backfill the `cli` CliContext\n    except ProjectNotFound:\n        ctx.obj[\"project\"] = None\n    except IncompatibleVersionError:\n        click.secho(\n            \"This Meltano project is incompatible with this version of `meltano`.\",\n            fg=\"yellow\",\n        )\n        click.echo(\n            \"For more details, visit https://docs.meltano.com/guide/installation#upgrading-meltano-version\"\n        )\n        sys.exit(3)\n\n\ndef activate_environment(\n    ctx: click.Context, project: Project, required: bool = False\n) -> None:\n    \"\"\"Activate the selected environment.\n\n    The selected environment is whatever was selected with the `--environment`\n    option, or the default environment (set in `meltano.yml`) otherwise.\n\n    Args:\n        ctx: The Click context, used to determine the selected environment.\n        project: The project for which the environment will be activated.\n    \"\"\"\n    if ctx.obj[\"selected_environment\"]:\n        project.activate_environment(ctx.obj[\"selected_environment\"])\n    elif required:\n        raise MeltanoConfigurationError(\n            reason=\"A Meltano environment must be specified\",\n            instruction=\"Set the `default_environment` option in \"\n            \"`meltano.yml`, or the `--environment` CLI option\",\n        )\n\n\ndef activate_explicitly_provided_environment(\n    ctx: click.Context, project: Project\n) -> None:\n    \"\"\"Activate the selected environment if it has been explicitly set.\n\n    Some commands (e.g. `config`, `job`, etc.) do not respect the configured\n    `default_environment`, and will only run with an environment active if it\n    has been explicitly set (e.g. with the `--environment` CLI option).\n\n    Args:\n        ctx: The Click context, used to determine the selected environment.\n        project: The project for which the environment will be activated.\n    \"\"\"\n    if ctx.obj[\"is_default_environment\"]:\n        logger.info(\n            f\"The default environment {ctx.obj['selected_environment']!r} will \"\n            f\"be ignored for `meltano {ctx.command.name}`. To configure a specific \"\n            \"environment, please use the option `--environment=<environment name>`.\"\n        )\n        project.deactivate_environment()\n    else:\n        activate_environment(ctx, project)\n", "path": "src/meltano/cli/cli.py"}]}