Skip to content

Commit

Permalink
Operate in temporary directory (#68)
Browse files Browse the repository at this point in the history
* add decorator that executes the action in a temporary directory
* log the git working directory
  • Loading branch information
jdkandersson authored Jan 23, 2023
1 parent c9beef9 commit a2759c2
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
37 changes: 37 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,16 @@

"""Main execution for the action."""

import functools
import json
import logging
import os
import pathlib
import shutil
import tempfile
import typing
from functools import partial
from pathlib import Path

from src import GETTING_STARTED, exceptions, run, types_
from src.discourse import create_discourse
Expand Down Expand Up @@ -87,6 +92,38 @@ def _write_github_output(urls_with_actions_dict: dict[str, str]) -> None:
)


def execute_in_tmpdir(func: typing.Callable[[], None]) -> typing.Callable[[], None]:
"""Execute a function in a temporary directory.
Makes a copy of the current working directory in a temporary directory, changes the working
directory to that directory, executes the function, changes the working directory back and
deletes the temporary directory.
Args:
func: The function to run in a temporary directory.
Returns:
The wrapper for the function that executes it in a temporary directory.
"""

@functools.wraps(func)
def wrapper() -> None:
"""Replacement function."""
initial_cwd = Path.cwd()
try:
with tempfile.TemporaryDirectory() as tempdir_name:
tempdir = Path(tempdir_name)
execute_cwd = tempdir / "cwd"
shutil.copytree(src=initial_cwd, dst=execute_cwd)
os.chdir(execute_cwd)
func()
finally:
os.chdir(initial_cwd)

return wrapper


@execute_in_tmpdir
def main() -> None:
"""Execute the action."""
logging.basicConfig(level=logging.INFO)
Expand Down
1 change: 1 addition & 0 deletions src/pull_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,7 @@ def create_repository_client(access_token: str | None, base_path: Path) -> Repos
)

local_repo = Repo(base_path)
logging.info("executing in git repository in the directory: %s", local_repo.working_dir)
github_client = Github(login_or_token=access_token)
remote_url = local_repo.remote().url
repository_fullname = _get_repository_name_from_git_url(remote_url=remote_url)
Expand Down

0 comments on commit a2759c2

Please sign in to comment.