From e588457bcd250245190cfb45867d927f5ee9bd27 Mon Sep 17 00:00:00 2001 From: bagel897 Date: Tue, 29 Apr 2025 11:09:44 -0700 Subject: [PATCH] update pre-commit --- .pre-commit-config.yaml | 10 ++++---- src/codegen/agents/agent.py | 6 ++--- src/codegen/cli/commands/serve/main.py | 3 +-- .../extensions/attribution/git_history.py | 13 +++++----- src/codegen/extensions/attribution/main.py | 6 ++--- src/codegen/extensions/events/codegen_app.py | 4 ++-- src/codegen/extensions/events/github.py | 3 ++- src/codegen/extensions/events/github_types.py | 9 ++++--- src/codegen/extensions/events/linear.py | 3 ++- .../extensions/github/types/pull_request.py | 24 +++++++++---------- src/codegen/extensions/github/types/push.py | 4 +--- src/codegen/extensions/graph/create_graph.py | 4 +--- .../extensions/graph/neo4j_exporter.py | 4 ++-- src/codegen/extensions/index/code_index.py | 12 +++++----- src/codegen/extensions/index/file_index.py | 3 +-- .../extensions/linear/linear_client.py | 3 +-- src/codegen/extensions/lsp/definition.py | 2 +- src/codegen/extensions/lsp/execute.py | 3 ++- src/codegen/extensions/lsp/server.py | 8 +++---- src/codegen/extensions/mcp/codebase_tools.py | 14 +++++------ src/codegen/extensions/swebench/utils.py | 10 ++++---- src/codegen/runner/sandbox/middlewares.py | 3 ++- src/codegen/sdk/codebase/multigraph.py | 5 +--- src/codegen/sdk/core/codeowner.py | 4 ++-- src/codegen/sdk/core/utils/cache_utils.py | 4 ++-- src/codegen/sdk/types.py | 4 +--- .../shared/compilation/exception_utils.py | 9 +++---- tests/unit/codegen/agents/test_api_client.py | 2 +- .../extensions/lsp/test_document_symbols.py | 8 ++++--- .../extensions/lsp/test_workspace_sync.py | 2 +- 30 files changed, 88 insertions(+), 101 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index eeea3f677..52ad11a37 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -7,7 +7,7 @@ repos: hooks: - id: taplo-format - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.9.6 + rev: v0.11.7 hooks: # Run the linter. - id: ruff @@ -19,7 +19,7 @@ repos: types_or: [python, jupyter, pyi] - repo: https://github.com/biomejs/pre-commit - rev: "v0.6.1" + rev: "v2.0.0-beta.1" hooks: - id: biome-check language: node @@ -48,7 +48,7 @@ repos: - id: check-merge-conflict - repo: https://github.com/python-jsonschema/check-jsonschema - rev: 0.31.1 + rev: 0.33.0 hooks: - id: check-github-workflows - id: check-github-actions @@ -77,12 +77,12 @@ repos: entry: bash -c "uv run --frozen --all-extras --dev deptry src --ignore DEP001 --extend-exclude 'codegen-examples/.*'" - repo: https://github.com/renovatebot/pre-commit-hooks - rev: 39.169.3 + rev: 39.263.1 hooks: - id: renovate-config-validator - repo: https://github.com/astral-sh/uv-pre-commit - rev: "0.5.31" + rev: "0.6.17" hooks: - id: uv-sync args: ["--frozen", "--all-packages", "--all-extras"] diff --git a/src/codegen/agents/agent.py b/src/codegen/agents/agent.py index 48cc7c094..288698e53 100644 --- a/src/codegen/agents/agent.py +++ b/src/codegen/agents/agent.py @@ -1,5 +1,5 @@ import os -from typing import Any, Optional +from typing import Any from codegen_api_client.api.agents_api import AgentsApi from codegen_api_client.api_client import ApiClient @@ -45,7 +45,7 @@ def refresh(self) -> None: class Agent: """API client for interacting with Codegen AI agents.""" - def __init__(self, token: str, org_id: Optional[int] = None, base_url: Optional[str] = CODEGEN_BASE_API_URL): + def __init__(self, token: str, org_id: int | None = None, base_url: str | None = CODEGEN_BASE_API_URL): """Initialize a new Agent client. Args: @@ -82,7 +82,7 @@ def run(self, prompt: str) -> AgentTask: self.current_job = job return job - def get_status(self) -> Optional[dict[str, Any]]: + def get_status(self) -> dict[str, Any] | None: """Get the status of the current job. Returns: diff --git a/src/codegen/cli/commands/serve/main.py b/src/codegen/cli/commands/serve/main.py index 4c2dbc12e..0a074075e 100644 --- a/src/codegen/cli/commands/serve/main.py +++ b/src/codegen/cli/commands/serve/main.py @@ -4,7 +4,6 @@ import subprocess import sys from pathlib import Path -from typing import Optional import rich import rich_click as click @@ -89,7 +88,7 @@ def create_app_module(file_path: Path) -> str: return f"{module_name}:app" -def start_ngrok(port: int) -> Optional[str]: +def start_ngrok(port: int) -> str | None: """Start ngrok and return the public URL""" try: import requests diff --git a/src/codegen/extensions/attribution/git_history.py b/src/codegen/extensions/attribution/git_history.py index 39dfcc740..b985ad757 100644 --- a/src/codegen/extensions/attribution/git_history.py +++ b/src/codegen/extensions/attribution/git_history.py @@ -1,7 +1,6 @@ import time from collections import defaultdict, deque from datetime import datetime -from typing import Optional import pygit2 from intervaltree import IntervalTree @@ -16,7 +15,7 @@ class GitAttributionTracker: """Tracks attribution information for code symbols based on git history.""" - def __init__(self, codebase: Codebase, ai_authors: Optional[list[str]] = None): + def __init__(self, codebase: Codebase, ai_authors: list[str] | None = None): """Initialize the attribution tracker. Args: @@ -43,7 +42,7 @@ def __init__(self, codebase: Codebase, ai_authors: Optional[list[str]] = None): self._commits: deque[Commit] - def build_history(self, max_commits: Optional[int] = None) -> None: + def build_history(self, max_commits: int | None = None) -> None: """Build the git history for the codebase. Args: @@ -206,7 +205,7 @@ def map_symbols_to_history(self, force=False) -> None: start_time = time.time() print("Stashing any working directory changes...") - stash_msg = f"Codegen Attribution Stash @ {datetime.now().timestamp()}" + stash_msg = f"Codegen Attribution Stash @ {datetime.now().timestamp()}" # noqa: DTZ005 stash_id = None try: stash_id = self.repo.stash(self.repo.default_signature, stash_msg, include_untracked=True) @@ -325,7 +324,7 @@ def get_symbol_history(self, symbol: Symbol) -> list[dict]: symbol_id = f"{symbol.filepath}:{symbol.name}" return self._symbol_history.get(symbol_id, []) - def get_symbol_last_editor(self, symbol: Symbol) -> Optional[str]: + def get_symbol_last_editor(self, symbol: Symbol) -> str | None: """Get the last person who edited a symbol. Args: @@ -423,7 +422,7 @@ def get_ai_contribution_timeline(self) -> list[tuple[datetime, int]]: if any(name in author for name in self.ai_authors): for commit in commits: # Convert timestamp to year-month - dt = datetime.fromtimestamp(commit["timestamp"]) + dt = datetime.fromtimestamp(commit["timestamp"]) # noqa: DTZ006 month_key = f"{dt.year}-{dt.month:02d}" monthly_counts[month_key] += 1 @@ -431,4 +430,4 @@ def get_ai_contribution_timeline(self) -> list[tuple[datetime, int]]: timeline = sorted(monthly_counts.items()) # Convert to datetime objects - return [(datetime.strptime(month, "%Y-%m"), count) for month, count in timeline] + return [(datetime.strptime(month, "%Y-%m"), count) for month, count in timeline] # noqa: DTZ007 diff --git a/src/codegen/extensions/attribution/main.py b/src/codegen/extensions/attribution/main.py index a282fda89..c197a7a3b 100644 --- a/src/codegen/extensions/attribution/main.py +++ b/src/codegen/extensions/attribution/main.py @@ -1,10 +1,8 @@ -from typing import Optional - from codegen.extensions.attribution.git_history import GitAttributionTracker from codegen.sdk.core.codebase import Codebase -def analyze_ai_impact(codebase: Codebase, ai_authors: Optional[list[str]] = None, max_commits: Optional[int] = None) -> dict: +def analyze_ai_impact(codebase: Codebase, ai_authors: list[str] | None = None, max_commits: int | None = None) -> dict: """Analyze the impact of AI on a codebase. Args: @@ -57,7 +55,7 @@ def analyze_ai_impact(codebase: Codebase, ai_authors: Optional[list[str]] = None } -def add_attribution_to_symbols(codebase: Codebase, ai_authors: Optional[list[str]] = None) -> None: +def add_attribution_to_symbols(codebase: Codebase, ai_authors: list[str] | None = None) -> None: """Add attribution information to symbols in the codebase. This adds the following attributes to each symbol: diff --git a/src/codegen/extensions/events/codegen_app.py b/src/codegen/extensions/events/codegen_app.py index 024730168..4d3e5b415 100644 --- a/src/codegen/extensions/events/codegen_app.py +++ b/src/codegen/extensions/events/codegen_app.py @@ -1,5 +1,5 @@ import os -from typing import Any, Optional +from typing import Any from fastapi import FastAPI, Request from fastapi.responses import HTMLResponse @@ -23,7 +23,7 @@ class CodegenApp: linear: Linear slack: Slack - def __init__(self, name: str, repo: Optional[str] = None, tmp_dir: str = "/tmp/codegen", commit: str | None = "latest"): + def __init__(self, name: str, repo: str | None = None, tmp_dir: str = "/tmp/codegen", commit: str | None = "latest"): self.name = name self.tmp_dir = tmp_dir diff --git a/src/codegen/extensions/events/github.py b/src/codegen/extensions/events/github.py index d17b16aef..5f1733ff3 100644 --- a/src/codegen/extensions/events/github.py +++ b/src/codegen/extensions/events/github.py @@ -1,6 +1,7 @@ import logging import os -from typing import Any, Callable, TypeVar +from collections.abc import Callable +from typing import Any, TypeVar from fastapi import Request from github import Github diff --git a/src/codegen/extensions/events/github_types.py b/src/codegen/extensions/events/github_types.py index fd3f62536..18cce2c82 100644 --- a/src/codegen/extensions/events/github_types.py +++ b/src/codegen/extensions/events/github_types.py @@ -1,5 +1,4 @@ from datetime import datetime -from typing import Optional class GitHubRepository: @@ -37,11 +36,11 @@ class GitHubInstallation: events: list[str] created_at: datetime updated_at: datetime - single_file_name: Optional[str] + single_file_name: str | None has_multiple_single_files: bool single_file_paths: list[str] - suspended_by: Optional[str] - suspended_at: Optional[datetime] + suspended_by: str | None + suspended_at: datetime | None class GitHubUser: @@ -58,5 +57,5 @@ class GitHubInstallationEvent: action: str installation: GitHubInstallation repositories: list[GitHubRepository] - requester: Optional[dict] + requester: dict | None sender: GitHubUser diff --git a/src/codegen/extensions/events/linear.py b/src/codegen/extensions/events/linear.py index 4fe5b2e91..813556f76 100644 --- a/src/codegen/extensions/events/linear.py +++ b/src/codegen/extensions/events/linear.py @@ -1,5 +1,6 @@ import logging -from typing import Any, Callable, TypeVar +from collections.abc import Callable +from typing import Any, TypeVar from pydantic import BaseModel diff --git a/src/codegen/extensions/github/types/pull_request.py b/src/codegen/extensions/github/types/pull_request.py index c4b58eed6..739c69776 100644 --- a/src/codegen/extensions/github/types/pull_request.py +++ b/src/codegen/extensions/github/types/pull_request.py @@ -1,4 +1,4 @@ -from typing import Literal, Optional +from typing import Literal from pydantic import BaseModel @@ -47,30 +47,30 @@ class PullRequest(BaseModel): locked: bool title: str user: GitHubUser - body: Optional[str] + body: str | None created_at: str updated_at: str - closed_at: Optional[str] - merged_at: Optional[str] - merge_commit_sha: Optional[str] - assignee: Optional[GitHubUser] + closed_at: str | None + merged_at: str | None + merge_commit_sha: str | None + assignee: GitHubUser | None assignees: list[GitHubUser] requested_reviewers: list[GitHubUser] requested_teams: list[dict] labels: list[Label] - milestone: Optional[dict] + milestone: dict | None draft: bool head: PullRequestRef base: PullRequestRef _links: PullRequestLinks author_association: str - auto_merge: Optional[dict] - active_lock_reason: Optional[str] + auto_merge: dict | None + active_lock_reason: str | None merged: bool - mergeable: Optional[bool] - rebaseable: Optional[bool] + mergeable: bool | None + rebaseable: bool | None mergeable_state: str - merged_by: Optional[GitHubUser] + merged_by: GitHubUser | None comments: int review_comments: int maintainer_can_modify: bool diff --git a/src/codegen/extensions/github/types/push.py b/src/codegen/extensions/github/types/push.py index 10f44f5e7..2cf615b6a 100644 --- a/src/codegen/extensions/github/types/push.py +++ b/src/codegen/extensions/github/types/push.py @@ -1,5 +1,3 @@ -from typing import Optional - from pydantic import BaseModel from .base import GitHubRepository, GitHubUser @@ -23,7 +21,7 @@ class PushEvent(BaseModel): created: bool deleted: bool forced: bool - base_ref: Optional[str] + base_ref: str | None compare: str commits: list[GitHubCommit] head_commit: GitHubCommit diff --git a/src/codegen/extensions/graph/create_graph.py b/src/codegen/extensions/graph/create_graph.py index 442b2dcd6..9718f01eb 100644 --- a/src/codegen/extensions/graph/create_graph.py +++ b/src/codegen/extensions/graph/create_graph.py @@ -1,5 +1,3 @@ -from typing import Optional - from codegen.extensions.graph.utils import Node, NodeLabel, Relation, RelationLabel, SimpleGraph from codegen.sdk.code_generation.doc_utils.utils import safe_get_class from codegen.sdk.core.class_definition import Class @@ -16,7 +14,7 @@ def create_codebase_graph(codebase): # Track existing nodes by name to prevent duplicates node_registry = {} # name -> node_id mapping - def get_or_create_node(name: str, label: NodeLabel, parent_name: Optional[str] = None, properties: dict | None = None): + def get_or_create_node(name: str, label: NodeLabel, parent_name: str | None = None, properties: dict | None = None): """Get existing node or create new one if it doesn't exist.""" full_name = f"{parent_name}.{name}" if parent_name and parent_name != "Class" else name if full_name in node_registry: diff --git a/src/codegen/extensions/graph/neo4j_exporter.py b/src/codegen/extensions/graph/neo4j_exporter.py index 72a499636..48241c0d6 100644 --- a/src/codegen/extensions/graph/neo4j_exporter.py +++ b/src/codegen/extensions/graph/neo4j_exporter.py @@ -26,7 +26,7 @@ def export_graph(self, graph: SimpleGraph): with self.driver.session() as session: # Create nodes for node in graph.nodes.values(): - properties = {"name": node.name, "full_name": node.full_name, **{k: str(v) if isinstance(v, (dict, list)) else v for k, v in node.properties.items()}} + properties = {"name": node.name, "full_name": node.full_name, **{k: str(v) if isinstance(v, dict | list) else v for k, v in node.properties.items()}} query = f"CREATE (n:{node.label} {{{', '.join(f'{k}: ${k}' for k in properties.keys())}}})" session.run(query, properties) @@ -36,7 +36,7 @@ def export_graph(self, graph: SimpleGraph): source_node = graph.nodes[relation.source_id] target_node = graph.nodes[relation.target_id] - properties = {**{k: str(v) if isinstance(v, (dict, list)) else v for k, v in relation.properties.items()}} + properties = {**{k: str(v) if isinstance(v, dict | list) else v for k, v in relation.properties.items()}} query = ( f"MATCH (source:{source_node.label} {{full_name: $source_name}}), " diff --git a/src/codegen/extensions/index/code_index.py b/src/codegen/extensions/index/code_index.py index 4cf8a5de3..bd422b6a8 100644 --- a/src/codegen/extensions/index/code_index.py +++ b/src/codegen/extensions/index/code_index.py @@ -2,7 +2,7 @@ from abc import ABC, abstractmethod from pathlib import Path -from typing import Optional, TypeVar +from typing import TypeVar import numpy as np @@ -34,9 +34,9 @@ def __init__(self, codebase: Codebase): codebase: The codebase to index """ self.codebase = codebase - self.E: Optional[np.ndarray] = None - self.items: Optional[np.ndarray] = None - self.commit_hash: Optional[str] = None + self.E: np.ndarray | None = None + self.items: np.ndarray | None = None + self.commit_hash: str | None = None @property @abstractmethod @@ -151,7 +151,7 @@ def update(self) -> None: # Update commit hash self.commit_hash = self._get_current_commit() - def save(self, save_path: Optional[str] = None) -> None: + def save(self, save_path: str | None = None) -> None: """Save the index to disk.""" if self.E is None or self.items is None: msg = "No embeddings to save. Call create() first." @@ -162,7 +162,7 @@ def save(self, save_path: Optional[str] = None) -> None: self._save_index(save_path) - def load(self, load_path: Optional[str] = None) -> None: + def load(self, load_path: str | None = None) -> None: """Load the index from disk.""" load_path = Path(load_path) if load_path else self._get_default_save_path() diff --git a/src/codegen/extensions/index/file_index.py b/src/codegen/extensions/index/file_index.py index a76e62d5e..dee164999 100644 --- a/src/codegen/extensions/index/file_index.py +++ b/src/codegen/extensions/index/file_index.py @@ -2,7 +2,6 @@ import pickle from pathlib import Path -from typing import Optional import modal import numpy as np @@ -87,7 +86,7 @@ def delete_modal_dict(self) -> bool: logger.exception(f"Failed to delete Modal Dict: {e}") return False - def modal_dict_exists(self, commit_hash: Optional[str] = None) -> bool: + def modal_dict_exists(self, commit_hash: str | None = None) -> bool: """Check if a Modal Dict exists for a specific commit. Args: diff --git a/src/codegen/extensions/linear/linear_client.py b/src/codegen/extensions/linear/linear_client.py index 0c3803153..4cca2c5e1 100644 --- a/src/codegen/extensions/linear/linear_client.py +++ b/src/codegen/extensions/linear/linear_client.py @@ -1,5 +1,4 @@ import os -from typing import Optional import requests from requests.adapters import HTTPAdapter @@ -15,7 +14,7 @@ class LinearClient: api_headers: dict api_endpoint = "https://api.linear.app/graphql" - def __init__(self, access_token: Optional[str] = None, team_id: Optional[str] = None, max_retries: int = 3, backoff_factor: float = 0.5): + def __init__(self, access_token: str | None = None, team_id: str | None = None, max_retries: int = 3, backoff_factor: float = 0.5): if not access_token: access_token = os.getenv("LINEAR_ACCESS_TOKEN") if not access_token: diff --git a/src/codegen/extensions/lsp/definition.py b/src/codegen/extensions/lsp/definition.py index acecc7256..ef8deff5c 100644 --- a/src/codegen/extensions/lsp/definition.py +++ b/src/codegen/extensions/lsp/definition.py @@ -28,7 +28,7 @@ def go_to_definition(node: Editable | None, uri: str, position: Position) -> Edi if resolved is None: logger.warning(f"No resolved value found for {node.name} at {uri}:{position}") return None - if isinstance(resolved, (HasName,)): + if isinstance(resolved, HasName): resolved = resolved.get_name() if isinstance(resolved.parent, Assignment) and resolved.parent.value == resolved: resolved = resolved.parent.get_name() diff --git a/src/codegen/extensions/lsp/execute.py b/src/codegen/extensions/lsp/execute.py index 5e34121d1..e72fafddc 100644 --- a/src/codegen/extensions/lsp/execute.py +++ b/src/codegen/extensions/lsp/execute.py @@ -1,4 +1,5 @@ -from typing import TYPE_CHECKING, Any, Callable +from collections.abc import Callable +from typing import TYPE_CHECKING, Any from lsprotocol import types from lsprotocol.types import Position, Range diff --git a/src/codegen/extensions/lsp/server.py b/src/codegen/extensions/lsp/server.py index 4d24cc7f2..7ba5d1f74 100644 --- a/src/codegen/extensions/lsp/server.py +++ b/src/codegen/extensions/lsp/server.py @@ -1,4 +1,4 @@ -from typing import Any, Optional +from typing import Any from lsprotocol import types from lsprotocol.types import Position, Range @@ -21,9 +21,9 @@ class CodegenLanguageServer(LanguageServer): - codebase: Optional[Codebase] - io: Optional[LSPIO] - progress_manager: Optional[LSPProgress] + codebase: Codebase | None + io: LSPIO | None + progress_manager: LSPProgress | None actions: dict[str, CodeAction] def __init__(self, *args: Any, **kwargs: Any) -> None: diff --git a/src/codegen/extensions/mcp/codebase_tools.py b/src/codegen/extensions/mcp/codebase_tools.py index 52a25b1d6..bb3423e73 100644 --- a/src/codegen/extensions/mcp/codebase_tools.py +++ b/src/codegen/extensions/mcp/codebase_tools.py @@ -1,5 +1,5 @@ import json -from typing import Annotated, Optional +from typing import Annotated from mcp.server.fastmcp import FastMCP @@ -18,12 +18,12 @@ @mcp.tool(name="reveal_symbol", description="Reveal the dependencies and usages of a symbol up to N degrees") def reveal_symbol_tool( symbol_name: Annotated[str, "Name of the symbol to inspect"], - target_file: Annotated[Optional[str], "The file path of the file containing the symbol to inspect"], + target_file: Annotated[str | None, "The file path of the file containing the symbol to inspect"], codebase_dir: Annotated[str, "The root directory of your codebase"], codebase_language: Annotated[ProgrammingLanguage, "The language the codebase is written in"], - max_depth: Annotated[Optional[int], "depth up to which symbol information is retrieved"], - collect_dependencies: Annotated[Optional[bool], "includes dependencies of symbol"], - collect_usages: Annotated[Optional[bool], "includes usages of symbol"], + max_depth: Annotated[int | None, "depth up to which symbol information is retrieved"], + collect_dependencies: Annotated[bool | None, "includes dependencies of symbol"], + collect_usages: Annotated[bool | None, "includes usages of symbol"], ): codebase = Codebase(repo_path=codebase_dir, language=codebase_language) result = reveal_symbol( @@ -42,8 +42,8 @@ def search_codebase_tool( query: Annotated[str, "The search query to find in the codebase. When ripgrep is available, this will be passed as a ripgrep pattern. For regex searches, set use_regex=True."], codebase_dir: Annotated[str, "The root directory of your codebase"], codebase_language: Annotated[ProgrammingLanguage, "The language the codebase is written in"], - target_directories: Annotated[Optional[list[str]], "list of directories to search within"] = None, - file_extensions: Annotated[Optional[list[str]], "list of file extensions to search (e.g. ['.py', '.ts'])"] = None, + target_directories: Annotated[list[str] | None, "list of directories to search within"] = None, + file_extensions: Annotated[list[str] | None, "list of file extensions to search (e.g. ['.py', '.ts'])"] = None, page: Annotated[int, "page number to return (1-based)"] = 1, files_per_page: Annotated[int, "number of files to return per page"] = 10, use_regex: Annotated[bool, "use regex for the search query"] = False, diff --git a/src/codegen/extensions/swebench/utils.py b/src/codegen/extensions/swebench/utils.py index c5054b2d0..f29fdbcc8 100644 --- a/src/codegen/extensions/swebench/utils.py +++ b/src/codegen/extensions/swebench/utils.py @@ -2,7 +2,7 @@ from dataclasses import dataclass from pathlib import Path from pprint import pprint -from typing import Literal, Optional +from typing import Literal from datasets import load_dataset @@ -21,13 +21,13 @@ class SweBenchExample: patch: str test_patch: str problem_statement: str - hints_text: Optional[str] + hints_text: str | None created_at: str version: str fail_to_pass: str - pass_to_pass: Optional[str] - environment_setup_commit: Optional[str] - difficulty: Optional[int] + pass_to_pass: str | None + environment_setup_commit: str | None + difficulty: int | None def load_predictions(paths): diff --git a/src/codegen/runner/sandbox/middlewares.py b/src/codegen/runner/sandbox/middlewares.py index 8edea49b9..9b2752916 100644 --- a/src/codegen/runner/sandbox/middlewares.py +++ b/src/codegen/runner/sandbox/middlewares.py @@ -1,6 +1,7 @@ import traceback +from collections.abc import Callable from http import HTTPStatus -from typing import Callable, TypeVar +from typing import TypeVar from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint from starlette.requests import Request diff --git a/src/codegen/sdk/codebase/multigraph.py b/src/codegen/sdk/codebase/multigraph.py index 2a76fec70..912b1db5b 100644 --- a/src/codegen/sdk/codebase/multigraph.py +++ b/src/codegen/sdk/codebase/multigraph.py @@ -2,11 +2,8 @@ from dataclasses import dataclass, field from typing import Generic, TypeVar -from codegen.sdk import TYPE_CHECKING from codegen.sdk.core.detached_symbols.function_call import FunctionCall - -if TYPE_CHECKING: - from codegen.sdk.core.function import Function +from codegen.sdk.core.function import Function TFunction = TypeVar("TFunction", bound=Function) diff --git a/src/codegen/sdk/core/codeowner.py b/src/codegen/sdk/core/codeowner.py index 8db24cc67..90416cbe2 100644 --- a/src/codegen/sdk/core/codeowner.py +++ b/src/codegen/sdk/core/codeowner.py @@ -1,5 +1,5 @@ -from collections.abc import Iterable, Iterator -from typing import Callable, Generic, Literal +from collections.abc import Callable, Iterable, Iterator +from typing import Generic, Literal from codeowners import CodeOwners as CodeOwnersParser diff --git a/src/codegen/sdk/core/utils/cache_utils.py b/src/codegen/sdk/core/utils/cache_utils.py index 60f7c4dbf..723e8ee8d 100644 --- a/src/codegen/sdk/core/utils/cache_utils.py +++ b/src/codegen/sdk/core/utils/cache_utils.py @@ -1,6 +1,6 @@ import functools -from collections.abc import Iterator -from typing import Callable, Generic, ParamSpec, TypeVar +from collections.abc import Callable, Iterator +from typing import Generic, ParamSpec, TypeVar from codegen.sdk.extensions.utils import lru_cache diff --git a/src/codegen/sdk/types.py b/src/codegen/sdk/types.py index 7f070aa0d..99943886b 100644 --- a/src/codegen/sdk/types.py +++ b/src/codegen/sdk/types.py @@ -1,3 +1 @@ -from typing import TypeAlias - -JSON: TypeAlias = dict[str, "JSON"] | list["JSON"] | str | int | float | bool | None +type JSON = dict[str, "JSON"] | list["JSON"] | str | int | float | bool | None diff --git a/src/codegen/shared/compilation/exception_utils.py b/src/codegen/shared/compilation/exception_utils.py index 3f1a40400..b19cc6084 100644 --- a/src/codegen/shared/compilation/exception_utils.py +++ b/src/codegen/shared/compilation/exception_utils.py @@ -45,10 +45,7 @@ def get_local_frame(exc_type: type[BaseException], exc_value: BaseException, exc def get_local_frame_context(frame: FrameType): local_vars = {k: v for k, v in frame.f_locals.items() if not k.startswith("__")} - if "print" in local_vars: - del local_vars["print"] - if "codebase" in local_vars: - del local_vars["codebase"] - if "pr_options" in local_vars: - del local_vars["pr_options"] + local_vars.pop("print", None) + local_vars.pop("codebase", None) + local_vars.pop("pr_options", None) return local_vars diff --git a/tests/unit/codegen/agents/test_api_client.py b/tests/unit/codegen/agents/test_api_client.py index a2de88dbe..a634f4478 100644 --- a/tests/unit/codegen/agents/test_api_client.py +++ b/tests/unit/codegen/agents/test_api_client.py @@ -88,7 +88,7 @@ def test_sanitize_for_serialization_tuple(self, api_client): def test_sanitize_for_serialization_datetime(self, api_client): """Test sanitization of datetime values""" - dt = datetime.datetime(2022, 1, 1, 12, 0, 0, tzinfo=datetime.timezone.utc) + dt = datetime.datetime(2022, 1, 1, 12, 0, 0, tzinfo=datetime.UTC) assert api_client.sanitize_for_serialization(dt) == "2022-01-01T12:00:00+00:00" date = datetime.date(2022, 1, 1) diff --git a/tests/unit/codegen/extensions/lsp/test_document_symbols.py b/tests/unit/codegen/extensions/lsp/test_document_symbols.py index 7671ae652..14f516f84 100644 --- a/tests/unit/codegen/extensions/lsp/test_document_symbols.py +++ b/tests/unit/codegen/extensions/lsp/test_document_symbols.py @@ -1,5 +1,4 @@ -from collections.abc import Sequence -from typing import cast +from typing import TYPE_CHECKING, cast import pytest from lsprotocol.types import ( @@ -14,6 +13,9 @@ from codegen.sdk.core.codebase import Codebase +if TYPE_CHECKING: + from collections.abc import Sequence + @pytest.mark.parametrize( "original, expected_symbols", @@ -227,7 +229,7 @@ async def test_document_symbols( result = await client.text_document_document_symbol_async(params=DocumentSymbolParams(text_document=TextDocumentIdentifier(uri=f"file://{codebase.repo_path}/test.py"))) assert result is not None - symbols = cast(Sequence[DocumentSymbol], result) + symbols = cast("Sequence[DocumentSymbol]", result) assert len(symbols) == len(expected_symbols) for actual, expected in zip(symbols, expected_symbols): assert actual.name == expected.name diff --git a/tests/unit/codegen/extensions/lsp/test_workspace_sync.py b/tests/unit/codegen/extensions/lsp/test_workspace_sync.py index c3cd38b64..2b7a839c0 100644 --- a/tests/unit/codegen/extensions/lsp/test_workspace_sync.py +++ b/tests/unit/codegen/extensions/lsp/test_workspace_sync.py @@ -1,4 +1,4 @@ -from typing import Callable +from collections.abc import Callable import pytest from lsprotocol.types import (