"""Utilities for benchmarks."""

from pathlib import Path
import os
import tempfile


class ChdirTemporaryDirectory(tempfile.TemporaryDirectory):
    """
    Context manager to create and change to a temporary directory.

    On exit, returns to the previous working directory.
    """

    def __enter__(self) -> Path:
        """Create and change to a temporary directory."""
        self._prev_cwd = os.getcwd()
        path = super().__enter__()
        os.chdir(path)
        return path

    def __exit__(self, exc_type, exc_value, traceback):
        """Return to the previous directory and clean up."""
        os.chdir(self._prev_cwd)
        return super().__exit__(exc_type, exc_value, traceback)
