From cb55b10a0ab92cdc94a72493a4cf9ac0f3bc6951 Mon Sep 17 00:00:00 2001 From: finswimmer Date: Wed, 6 Nov 2024 14:34:34 +0100 Subject: [PATCH] feat(cli): introduce --directory to actually switch the directory --- src/poetry/console/application.py | 33 ++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/src/poetry/console/application.py b/src/poetry/console/application.py index 1d20a21a052..70c37af9b88 100644 --- a/src/poetry/console/application.py +++ b/src/poetry/console/application.py @@ -1,6 +1,8 @@ from __future__ import annotations +import contextlib import logging +import os import re from contextlib import suppress @@ -25,6 +27,7 @@ if TYPE_CHECKING: from collections.abc import Callable + from collections.abc import Iterator from cleo.events.event import Event from cleo.io.inputs.argv_input import ArgvInput @@ -48,6 +51,17 @@ def _load() -> Command: return _load +@contextlib.contextmanager +def switch_working_directory(path: Path) -> Iterator[Path]: + original_cwd = Path.cwd() + os.chdir(path) + + try: + yield path + finally: + os.chdir(original_cwd) + + COMMANDS = [ "about", "add", @@ -172,7 +186,9 @@ def _run(self, io: IO) -> int: self._load_plugins(io) - exit_code: int = super()._run(io) + with switch_working_directory(self._directory): + exit_code: int = super()._run(io) + return exit_code def _configure_io(self, io: IO) -> None: @@ -367,12 +383,27 @@ def _default_definition(self) -> Definition: ) ) + definition.add_option( + Option( + "--directory", + "-C", + flag=False, + description=( + "The working directory for the Poetry command (defaults to the" + " current working directory)." + ), + ) + ) + return definition @cached_property def _directory(self) -> Path: if self._io and self._io.input.option("project"): return Path(self._io.input.option("project")).absolute() + elif self._io and self._io.input.option("directory"): + return Path(self._io.input.option("directory")).absolute() + return Path.cwd()