Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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"]
Expand Down
6 changes: 3 additions & 3 deletions src/codegen/agents/agent.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -45,7 +45,7 @@
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:
Expand Down Expand Up @@ -79,10 +79,10 @@
# Convert API response to dict for Job initialization

job = AgentTask(agent_run_response, self.api_client, self.org_id)
self.current_job = job

Check failure on line 82 in src/codegen/agents/agent.py

View workflow job for this annotation

GitHub Actions / mypy

error: Incompatible types in assignment (expression has type "AgentTask", variable has type "None") [assignment]
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:
Expand Down
3 changes: 1 addition & 2 deletions src/codegen/cli/commands/serve/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import subprocess
import sys
from pathlib import Path
from typing import Optional

import rich
import rich_click as click
Expand Down Expand Up @@ -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
Expand Down
13 changes: 6 additions & 7 deletions src/codegen/extensions/attribution/git_history.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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:
Expand All @@ -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:
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -423,12 +422,12 @@ 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

# Sort by date
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
6 changes: 2 additions & 4 deletions src/codegen/extensions/attribution/main.py
Original file line number Diff line number Diff line change
@@ -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:
Expand Down Expand Up @@ -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:
Expand Down
4 changes: 2 additions & 2 deletions src/codegen/extensions/events/codegen_app.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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

Expand Down
3 changes: 2 additions & 1 deletion src/codegen/extensions/events/github.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -29,7 +30,7 @@
msg = "GITHUB_TOKEN is not set"
logger.exception(msg)
raise ValueError(msg)
if not self._client:

Check failure on line 33 in src/codegen/extensions/events/github.py

View workflow job for this annotation

GitHub Actions / mypy

error: Cannot determine type of "_client" [has-type]
self._client = Github(os.getenv("GITHUB_TOKEN"))
return self._client

Expand Down Expand Up @@ -68,7 +69,7 @@
raise
else:
# Pass through raw dict if no type validation needed
return func(raw_event)

Check failure on line 72 in src/codegen/extensions/events/github.py

View workflow job for this annotation

GitHub Actions / mypy

error: Argument 1 has incompatible type "dict[Any, Any]"; expected "T" [arg-type]

self.registered_handlers[event_name] = new_func
return new_func
Expand Down
9 changes: 4 additions & 5 deletions src/codegen/extensions/events/github_types.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from datetime import datetime
from typing import Optional


class GitHubRepository:
Expand Down Expand Up @@ -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:
Expand All @@ -58,5 +57,5 @@ class GitHubInstallationEvent:
action: str
installation: GitHubInstallation
repositories: list[GitHubRepository]
requester: Optional[dict]
requester: dict | None
sender: GitHubUser
3 changes: 2 additions & 1 deletion src/codegen/extensions/events/linear.py
Original file line number Diff line number Diff line change
@@ -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

Expand Down
24 changes: 12 additions & 12 deletions src/codegen/extensions/github/types/pull_request.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Literal, Optional
from typing import Literal

Check warning on line 1 in src/codegen/extensions/github/types/pull_request.py

View check run for this annotation

Codecov / codecov/patch

src/codegen/extensions/github/types/pull_request.py#L1

Added line #L1 was not covered by tests

from pydantic import BaseModel

Expand Down Expand Up @@ -47,30 +47,30 @@
locked: bool
title: str
user: GitHubUser
body: Optional[str]
body: str | None

Check warning on line 50 in src/codegen/extensions/github/types/pull_request.py

View check run for this annotation

Codecov / codecov/patch

src/codegen/extensions/github/types/pull_request.py#L50

Added line #L50 was not covered by tests
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

Check warning on line 56 in src/codegen/extensions/github/types/pull_request.py

View check run for this annotation

Codecov / codecov/patch

src/codegen/extensions/github/types/pull_request.py#L53-L56

Added lines #L53 - L56 were not covered by tests
assignees: list[GitHubUser]
requested_reviewers: list[GitHubUser]
requested_teams: list[dict]
labels: list[Label]
milestone: Optional[dict]
milestone: dict | None

Check warning on line 61 in src/codegen/extensions/github/types/pull_request.py

View check run for this annotation

Codecov / codecov/patch

src/codegen/extensions/github/types/pull_request.py#L61

Added line #L61 was not covered by tests
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

Check warning on line 68 in src/codegen/extensions/github/types/pull_request.py

View check run for this annotation

Codecov / codecov/patch

src/codegen/extensions/github/types/pull_request.py#L67-L68

Added lines #L67 - L68 were not covered by tests
merged: bool
mergeable: Optional[bool]
rebaseable: Optional[bool]
mergeable: bool | None
rebaseable: bool | None

Check warning on line 71 in src/codegen/extensions/github/types/pull_request.py

View check run for this annotation

Codecov / codecov/patch

src/codegen/extensions/github/types/pull_request.py#L70-L71

Added lines #L70 - L71 were not covered by tests
mergeable_state: str
merged_by: Optional[GitHubUser]
merged_by: GitHubUser | None

Check warning on line 73 in src/codegen/extensions/github/types/pull_request.py

View check run for this annotation

Codecov / codecov/patch

src/codegen/extensions/github/types/pull_request.py#L73

Added line #L73 was not covered by tests
comments: int
review_comments: int
maintainer_can_modify: bool
Expand Down
4 changes: 1 addition & 3 deletions src/codegen/extensions/github/types/push.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from typing import Optional

from pydantic import BaseModel

from .base import GitHubRepository, GitHubUser
Expand All @@ -23,7 +21,7 @@
created: bool
deleted: bool
forced: bool
base_ref: Optional[str]
base_ref: str | None

Check warning on line 24 in src/codegen/extensions/github/types/push.py

View check run for this annotation

Codecov / codecov/patch

src/codegen/extensions/github/types/push.py#L24

Added line #L24 was not covered by tests
compare: str
commits: list[GitHubCommit]
head_commit: GitHubCommit
4 changes: 1 addition & 3 deletions src/codegen/extensions/graph/create_graph.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -16,7 +14,7 @@
# 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):

Check warning on line 17 in src/codegen/extensions/graph/create_graph.py

View check run for this annotation

Codecov / codecov/patch

src/codegen/extensions/graph/create_graph.py#L17

Added line #L17 was not covered by tests
"""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:
Expand Down
4 changes: 2 additions & 2 deletions src/codegen/extensions/graph/neo4j_exporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
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()}}

Check warning on line 29 in src/codegen/extensions/graph/neo4j_exporter.py

View check run for this annotation

Codecov / codecov/patch

src/codegen/extensions/graph/neo4j_exporter.py#L29

Added line #L29 was not covered by tests

query = f"CREATE (n:{node.label} {{{', '.join(f'{k}: ${k}' for k in properties.keys())}}})"
session.run(query, properties)
Expand All @@ -36,7 +36,7 @@
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()}}

Check warning on line 39 in src/codegen/extensions/graph/neo4j_exporter.py

View check run for this annotation

Codecov / codecov/patch

src/codegen/extensions/graph/neo4j_exporter.py#L39

Added line #L39 was not covered by tests

query = (
f"MATCH (source:{source_node.label} {{full_name: $source_name}}), "
Expand Down
12 changes: 6 additions & 6 deletions src/codegen/extensions/index/code_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -34,9 +34,9 @@
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

Check warning on line 39 in src/codegen/extensions/index/code_index.py

View check run for this annotation

Codecov / codecov/patch

src/codegen/extensions/index/code_index.py#L37-L39

Added lines #L37 - L39 were not covered by tests

@property
@abstractmethod
Expand Down Expand Up @@ -151,7 +151,7 @@
# 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."
Expand All @@ -162,7 +162,7 @@

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()

Expand Down
3 changes: 1 addition & 2 deletions src/codegen/extensions/index/file_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import pickle
from pathlib import Path
from typing import Optional

import modal
import numpy as np
Expand Down Expand Up @@ -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:
Expand Down
3 changes: 1 addition & 2 deletions src/codegen/extensions/linear/linear_client.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import os
from typing import Optional

import requests
from requests.adapters import HTTPAdapter
Expand All @@ -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:
Expand Down
Loading