Skip to content

Commit

Permalink
feat(cli): introduce --directory to actually switch the directory
Browse files Browse the repository at this point in the history
  • Loading branch information
finswimmer committed Nov 6, 2024
1 parent 6c05c10 commit cb55b10
Showing 1 changed file with 32 additions and 1 deletion.
33 changes: 32 additions & 1 deletion src/poetry/console/application.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from __future__ import annotations

import contextlib
import logging
import os
import re

from contextlib import suppress
Expand All @@ -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
Expand All @@ -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",
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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()


Expand Down

0 comments on commit cb55b10

Please sign in to comment.