Skip to content
Closed
Binary file not shown.
9,231 changes: 9,231 additions & 0 deletions .codegen/codemods/remove_dead_code/remove_dead_code-system-prompt.txt

Large diffs are not rendered by default.

48 changes: 48 additions & 0 deletions .codegen/codemods/remove_dead_code/remove_dead_code.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import codegen
from codegen.sdk.core.codebase import Codebase


@codegen.function("remove-dead-code")
def run(codebase: Codebase):
# Codemod: Remove dead code in the src/codegen directory

# Iterate through all files in the src/codegen directory
for file in codebase.files:
# Only process files in the src/codegen directory
if not file.filepath.startswith("src/codegen"):
continue

# Iterate over all functions in the file
for function in file.functions:
# Skip test functions, decorated functions, and those used as endpoints
if "test" not in function.file.filepath and not function.decorators and not function.usages:
# If function has no usages or call sites, remove it
if not function.usages and not function.call_sites:
print(f"Removing unused function: {function.name} in {function.file.filepath}")
function.remove()

# Similarly, check and remove unused classes
for cls in file.classes:
# Skip classes with no usage, preserving API endpoints
if not cls.decorators:
# Check if any method in the class has a decorator containing "route"
is_endpoint = False
for method in cls.methods:
if method.decorators and any("route" in d.source for d in method.decorators):
is_endpoint = True
break

if not cls.usages and not is_endpoint:
print(f"Removing unused class: {cls.name} in {cls.file.filepath}")
cls.remove()

# Commit changes to the codebase
codebase.commit()


if __name__ == "__main__":
print("Parsing codebase...")
codebase = Codebase("./")

print("Running function...")
run(codebase)
14 changes: 0 additions & 14 deletions src/codegen/cli/commands/create/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import rich_click as click

from codegen.cli.api.client import RestAPI
from codegen.cli.auth.constants import PROMPTS_DIR
from codegen.cli.auth.session import CodegenSession
from codegen.cli.auth.token_manager import get_current_token
from codegen.cli.codemod.convert import convert_to_cli
Expand All @@ -16,19 +15,6 @@
from codegen.cli.workspace.decorators import requires_init


def get_prompts_dir() -> Path:
"""Get the directory for storing prompts, creating it if needed."""
PROMPTS_DIR.mkdir(parents=True, exist_ok=True)

# Ensure .gitignore exists and contains the prompts directory
gitignore = Path.cwd() / ".gitignore"
if not gitignore.exists() or "codegen-sh/prompts" not in gitignore.read_text():
with open(gitignore, "a") as f:
f.write("\n# Codegen prompts\ncodegen-sh/prompts/\n")

return PROMPTS_DIR


def get_target_paths(name: str, path: Path) -> tuple[Path, Path]:
"""Get the target path for the new function file.

Expand Down
17 changes: 0 additions & 17 deletions src/codegen/cli/commands/run/render.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,6 @@
from rich.markdown import Markdown
from rich.panel import Panel

from codegen.cli.api.schemas import RunCodemodOutput


def pretty_print_output(output: RunCodemodOutput):
"""Pretty print the codemod run output with panels."""
if output.web_link:
rich.print("\n• [blue underline]" + output.web_link + "[/blue underline]\n")

if output.logs:
pretty_print_logs(output.logs)

if output.error:
pretty_print_error(output.error)

if output.observation:
pretty_print_diff(output.observation)


def pretty_print_logs(logs: str):
"""Pretty print logs in a panel."""
Expand Down
39 changes: 0 additions & 39 deletions src/codegen/cli/commands/serve/main.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import importlib.util
import logging
import socket
import subprocess
Expand All @@ -12,8 +11,6 @@
from rich.logging import RichHandler
from rich.panel import Panel

from codegen.extensions.events.codegen_app import CodegenApp

logger = logging.getLogger(__name__)


Expand All @@ -33,42 +30,6 @@ def setup_logging(debug: bool):
)


def load_app_from_file(file_path: Path) -> CodegenApp:
"""Load a CodegenApp instance from a Python file.

Args:
file_path: Path to the Python file containing the CodegenApp

Returns:
The CodegenApp instance from the file

Raises:
click.ClickException: If no CodegenApp instance is found
"""
try:
# Import the module from file path
spec = importlib.util.spec_from_file_location("app_module", file_path)
if not spec or not spec.loader:
msg = f"Could not load module from {file_path}"
raise click.ClickException(msg)

module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)

# Find CodegenApp instance
for attr_name in dir(module):
attr = getattr(module, attr_name)
if isinstance(attr, CodegenApp):
return attr

msg = f"No CodegenApp instance found in {file_path}"
raise click.ClickException(msg)

except Exception as e:
msg = f"Error loading app from {file_path}: {e!s}"
raise click.ClickException(msg)


def create_app_module(file_path: Path) -> str:
"""Create a temporary module that exports the app for uvicorn."""
# Add the file's directory to Python path
Expand Down
35 changes: 0 additions & 35 deletions src/codegen/cli/errors.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
# TODO: refactor this file out
import functools

import rich
import rich_click as click
from rich.panel import Panel


class AuthError(Exception):
Expand All @@ -18,12 +13,6 @@ class InvalidTokenError(AuthError):
pass


class NoTokenError(AuthError):
"""Error raised if no token is provided."""

pass


class CodegenError(Exception):
"""Base class for Codegen-specific errors."""

Expand All @@ -34,27 +23,3 @@ class ServerError(CodegenError):
"""Error raised when the server encounters an error."""

pass


def format_error_message(error):
"""Format error message based on error type."""
if isinstance(error, AuthError):
return "[red]Authentication Error:[/red] Please run 'codegen login' first."
elif isinstance(error, ServerError):
return "[red]Server Error:[/red] The server encountered an error. Please try again later."
else:
return f"[red]Error:[/red] {error!s}"


def handle_auth_error(f):
"""Decorator to handle authentication errors gracefully."""

@functools.wraps(f)
def wrapper(*args, **kwargs):
try:
return f(*args, **kwargs)
except AuthError:
rich.print(Panel("[red]Authentication Error:[/red] Please run 'codegen login' first.", title="Codegen Error", border_style="red"))
raise click.Abort()

return wrapper
5 changes: 0 additions & 5 deletions src/codegen/cli/rich/codeblocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,6 @@ def format_codeblock(code: str) -> str:
return f"\n\t[cyan]{code}[/cyan]\n"


def format_code(code: str) -> str:
"""Just blue for a span"""
return f"[cyan]{code}[/cyan]"


def format_path(path: str) -> str:
"""Format a path in a consistent style.

Expand Down
17 changes: 0 additions & 17 deletions src/codegen/cli/rich/pretty_print.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,6 @@
from rich.markdown import Markdown
from rich.panel import Panel

from codegen.cli.api.schemas import RunCodemodOutput


def pretty_print_output(output: RunCodemodOutput):
"""Pretty print the codemod run output with panels."""
if output.web_link:
rich.print("\n• [blue underline]" + output.web_link + "[/blue underline]\n")

if output.logs:
pretty_print_logs(output.logs)

if output.error:
pretty_print_error(output.error)

if output.observation:
pretty_print_diff(output.observation)


def pretty_print_logs(logs: str):
"""Pretty print logs in a panel."""
Expand Down
45 changes: 0 additions & 45 deletions src/codegen/cli/sdk/decorator.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,48 +55,3 @@ def run(codebase):

"""
return DecoratedFunction(name)


def webhook(
label: str,
*,
type: WebhookType = "pr",
event: WebhookEvent = "created",
description: str | None = None,
users: Sequence[str] | None = None,
) -> DecoratedFunction:
"""Decorator for webhook functions that run in response to events.

Args:
label: Unique identifier for this webhook
type: Type of webhook ("pr", "push", "issue", "release")
event: Event to trigger on ("created", "updated", "closed", etc.)
description: Human-readable description of what this webhook does
users: List of GitHub usernames to notify (with or without @ symbol)

Example:
@codegen.webhook(
label="flag-customer-code",
type="pr",
event="created",
description="Flags customer code",
)
def run(codebase, pr):
pass

"""
normalized_users = [user.lstrip("@") for user in users] if users else []

webhook_config = {
"type": type,
"event": event,
"description": description,
"users": normalized_users,
}

return DecoratedFunction(
name=label,
webhook_config=webhook_config,
lint_mode=True,
lint_user_whitelist=normalized_users,
)
5 changes: 0 additions & 5 deletions src/codegen/cli/utils/json_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,10 @@
from tempfile import TemporaryDirectory

from datamodel_code_generator import DataModelType, InputFileType, generate
from pydantic import BaseModel

# This utility contains functions for utilizing, transforming and validating JSON schemas generated by Pydantic models.


def get_schema(model: BaseModel) -> dict:
return model.model_json_schema()


def validate_json(schema: dict, json_data: str) -> bool:
json_schema = json.dumps(schema)
exec_scope = {}
Expand Down
7 changes: 0 additions & 7 deletions src/codegen/cli/workspace/initialize_workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,13 +86,6 @@ def initialize_codegen(session: CodegenSession, status: Status | str = "Initiali
return CODEGEN_FOLDER, DOCS_FOLDER, EXAMPLES_FOLDER


def add_to_gitignore_if_not_present(gitignore: Path, line: str):
if not gitignore.exists():
gitignore.write_text(line)
elif line not in gitignore.read_text():
gitignore.write_text(gitignore.read_text() + "\n" + line)


def modify_gitignore(codegen_folder: Path):
"""Update .gitignore to track only specific Codegen files."""
gitignore_path = codegen_folder / ".gitignore"
Expand Down
9 changes: 0 additions & 9 deletions src/codegen/configs/models/utils.py
Original file line number Diff line number Diff line change
@@ -1,9 +0,0 @@
from pydantic_settings import SettingsConfigDict


def get_setting_config(prefix: str) -> SettingsConfigDict:
return SettingsConfigDict(
env_prefix=f"{prefix}_",
case_sensitive=False,
extra="ignore",
)
8 changes: 0 additions & 8 deletions src/codegen/extensions/events/github_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,3 @@ class GitHubUser:
type: str
site_admin: bool
# Other URL fields omitted for brevity


class GitHubInstallationEvent:
action: str
installation: GitHubInstallation
repositories: list[GitHubRepository]
requester: Optional[dict]
sender: GitHubUser
25 changes: 0 additions & 25 deletions src/codegen/extensions/github/types/events/pull_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,20 +25,6 @@ class Label(BaseModel):
default: bool


class SimplePullRequest(BaseModel):
id: int
number: int
state: str
locked: bool
title: str
user: User
body: str | None = None
labels: list[Label] = []
created_at: str
updated_at: str
draft: bool = False


class PullRequestLabeledEvent(BaseModel):
"""Simplified version of the PR labeled event for testing"""

Expand All @@ -50,17 +36,6 @@ class PullRequestLabeledEvent(BaseModel):
sender: User


class PullRequestOpenedEvent(BaseModel):
action: str = "opened" # Always "opened" for this event
number: int
pull_request: PullRequest
repository: GitHubRepository
organization: GitHubOrganization
enterprise: GitHubEnterprise
sender: GitHubUser
installation: GitHubInstallation


class PullRequestUnlabeledEvent(BaseModel):
action: str
number: int
Expand Down
Loading
Loading