Skip to content

SWE-agent takes a GitHub issue and tries to automatically fix it, using your LM of choice. It can also be employed for offensive cybersecurity or competitive coding challenges. [NeurIPS 2024]

Allow to run on local repository

Kilian Lieretd5af9586995c
diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.py
index 07f78aae..7bb32768 100644
--- a/sweagent/environment/swe_env.py
+++ b/sweagent/environment/swe_env.py
@@ -19,6 +19,7 @@ from rich.logging import RichHandler
from simple_parsing.helpers.serialization.serializable import FrozenSerializable
import yaml
from sweagent.environment.utils import (
+ copy_anything_to_container,
copy_file_to_container,
format_trajectory_markdown,
get_container,
@@ -130,7 +131,49 @@ class SWEEnv(gym.Env):
self.idx = 0
self.clean_multi_line_functions = lambda x: x
- def reset(self, index: Optional[int] = None, apply_test_patch: bool = False) -> Tuple[str, dict]:
+ @property
+ def _repo_name(self) -> str:
+ """Name of the local copy of the repository"""
+ assert self.record is not None
+ if not self.record["repo"].startswith("local://"):
+ return self.record["repo"].replace("/", "__")
+ else:
+ return self.record["repo"].removeprefix("local://").replace("/", "__")
+
+ def _copy_repo(self) -> str:
+ """Clone/copy repository/codebase in container
+ Returns:
+ folder name of clone
+ """
+ assert self.record is not None # mypy
+ if self.record["repo"].startswith("local://"):
+ copy_anything_to_container(self.container_obj, self.record["repo"].removeprefix("local://"), "/"+self._repo_name)
+ self.communicate_with_handling(
+ input=f"chown -R root:root {self._repo_name}",
+ error_msg="Failed to change permissions on copied repository",
+ )
+ return self._repo_name
+ token_prefix = ""
+ if self._github_token:
+ token_prefix = f"{self._github_token}@"
+ if not self.args.no_mirror and not self.is_from_github_url:
+ self.logger.info(f"{self._repo_name} not found in container, cloning...")
+ self.communicate_with_handling(
+ input=f"git clone https://{token_prefix}github.com/swe-bench/{self._repo_name}.git",
+ error_msg="Failed to clone repository from mirror",
+ timeout_duration=LONG_TIMEOUT,
+ )
+ return self._repo_name
+ else:
+ logger.info(f"Trying to clone from non-mirror...")
+ self.communicate_with_handling(
+ input=f"git clone https://{token_prefix}github.com/{self.record['repo']}.git {self._repo_name}",
+ error_msg="Failed to clone repository from non-mirror",
+ timeout_duration=LONG_TIMEOUT,
+ )
+ return self._repo_name
+
+ def reset(self, index: Optional[int] = None, apply_test_patch: bool = False) -> Tuple[Optional[str], dict]:
"""
Function to reset container between each task instance.
* Clones instance's repository
@@ -162,30 +205,13 @@ class SWEEnv(gym.Env):
# Clone repository if not already cloned
self.communicate(input="cd /")
folders = self.communicate(input="ls").split("\n")
- repo_name = self.record["repo"].replace("/", "__")
- if repo_name not in folders:
- token_prefix = ""
- if self._github_token:
- token_prefix = f"{self._github_token}@"
- if not self.args.no_mirror and not self.is_from_github_url:
- self.logger.info(f"{repo_name} not found in container, cloning...")
- self.communicate_with_handling(
- input=f"git clone https://{token_prefix}github.com/swe-bench/{repo_name}.git",
- error_msg="Failed to clone repository from mirror",
- timeout_duration=LONG_TIMEOUT,
- )
- else:
- logger.info(f"Trying to clone from non-mirror...")
- self.communicate_with_handling(
- input=f"git clone https://{token_prefix}github.com/{self.record['repo']}.git {repo_name}",
- error_msg="Failed to clone repository from non-mirror",
- timeout_duration=LONG_TIMEOUT,
- )
+ if self._repo_name not in folders:
+ self._copy_repo()
# Clean repository of any modifications + Checkout base commit
for cmd in [
"echo -n > /root/files_to_edit.txt",
- f"cd {repo_name}",
+ f"cd {self._repo_name}",
"export ROOT=$(pwd -P)",
"git status",
"git restore .",
@@ -570,14 +596,14 @@ class SWEEnv(gym.Env):
"""
Creates conda environment and installs third party dependencies to allow code execution
"""
- if self.is_from_github_url and self.args.environment_setup is None:
+ assert self.record is not None # mypy
+ if (self.is_from_github_url or self.record["repo"].startswith("local://")) and self.args.environment_setup is None:
logger.warning((
"install_environment is set to True, but the data path is a GitHub URL "
"without an environment config file (environment_config key/flag). "
"Skipping conda environment installation."
))
return
- repo_name = self.record["repo"].replace("/", "__")
if self.args.environment_setup is not None:
assert isinstance(self.args.environment_setup, (str, os.PathLike))
if Path(self.args.environment_setup).suffix in [".yml", ".yaml"]:
@@ -603,7 +629,7 @@ class SWEEnv(gym.Env):
)
raise ValueError(msg) from e
# Create environment if does not exist yet
- env_name = f"{repo_name}__{self.record['version']}"
+ env_name = f"{self._repo_name}__{self.record['version']}"
env_check = self.communicate(
f"conda env list | grep {env_name}", timeout_duration=LONG_TIMEOUT
)
@@ -687,7 +713,7 @@ class SWEEnv(gym.Env):
pre_install_cmd,
error_msg="Pre-install commands failed to execute successfully",
)
- self.logger.info(f"Installing {repo_name} at base commit...")
+ self.logger.info(f"Installing {self._repo_name} at base commit...")
if "install" in install_configs:
install_cmd = install_configs["install"]
self.communicate_with_handling(
diff --git a/sweagent/environment/utils.py b/sweagent/environment/utils.py
index 72b5af89..3c1c0af2 100644
--- a/sweagent/environment/utils.py
+++ b/sweagent/environment/utils.py
@@ -18,7 +18,9 @@ from ghapi.all import GhApi
from io import BytesIO
from pathlib import Path
from subprocess import PIPE, STDOUT
-from typing import Any, List, Optional, Set, Tuple, Dict
+from typing import Any, List, Optional, Set, Tuple, Dict, Union
+
+from git import InvalidGitRepositoryError, Repo
LOGGER_NAME = "intercode"
START_UP_DELAY = 5
@@ -52,6 +54,7 @@ def is_github_repo_url(data_path: str) -> bool:
return GITHUB_REPO_URL_PATTERN.search(data_path) is not None
+# todo: Why not just use copy_anything_to_container?
def copy_file_to_container(container, contents, container_path):
"""
Copies a given string into a Docker container at a specified path.
@@ -97,6 +100,23 @@ def copy_file_to_container(container, contents, container_path):
os.remove(temp_file_name)
+def copy_anything_to_container(container, host_path: str, container_path: str) -> None:
+ """Copy files or directories from host to container
+
+ Note: Will need to set ownership on the copied files in the container.
+ """
+ if not Path(host_path).exists():
+ msg = f"Path {host_path} does not exist, cannot copy it to container."
+ raise FileNotFoundError(msg)
+ cmd = ["docker", "cp", host_path, f"{container.id}:{container_path}"]
+ logger.debug(f"Copying {host_path} to container at {container_path} with command: {shlex.join(cmd)}")
+ try:
+ subprocess.run(cmd, check=True)
+ except subprocess.CalledProcessError as e:
+ msg = f"Error copying {host_path} to container at {container_path}: {e}"
+ raise RuntimeError(msg) from e
+
+
def read_with_timeout(container, pid_func, timeout_duration):
"""
Read data from a subprocess with a timeout.
@@ -399,6 +419,35 @@ def get_instance_from_github_url(url: str, *, base_commit: Optional[str]=None, p
return record
+def get_instance_from_local_dir(data_path: Union[str, os.PathLike], *, problem_statement: str) -> Dict[str, Any]:
+ """Get task instance from a local directory"""
+ if not problem_statement:
+ msg = "Problem statement must be provided if data_path is a local directory."
+ raise ValueError(msg)
+ data_path = Path(data_path).resolve()
+ if not data_path.is_dir():
+ msg = "data_path must be a directory"
+ raise ValueError(msg)
+ try:
+ repo = Repo(data_path, search_parent_directories=True)
+ except InvalidGitRepositoryError as e:
+ msg = "data_path must be a git repository"
+ raise ValueError(msg) from e
+ # The instance id is made up of the hash of the parent directory, the sanitized directory name
+ # and the hash of the problem statement
+ iid = hashlib.sha256(str(data_path.parent).encode()).hexdigest()[:6]
+ iid += "__"+ "".join(x for x in data_path.stem if x.isalnum())
+ iid += "-" + hashlib.sha256(problem_statement.encode()).hexdigest()[:6]
+ base_commit = repo.head.object.hexsha
+ return {
+ "repo": f"local://{data_path}",
+ "base_commit": base_commit,
+ "version": base_commit[:7],
+ "problem_statement": problem_statement,
+ "instance_id": iid,
+ }
+
+
def get_instances(
file_path: str,
base_commit: Optional[str] = None,
@@ -406,7 +455,7 @@ def get_instances(
token: Optional[str] = None,
*,
problem_statement: str = "",
- ):
+ ) -> List[Dict[str, Any]]:
"""
Getter function for handling json, jsonl files
@@ -418,12 +467,23 @@ def get_instances(
Returns:
List of instances
"""
+
# If file_path is a directory, attempt load from disk
if os.path.isdir(file_path):
- dataset_or_dict = load_from_disk(file_path)
- if isinstance(dataset_or_dict, dict):
- return dataset_or_dict[split]
- return dataset_or_dict
+ try:
+ dataset_or_dict = load_from_disk(file_path)
+ if isinstance(dataset_or_dict, dict):
+ return dataset_or_dict[split]
+ return dataset_or_dict
+ except FileNotFoundError:
+ # Raised by load_from_disk if the directory is not a dataset directory
+ pass
+
+ if Path(file_path).is_dir():
+ if base_commit is not None:
+ msg = "base_commit must be None if data_path is a local directory"
+ raise ValueError(msg)
+ return [get_instance_from_local_dir(file_path, problem_statement=problem_statement)]
# If file_path is a github issue url, fetch the issue and return a single instance
if is_github_repo_url(file_path):
diff --git a/tests/test_utils.py b/tests/test_utils.py
index de4b3c10..24755894 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -1,5 +1,5 @@
import pytest
-from sweagent.environment.utils import InvalidGithubURL, format_trajectory_markdown, _MARKDOWN_TRAJECTORY_EMOJI_MAPPING, get_instance_from_github_url, is_github_repo_url, remove_triple_backticks, parse_gh_repo_url, parse_gh_issue_url, is_github_issue_url, get_associated_commit_urls
+from sweagent.environment.utils import InvalidGithubURL, format_trajectory_markdown, _MARKDOWN_TRAJECTORY_EMOJI_MAPPING, get_instance_from_github_url, get_instances, is_github_repo_url, remove_triple_backticks, parse_gh_repo_url, parse_gh_issue_url, is_github_issue_url, get_associated_commit_urls
def test_format_trajectory_markdown(test_trajectory):
formatted = format_trajectory_markdown(test_trajectory["trajectory"])
@@ -67,7 +67,7 @@ def test_get_associated_commit_urls():
def test_get_instance_from_github_url_github_issue():
- instance = get_instance_from_github_url("https://github.com/klieret/swe-agent-test-repo/issues/1")
+ instance = get_instances("https://github.com/klieret/swe-agent-test-repo/issues/1")[0]
compare_with = {
'repo': 'klieret/swe-agent-test-repo',
'base_commit': '3b37cb20ed4851f9239fe7bef239f9cca1195a1e',
@@ -81,7 +81,7 @@ def test_get_instance_from_github_url_github_issue():
def test_get_instance_from_github_url_github_issue_overrides():
- instance = get_instance_from_github_url("https://github.com/klieret/swe-agent-test-repo/issues/1", problem_statement="asdf", base_commit="1234")
+ instance = get_instances("https://github.com/klieret/swe-agent-test-repo/issues/1", problem_statement="asdf", base_commit="1234")[0]
assert instance["problem_statement"] == "asdf"
assert instance["base_commit"] == "1234"
@@ -94,3 +94,11 @@ def test_get_instance_from_github_url_github_repo_missing_problem():
def test_get_instance_from_github_url_github_repo():
instance = get_instance_from_github_url("https://github.com/klieret/swe-agent-test-repo/", problem_statement="asdf")
assert instance["problem_statement"] == "asdf"
+
+
+def test_get_instance_from_local_dir(tmp_path):
+ tmp_dir = tmp_path / "test"
+ tmp_dir.mkdir(parents=True)
+ instance = get_instances(file_path=tmp_dir, problem_statement="asdf")[0]
+ assert instance["problem_statement"] == "asdf"
+ assert instance["repo"] == f"local://{str(tmp_dir.resolve())}"