LibCST/libcst/helpers/paths.py
Amethyst Reese c876db6d2d Add new FilePathProvider
Caches file path information on the root `Module` node.
Resolves paths when caching, so they are always absolute paths.

Adds a new `chdir` helper to change working directory and automatically
revert to previous directory, which makes testing file paths with the
`"."` repo root easier.

ghstack-source-id: 3413905fc1
Pull Request resolved: https://github.com/Instagram/LibCST/pull/892
2023-03-13 18:33:46 -07:00

25 lines
635 B
Python

# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
from contextlib import contextmanager
from pathlib import Path
from typing import Generator
from libcst._types import StrPath
@contextmanager
def chdir(path: StrPath) -> Generator[Path, None, None]:
"""
Temporarily chdir to the given path, and then return to the previous path.
"""
try:
path = Path(path).resolve()
cwd = os.getcwd()
os.chdir(path)
yield path
finally:
os.chdir(cwd)