Fix linting (#7965)

This commit is contained in:
Michael Panchenko
2025-04-21 00:34:40 +02:00
committed by GitHub
parent 0637b5b912
commit 14564b25d6
13 changed files with 69 additions and 69 deletions

View File

@@ -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'],

View File

@@ -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
]

View File

@@ -4,6 +4,7 @@ from typing import Any
import httpx
from pydantic import SecretStr
from openhands.core.logger import openhands_logger as logger
from openhands.integrations.service_types import (
AuthenticationError,
GitService,
@@ -14,7 +15,7 @@ from openhands.integrations.service_types import (
)
from openhands.server.types import AppMode
from 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 string
variables: 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 GraphQL
gitlab_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
]

View File

@@ -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:' part
poetry_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: ASYNC101
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,

View File

@@ -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: ASYNC101
lines = 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: ASYNC101
if mode != 'w':
all_lines = file.readlines()
new_file = insert_lines(insert, all_lines, start, end)

View File

@@ -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_id
from openhands.server.shared import server_config
app = 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:

View File

@@ -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: ASYNC100
for model in ollama_models_list:
model_list.append('ollama/' + model['name'])
break

View File

@@ -2,9 +2,9 @@ import os
import subprocess
import tempfile
from openhands.integrations.service_types import ProviderType
from openhands.resolver.interfaces.issue import Issue
from openhands.resolver.send_pull_request import make_commit
from openhands.integrations.service_types import ProviderType
def test_commit_message_with_quotes():

View File

@@ -11,6 +11,7 @@ from openhands.events.observation import (
CmdOutputObservation,
NullObservation,
)
from openhands.integrations.service_types import ProviderType
from openhands.llm.llm import LLM
from openhands.resolver.interfaces.github import GithubIssueHandler, GithubPRHandler
from 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 == 5

View File

@@ -5,6 +5,7 @@ from unittest.mock import ANY, MagicMock, call, patch
import pytest
from openhands.core.config import LLMConfig
from openhands.integrations.service_types import ProviderType
from openhands.resolver.interfaces.github import GithubIssueHandler
from openhands.resolver.interfaces.issue import ReviewThread
from 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 token
mock_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 vars
with pytest.raises(ValueError, match='token is not set'):
main()

View File

@@ -3,10 +3,10 @@ import subprocess
import tempfile
from openhands.core.logger import openhands_logger as logger
from openhands.resolver.interfaces.issue import Issue
from openhands.resolver.send_pull_request import make_commit
from 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 repo

View File

@@ -11,6 +11,7 @@ from openhands.events.observation import (
CmdOutputObservation,
NullObservation,
)
from openhands.integrations.service_types import ProviderType
from openhands.llm.llm import LLM
from openhands.resolver.interfaces.gitlab import GitlabIssueHandler, GitlabPRHandler
from 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.fixture
def 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 == 5

View File

@@ -6,6 +6,7 @@ from urllib.parse import quote
import pytest
from openhands.core.config import LLMConfig
from openhands.integrations.service_types import ProviderType
from openhands.resolver.interfaces.gitlab import GitlabIssueHandler
from openhands.resolver.interfaces.issue import ReviewThread
from 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.fixture
def mock_output_dir():
@@ -1222,7 +1223,9 @@ def test_main(
# Test for invalid token
mock_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 vars
with pytest.raises(ValueError, match='token is not set'):
main()