Skip to content

Commit

Permalink
[Style]: Fix lint issues
Browse files Browse the repository at this point in the history
  • Loading branch information
openhands-agent committed Feb 24, 2025
1 parent 451494c commit 3db785a
Show file tree
Hide file tree
Showing 10 changed files with 170 additions and 101 deletions.
99 changes: 57 additions & 42 deletions openhands/integrations/github/github_service.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import os
import json
import os
from typing import Any

import httpx
Expand All @@ -10,8 +10,8 @@
GHUnknownException,
GitHubRepository,
GitHubUser,
TaskType,
SuggestedTask,
TaskType,
)
from openhands.utils.import_utils import get_impl

Expand Down Expand Up @@ -139,24 +139,28 @@ async def search_repositories(

return repos

async def execute_graphql_query(self, query: str, variables: dict[str, Any]) -> dict[str, Any]:
async def execute_graphql_query(
self, query: str, variables: dict[str, Any]
) -> dict[str, Any]:
"""Execute a GraphQL query against the GitHub API."""
try:
async with httpx.AsyncClient() as client:
github_headers = await self._get_github_headers()
response = await client.post(
f"{self.BASE_URL}/graphql",
f'{self.BASE_URL}/graphql',
headers=github_headers,
json={"query": query, "variables": variables}
json={'query': query, 'variables': variables},
)
response.raise_for_status()

result = response.json()
if "errors" in result:
raise GHUnknownException(f"GraphQL query error: {json.dumps(result['errors'])}")

if 'errors' in result:
raise GHUnknownException(
f"GraphQL query error: {json.dumps(result['errors'])}"
)

return result

except httpx.HTTPStatusError as e:
if e.response.status_code == 401:
raise GhAuthenticationError('Invalid Github token')
Expand All @@ -165,7 +169,9 @@ async def execute_graphql_query(self, query: str, variables: dict[str, Any]) ->
except httpx.HTTPError:
raise GHUnknownException('Unknown error')

async def get_suggested_tasks(self, repo_full_name: str | None = None) -> list[SuggestedTask]:
async def get_suggested_tasks(
self, repo_full_name: str | None = None
) -> list[SuggestedTask]:
"""
Get suggested tasks for the authenticated user across all repositories.
Returns:
Expand Down Expand Up @@ -216,56 +222,65 @@ async def get_suggested_tasks(self, repo_full_name: str | None = None) -> list[S
}
"""

variables = {
"login": login
}
variables = {'login': login}

try:
response = await self.execute_graphql_query(query, variables)
print(f"\nGraphQL Response:")
print('\nGraphQL Response:')
print(response)
data = response["data"]["user"]

data = response['data']['user']
tasks: list[SuggestedTask] = []

# Process pull requests
for pr in data["pullRequests"]["nodes"]:
repo_name = pr["repository"]["nameWithOwner"]
for pr in data['pullRequests']['nodes']:
repo_name = pr['repository']['nameWithOwner']

# Always add open PRs
task_type = TaskType.OPEN_PR

# Check for specific states
if pr["mergeable"] == "CONFLICTING":
if pr['mergeable'] == 'CONFLICTING':
task_type = TaskType.MERGE_CONFLICTS
elif (pr["commits"]["nodes"] and
pr["commits"]["nodes"][0]["commit"]["statusCheckRollup"] and
pr["commits"]["nodes"][0]["commit"]["statusCheckRollup"]["state"] == "FAILURE"):
elif (
pr['commits']['nodes']
and pr['commits']['nodes'][0]['commit']['statusCheckRollup']
and pr['commits']['nodes'][0]['commit']['statusCheckRollup'][
'state'
]
== 'FAILURE'
):
task_type = TaskType.FAILING_CHECKS
elif any(review["state"] in ["CHANGES_REQUESTED", "COMMENTED"]
for review in pr["reviews"]["nodes"]):
elif any(
review['state'] in ['CHANGES_REQUESTED', 'COMMENTED']
for review in pr['reviews']['nodes']
):
task_type = TaskType.UNRESOLVED_COMMENTS

tasks.append(SuggestedTask(
task_type=task_type,
repo=repo_name,
issue_number=pr["number"],
title=pr["title"]
))
tasks.append(
SuggestedTask(
task_type=task_type,
repo=repo_name,
issue_number=pr['number'],
title=pr['title'],
)
)

# Process issues
for issue in data["issues"]["nodes"]:
repo_name = issue["repository"]["nameWithOwner"]
tasks.append(SuggestedTask(
task_type=TaskType.OPEN_ISSUE,
repo=repo_name,
issue_number=issue["number"],
title=issue["title"]
))
for issue in data['issues']['nodes']:
repo_name = issue['repository']['nameWithOwner']
tasks.append(
SuggestedTask(
task_type=TaskType.OPEN_ISSUE,
repo=repo_name,
issue_number=issue['number'],
title=issue['title'],
)
)

return tasks
except Exception as e:
print(f"Error: {str(e)}")
print(f'Error: {str(e)}')
return []


Expand Down
11 changes: 6 additions & 5 deletions openhands/integrations/github/github_types.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
from enum import Enum

from pydantic import BaseModel


class TaskType(str, Enum):
MERGE_CONFLICTS = "MERGE_CONFLICTS"
FAILING_CHECKS = "FAILING_CHECKS"
UNRESOLVED_COMMENTS = "UNRESOLVED_COMMENTS"
OPEN_ISSUE = "OPEN_ISSUE"
OPEN_PR = "OPEN_PR"
MERGE_CONFLICTS = 'MERGE_CONFLICTS'
FAILING_CHECKS = 'FAILING_CHECKS'
UNRESOLVED_COMMENTS = 'UNRESOLVED_COMMENTS'
OPEN_ISSUE = 'OPEN_ISSUE'
OPEN_PR = 'OPEN_PR'


class SuggestedTask(BaseModel):
Expand Down
6 changes: 4 additions & 2 deletions openhands/runtime/builder/docker.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,10 +168,12 @@ def build(
)

except subprocess.CalledProcessError as e:
logger.error(f'Image build failed:\n{e}') # TODO: {e} is empty
logger.error(f'Image build failed:\n{e}') # TODO: {e} is empty
logger.error(f'Command output:\n{e.output}')
if self.rolling_logger.is_enabled():
logger.error("Docker build output:\n" + self.rolling_logger.all_lines) # Show the error
logger.error(
'Docker build output:\n' + self.rolling_logger.all_lines
) # Show the error
raise

except subprocess.TimeoutExpired:
Expand Down
5 changes: 4 additions & 1 deletion openhands/runtime/impl/modal/modal_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,10 @@ def vscode_url(self) -> str | None:

tunnel = self.sandbox.tunnels()[self._vscode_port]
tunnel_url = tunnel.url
self._vscode_url = tunnel_url + f'/?tkn={token}&folder={self.config.workspace_mount_path_in_sandbox}'
self._vscode_url = (
tunnel_url
+ f'/?tkn={token}&folder={self.config.workspace_mount_path_in_sandbox}'
)

self.log(
'debug',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@ function deactivate() {}
module.exports = {
activate,
deactivate
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,4 @@
"title": "Hello World from OpenHands"
}]
}
}
}
2 changes: 1 addition & 1 deletion openhands/server/routes/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,4 +145,4 @@ async def get_suggested_tasks(
return JSONResponse(
content=str(e),
status_code=500,
)
)
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ reportlab = "*"
[tool.coverage.run]
concurrency = ["gevent"]


[tool.poetry.group.runtime.dependencies]
jupyterlab = "*"
notebook = "*"
Expand Down Expand Up @@ -136,6 +137,7 @@ ignore = ["D1"]
[tool.ruff.lint.pydocstyle]
convention = "google"


[tool.poetry.group.evaluation.dependencies]
streamlit = "*"
whatthepatch = "*"
Expand Down
32 changes: 32 additions & 0 deletions test_tasks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import asyncio
import os
from pydantic import SecretStr

from openhands.integrations.github.github_service import GitHubService

async def main():
token = SecretStr(os.environ.get('GITHUB_TOKEN', ''))
service = GitHubService(token=token)

print("Getting user info...")
user = await service.get_user()
print(f"Authenticated as: {user.login}")

print("\nFetching recent repositories...")
repos = await service.get_repositories(page=1, per_page=10, sort="pushed", installation_id=None)
print(f"Found {len(repos)} repositories:")
for repo in repos:
print(f"- {repo.full_name}")

print("\nFetching suggested tasks...")
tasks = await service.get_suggested_tasks()

print("\nFound tasks:")
if not tasks:
print("No tasks found")
for task in tasks:
print(f"\n{task.task_type} in {task.repo}:")
print(f"#{task.issue_number}: {task.title}")

if __name__ == "__main__":
asyncio.run(main())
Loading

0 comments on commit 3db785a

Please sign in to comment.