Skip to content

Commit 38c84e0

Browse files
committed
Provide helper chdir method on the context object.
Fixes #6 Signed-off-by: Pedro Algarvio <[email protected]>
1 parent 6f595c8 commit 38c84e0

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

changelog/6.improvement.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Provide helper `chdir` method on the context object.

src/ptscripts/parser.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
import pathlib
1111
import sys
1212
import typing
13+
from collections.abc import Iterator
14+
from contextlib import contextmanager
1315
from functools import partial
1416
from subprocess import CompletedProcess
1517
from types import FunctionType
@@ -147,6 +149,21 @@ def run(
147149
capture=capture,
148150
)
149151

152+
@contextmanager
153+
def chdir(self, path: pathlib.Path) -> Iterator[pathlib.Path]:
154+
"""
155+
Change the current working directory to the provided path.
156+
"""
157+
cwd = pathlib.Path.cwd()
158+
try:
159+
os.chdir(path)
160+
yield path
161+
finally:
162+
if not cwd.exists():
163+
self.error(f"Unable to change back to path {cwd}")
164+
else:
165+
os.chdir(cwd)
166+
150167

151168
class Parser:
152169
"""

0 commit comments

Comments
 (0)