π OpenHands: AI-Driven Development
Fix linting (#7965)
Michael Panchenko14564b25d62e
diff --git a/evaluation/benchmarks/swe_bench/scripts/swtbench/convert.py b/evaluation/benchmarks/swe_bench/scripts/swtbench/convert.pyindex 87f88ee934..e1aefa336d 100644--- a/evaluation/benchmarks/swe_bench/scripts/swtbench/convert.py+++ b/evaluation/benchmarks/swe_bench/scripts/swtbench/convert.py@@ -65,7 +65,7 @@ def main(ci_mode = pred['metadata']['details'].get('mode', '') == 'swt-ci'try:git_diff = remove_setup_files(git_diff, pred['instance'], ci_mode)- except:+ except: # noqa: E722_LOGGER.warning('Warning: Invalid git diff found for instance %s',pred['instance_id'],diff --git a/openhands/integrations/github/github_service.py b/openhands/integrations/github/github_service.pyindex 761f310ca5..7773c9f48c 100644--- a/openhands/integrations/github/github_service.py+++ b/openhands/integrations/github/github_service.py@@ -179,7 +179,7 @@ class GitHubService(GitService):full_name=repo.get('full_name'),stargazers_count=repo.get('stargazers_count'),git_provider=ProviderType.GITHUB,- is_public=not repo.get('private', True)+ is_public=not repo.get('private', True),)for repo in all_repos]diff --git a/openhands/integrations/gitlab/gitlab_service.py b/openhands/integrations/gitlab/gitlab_service.pyindex a3390729ab..9801105088 100644--- a/openhands/integrations/gitlab/gitlab_service.py+++ b/openhands/integrations/gitlab/gitlab_service.py@@ -4,6 +4,7 @@ from typing import Anyimport httpxfrom pydantic import SecretStr+from openhands.core.logger import openhands_logger as loggerfrom openhands.integrations.service_types import (AuthenticationError,GitService,@@ -14,7 +15,7 @@ from openhands.integrations.service_types import ()from openhands.server.types import AppModefrom openhands.utils.import_utils import get_impl-from openhands.core.logger import openhands_logger as logger+class GitLabService(GitService):BASE_URL = 'https://gitlab.com/api/v4'@@ -77,24 +78,22 @@ class GitLabService(GitService):except httpx.HTTPStatusError as e:if e.response.status_code == 401:raise AuthenticationError('Invalid GitLab token')-+logger.warning(f'Status error on GL API: {e}')raise UnknownException('Unknown error')except httpx.HTTPError as e:logger.warning(f'HTTP error on GL API: {e}')raise UnknownException('Unknown error')-- async def execute_graphql_query(- self, query: str, variables: dict[str, Any]- ) -> Any:++ async def execute_graphql_query(self, query: str, variables: dict[str, Any]) -> Any:"""Execute a GraphQL query against the GitLab GraphQL API-+Args:query: The GraphQL query stringvariables: Optional variables for the GraphQL query-+Returns:The data portion of the GraphQL response"""@@ -103,37 +102,35 @@ class GitLabService(GitService):gitlab_headers = await self._get_gitlab_headers()# Add content type header for GraphQLgitlab_headers['Content-Type'] = 'application/json'-+payload = {- "query": query,- "variables": variables,+ 'query': query,+ 'variables': variables,}-+response = await client.post(- self.GRAPHQL_URL,- headers=gitlab_headers,- json=payload+ self.GRAPHQL_URL, headers=gitlab_headers, json=payload)-+if self.refresh and self._has_token_expired(response.status_code):await self.get_latest_token()gitlab_headers = await self._get_gitlab_headers()gitlab_headers['Content-Type'] = 'application/json'response = await client.post(- self.GRAPHQL_URL,- headers=gitlab_headers,- json=payload+ self.GRAPHQL_URL, headers=gitlab_headers, json=payload)response.raise_for_status()result = response.json()-+# Check for GraphQL errors- if "errors" in result:- error_message = result["errors"][0].get("message", "Unknown GraphQL error")- raise UnknownException(f"GraphQL error: {error_message}")-- return result.get("data")+ if 'errors' in result:+ error_message = result['errors'][0].get(+ 'message', 'Unknown GraphQL error'+ )+ raise UnknownException(f'GraphQL error: {error_message}')++ return result.get('data')except httpx.HTTPStatusError as e:if e.response.status_code == 401:raise AuthenticationError('Invalid GitLab token')@@ -228,7 +225,7 @@ class GitLabService(GitService):full_name=repo.get('path_with_namespace'),stargazers_count=repo.get('star_count'),git_provider=ProviderType.GITLAB,- is_public = repo.get('visibility') == 'public'+ is_public=repo.get('visibility') == 'public',)for repo in all_repos]diff --git a/openhands/runtime/impl/local/local_runtime.py b/openhands/runtime/impl/local/local_runtime.pyindex 02aa2de9c0..f3c6877cd8 100644--- a/openhands/runtime/impl/local/local_runtime.py+++ b/openhands/runtime/impl/local/local_runtime.py@@ -210,25 +210,22 @@ class LocalRuntime(ActionExecutionClient):# Extract the poetry venv by parsing output of a shell command# Equivalent to:# run poetry show -v | head -n 1 | awk '{print $2}'- poetry_show_first_line = (- subprocess.check_output(- ['poetry', 'show', '-v'],- env=env,- cwd=code_repo_path,- text=True,- # Redirect stderr to stdout- # Needed since there might be a message on stderr like- # "Skipping virtualenv creation, as specified in config file."- # which will cause the command to fail- stderr=subprocess.STDOUT,- shell=False,- )- .splitlines()[0]- )+ poetry_show_first_line = subprocess.check_output( # noqa: ASYNC101+ ['poetry', 'show', '-v'],+ env=env,+ cwd=code_repo_path,+ text=True,+ # Redirect stderr to stdout+ # Needed since there might be a message on stderr like+ # "Skipping virtualenv creation, as specified in config file."+ # which will cause the command to fail+ stderr=subprocess.STDOUT,+ shell=False,+ ).splitlines()[0]if not poetry_show_first_line.lower().startswith('found:'):raise RuntimeError(- "Cannot find poetry venv path. Please check your poetry installation."- f"First line of poetry show -v: {poetry_show_first_line}"+ 'Cannot find poetry venv path. Please check your poetry installation.'+ f'First line of poetry show -v: {poetry_show_first_line}')# Split off the 'Found:' partpoetry_venvs_path = poetry_show_first_line.split(':')[1].strip()@@ -236,7 +233,7 @@ class LocalRuntime(ActionExecutionClient):logger.debug(f'POETRY_VIRTUALENVS_PATH: {poetry_venvs_path}')check_dependencies(code_repo_path, poetry_venvs_path)- self.server_process = subprocess.Popen(+ self.server_process = subprocess.Popen( # noqa: ASYNC101cmd,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,diff --git a/openhands/runtime/utils/files.py b/openhands/runtime/utils/files.pyindex 772293195a..f06d79f4d9 100644--- a/openhands/runtime/utils/files.py+++ b/openhands/runtime/utils/files.py@@ -86,7 +86,7 @@ async def read_file()try:- with open(whole_path, 'r', encoding='utf-8') as file:+ with open(whole_path, 'r', encoding='utf-8') as file: # noqa: ASYNC101lines = read_lines(file.readlines(), start, end)except FileNotFoundError:return ErrorObservation(f'File not found: {path}')@@ -127,7 +127,7 @@ async def write_file(os.makedirs(os.path.dirname(whole_path))mode = 'w' if not os.path.exists(whole_path) else 'r+'try:- with open(whole_path, mode, encoding='utf-8') as file:+ with open(whole_path, mode, encoding='utf-8') as file: # noqa: ASYNC101if mode != 'w':all_lines = file.readlines()new_file = insert_lines(insert, all_lines, start, end)diff --git a/openhands/server/routes/git.py b/openhands/server/routes/git.pyindex c0723e4a07..f926737750 100644--- a/openhands/server/routes/git.py+++ b/openhands/server/routes/git.py@@ -15,11 +15,7 @@ from openhands.integrations.service_types import (UnknownException,User,)-from openhands.server.auth import (- get_access_token,- get_provider_tokens,- get_user_id-)+from openhands.server.auth import get_access_token, get_provider_tokens, get_user_idfrom openhands.server.shared import server_configapp = APIRouter(prefix='/api/user')@@ -30,13 +26,13 @@ async def get_user_repositories(sort: str = 'pushed',provider_tokens: PROVIDER_TOKEN_TYPE | None = Depends(get_provider_tokens),access_token: SecretStr | None = Depends(get_access_token),- user_id: str | None = Depends(get_user_id)+ user_id: str | None = Depends(get_user_id),):if provider_tokens:client = ProviderHandler(- provider_tokens=provider_tokens,+ provider_tokens=provider_tokens,external_auth_token=access_token,- external_auth_id=user_id+ external_auth_id=user_id,)try:diff --git a/openhands/server/routes/public.py b/openhands/server/routes/public.pyindex 1f5d94bba2..156adcb00b 100644--- a/openhands/server/routes/public.py+++ b/openhands/server/routes/public.py@@ -60,7 +60,7 @@ async def get_litellm_models() -> list[str]:if ollama_base_url:ollama_url = ollama_base_url.strip('/') + '/api/tags'try:- ollama_models_list = httpx.get(ollama_url, timeout=3).json()['models']+ ollama_models_list = httpx.get(ollama_url, timeout=3).json()['models'] # noqa: ASYNC100for model in ollama_models_list:model_list.append('ollama/' + model['name'])breakdiff --git a/tests/unit/resolver/github/test_pr_title_escaping.py b/tests/unit/resolver/github/test_pr_title_escaping.pyindex 4c798ca39d..c0b7941d7a 100644--- a/tests/unit/resolver/github/test_pr_title_escaping.py+++ b/tests/unit/resolver/github/test_pr_title_escaping.py@@ -2,9 +2,9 @@ import osimport subprocessimport tempfile+from openhands.integrations.service_types import ProviderTypefrom openhands.resolver.interfaces.issue import Issuefrom openhands.resolver.send_pull_request import make_commit-from openhands.integrations.service_types import ProviderTypedef test_commit_message_with_quotes():diff --git a/tests/unit/resolver/github/test_resolve_issues.py b/tests/unit/resolver/github/test_resolve_issues.pyindex 8a9a22ee7b..d90e91ff01 100644--- a/tests/unit/resolver/github/test_resolve_issues.py+++ b/tests/unit/resolver/github/test_resolve_issues.py@@ -11,6 +11,7 @@ from openhands.events.observation import (CmdOutputObservation,NullObservation,)+from openhands.integrations.service_types import ProviderTypefrom openhands.llm.llm import LLMfrom openhands.resolver.interfaces.github import GithubIssueHandler, GithubPRHandlerfrom openhands.resolver.interfaces.issue import Issue, ReviewThread@@ -24,7 +25,6 @@ from openhands.resolver.resolve_issue import (process_issue,)from openhands.resolver.resolver_output import ResolverOutput-from openhands.integrations.service_types import ProviderType@pytest.fixture@@ -315,7 +315,9 @@ async def test_complete_runtime():create_cmd_output(exit_code=0, content='git diff content', command='git apply'),]- result = await complete_runtime(mock_runtime, 'base_commit_hash', ProviderType.GITHUB)+ result = await complete_runtime(+ mock_runtime, 'base_commit_hash', ProviderType.GITHUB+ )assert result == {'git_patch': 'git diff content'}assert mock_runtime.run_action.call_count == 5diff --git a/tests/unit/resolver/github/test_send_pull_request.py b/tests/unit/resolver/github/test_send_pull_request.pyindex ae4d2d27d4..8dabf7e6d5 100644--- a/tests/unit/resolver/github/test_send_pull_request.py+++ b/tests/unit/resolver/github/test_send_pull_request.py@@ -5,6 +5,7 @@ from unittest.mock import ANY, MagicMock, call, patchimport pytestfrom openhands.core.config import LLMConfig+from openhands.integrations.service_types import ProviderTypefrom openhands.resolver.interfaces.github import GithubIssueHandlerfrom openhands.resolver.interfaces.issue import ReviewThreadfrom openhands.resolver.resolver_output import Issue, ResolverOutput@@ -18,7 +19,6 @@ from openhands.resolver.send_pull_request import (send_pull_request,update_existing_pull_request,)-from openhands.integrations.service_types import ProviderType@pytest.fixture@@ -1321,7 +1321,9 @@ def test_main(# Test for invalid tokenmock_args.issue_number = '42' # Reset to valid issue number- mock_getenv.side_effect = lambda key, default=None: None # Return None for all env vars+ mock_getenv.side_effect = (+ lambda key, default=None: None+ ) # Return None for all env varswith pytest.raises(ValueError, match='token is not set'):main()diff --git a/tests/unit/resolver/gitlab/test_gitlab_pr_title_escaping.py b/tests/unit/resolver/gitlab/test_gitlab_pr_title_escaping.pyindex bf167f49a2..59a8537f8c 100644--- a/tests/unit/resolver/gitlab/test_gitlab_pr_title_escaping.py+++ b/tests/unit/resolver/gitlab/test_gitlab_pr_title_escaping.py@@ -3,10 +3,10 @@ import subprocessimport tempfilefrom openhands.core.logger import openhands_logger as logger-from openhands.resolver.interfaces.issue import Issue-from openhands.resolver.send_pull_request import make_commitfrom openhands.integrations.service_types import ProviderType-from openhands.resolver.send_pull_request import send_pull_request+from openhands.resolver.interfaces.issue import Issue+from openhands.resolver.send_pull_request import make_commit, send_pull_request+def test_commit_message_with_quotes():# Create a temporary directory and initialize git repodiff --git a/tests/unit/resolver/gitlab/test_gitlab_resolve_issues.py b/tests/unit/resolver/gitlab/test_gitlab_resolve_issues.pyindex c891ca25ae..19d8478d23 100644--- a/tests/unit/resolver/gitlab/test_gitlab_resolve_issues.py+++ b/tests/unit/resolver/gitlab/test_gitlab_resolve_issues.py@@ -11,6 +11,7 @@ from openhands.events.observation import (CmdOutputObservation,NullObservation,)+from openhands.integrations.service_types import ProviderTypefrom openhands.llm.llm import LLMfrom openhands.resolver.interfaces.gitlab import GitlabIssueHandler, GitlabPRHandlerfrom openhands.resolver.interfaces.issue import Issue, ReviewThread@@ -24,7 +25,7 @@ from openhands.resolver.resolve_issue import (process_issue,)from openhands.resolver.resolver_output import ResolverOutput-from openhands.integrations.service_types import ProviderType+@pytest.fixturedef mock_output_dir():@@ -354,7 +355,9 @@ async def test_complete_runtime():create_cmd_output(exit_code=0, content='git diff content', command='git apply'),]- result = await complete_runtime(mock_runtime, 'base_commit_hash', ProviderType.GITLAB)+ result = await complete_runtime(+ mock_runtime, 'base_commit_hash', ProviderType.GITLAB+ )assert result == {'git_patch': 'git diff content'}assert mock_runtime.run_action.call_count == 5diff --git a/tests/unit/resolver/gitlab/test_gitlab_send_pull_request.py b/tests/unit/resolver/gitlab/test_gitlab_send_pull_request.pyindex 2c9650defe..29084abbd3 100644--- a/tests/unit/resolver/gitlab/test_gitlab_send_pull_request.py+++ b/tests/unit/resolver/gitlab/test_gitlab_send_pull_request.py@@ -6,6 +6,7 @@ from urllib.parse import quoteimport pytestfrom openhands.core.config import LLMConfig+from openhands.integrations.service_types import ProviderTypefrom openhands.resolver.interfaces.gitlab import GitlabIssueHandlerfrom openhands.resolver.interfaces.issue import ReviewThreadfrom openhands.resolver.resolver_output import Issue, ResolverOutput@@ -19,7 +20,7 @@ from openhands.resolver.send_pull_request import (send_pull_request,update_existing_pull_request,)-from openhands.integrations.service_types import ProviderType+@pytest.fixturedef mock_output_dir():@@ -1222,7 +1223,9 @@ def test_main(# Test for invalid tokenmock_args.issue_number = '42' # Reset to valid issue number- mock_getenv.side_effect = lambda key, default=None: None # Return None for all env vars+ mock_getenv.side_effect = (+ lambda key, default=None: None+ ) # Return None for all env varswith pytest.raises(ValueError, match='token is not set'):main()