Skip to content

Commit 1a0c4ad

Browse files
rushilpatel0github-actions[bot]
authored andcommitted
Automated pre-commit update
1 parent 02fcd95 commit 1a0c4ad

File tree

8 files changed

+129
-164
lines changed

8 files changed

+129
-164
lines changed

codegen-examples/examples/snapshot_event_handler/event_handlers.py

Lines changed: 10 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from fastapi import FastAPI, Request
44

55
from codegen.extensions.github.types.pull_request import PullRequestLabeledEvent
6+
67
load_dotenv(".env")
78

89
import modal
@@ -40,22 +41,21 @@
4041
"fastapi[standard]",
4142
"slack_sdk",
4243
"fastapi_utils[all]",
43-
"classy-fastapi>=0.6.1"
44+
"classy-fastapi>=0.6.1",
4445
)
45-
46-
)
46+
)
4747

4848

4949
event_handlers_app = modal.App("codegen-event-handlers")
5050

5151

5252
@event_handlers_app.cls(image=base_image, secrets=[modal.Secret.from_dotenv(".env")], enable_memory_snapshot=True, container_idle_timeout=300)
5353
class CustomEventHandlersAPI(CodebaseEventsApp):
54-
commit: str = modal.parameter(default="79114f67ccfe8700416cd541d1c7c43659a95342")
54+
commit: str = modal.parameter(default="79114f67ccfe8700416cd541d1c7c43659a95342")
5555
repo_org: str = modal.parameter(default="codegen-sh")
5656
repo_name: str = modal.parameter(default="Kevin-s-Adventure-Game")
5757
snapshot_index_id: str = SNAPSHOT_DICT_ID
58-
58+
5959
def setup_handlers(self, cg: CodegenApp):
6060
@cg.slack.event("app_mention")
6161
async def handle_mention(event: SlackEvent):
@@ -76,7 +76,6 @@ async def handle_mention(event: SlackEvent):
7676

7777
return {"message": "Mentioned", "received_text": event.text, "response": response}
7878

79-
8079
@cg.github.event("pull_request:labeled")
8180
def handle_pr(event: PullRequestLabeledEvent):
8281
logger.info("PR labeled")
@@ -90,37 +89,30 @@ def handle_pr(event: PullRequestLabeledEvent):
9089
logger.info("> Checking out commit")
9190
codebase.checkout(commit=event.pull_request.head.sha)
9291

93-
9492
logger.info("> Running PR Lints")
9593
# LINT CODEMOD
9694
lint_for_dev_import_violations(codebase, event)
9795

9896
# REVIEW CODEMOD
9997
review_with_codegen_agent(codebase, event)
10098

101-
102-
10399
return {"message": "PR event handled", "num_files": len(codebase.files), "num_functions": len(codebase.functions)}
104100

105-
106101
@cg.linear.event("Issue")
107102
def handle_issue(event: LinearEvent):
108103
logger.info(f"Issue created: {event}")
109104
codebase = cg.get_codebase()
110105
return {"message": "Linear Issue event", "num_files": len(codebase.files), "num_functions": len(codebase.functions)}
111106

112107

113-
114-
@codegen_events_app.cls(image=base_image, secrets=[modal.Secret.from_dotenv('.env')])
108+
@codegen_events_app.cls(image=base_image, secrets=[modal.Secret.from_dotenv(".env")])
115109
class WebhookEventRouterAPI(EventRouterMixin, Routable):
116-
117110
snapshot_index_id: str = SNAPSHOT_DICT_ID
118-
119111

120112
def get_event_handler_cls(self):
121113
modal_cls = modal.Cls.from_name(app_name="Events", name="CustomEventHandlersAPI")
122114
return modal_cls
123-
115+
124116
@post("/{org}/{repo}/{provider}/events")
125117
async def handle_event(self, org: str, repo: str, provider: Literal["slack", "github", "linear"], request: Request):
126118
# Define the route for the webhook url sink, it will need to indicate the repo repo org, and the provider
@@ -133,14 +125,14 @@ def api(self):
133125
route_view = WebhookEventRouterAPI()
134126
event_api.include_router(route_view.router)
135127
return event_api
136-
137128

138-
# Setup a cron job to trigger updates to the codebase snapshots.
129+
130+
# Setup a cron job to trigger updates to the codebase snapshots.
139131
@codegen_events_app.function(schedule=modal.Cron("*/10 * * * *"), image=base_image, secrets=[modal.Secret.from_dotenv(".env")])
140132
def refresh_repository_snapshots():
141133
WebhookEventRouterAPI().refresh_repository_snapshots(snapshot_index_id=SNAPSHOT_DICT_ID)
142134

143135

144-
app = modal.App("Events", secrets=[modal.Secret.from_dotenv('.env')])
136+
app = modal.App("Events", secrets=[modal.Secret.from_dotenv(".env")])
145137
app.include(event_handlers_app)
146138
app.include(codegen_events_app)
Lines changed: 29 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,5 @@
1-
2-
3-
41
import logging
52
from codegen.agents.code_agent import CodeAgent
6-
from codegen.configs.models.secrets import SecretsConfig
73
from codegen.extensions.github.types.pull_request import PullRequestLabeledEvent
84

95
from codegen.extensions.langchain.tools import GithubCreatePRCommentTool, GithubCreatePRReviewCommentTool, GithubViewPRTool
@@ -12,61 +8,61 @@
128
logging.basicConfig(level=logging.INFO, force=True)
139
logger = logging.getLogger(__name__)
1410

11+
1512
def lint_for_dev_import_violations(codebase: Codebase, event: PullRequestLabeledEvent):
16-
1713
patch, commit_shas, modified_symbols = codebase.get_modified_symbols_in_pr(event.pull_request.number)
1814
modified_files = set(commit_shas.keys())
1915

20-
DIR_NAME = 'packages/next/src/client/components/react-dev-overlay'
16+
DIR_NAME = "packages/next/src/client/components/react-dev-overlay"
2117
directory = codebase.get_directory(DIR_NAME)
2218

2319
# Initialize a list to store all violations
2420
violations = []
2521

26-
print('modified_files', modified_files)
27-
22+
print("modified_files", modified_files)
23+
2824
# Check if directory exists before proceeding
29-
if directory is not None and hasattr(directory, 'files'):
25+
if directory is not None and hasattr(directory, "files"):
3026
for file in directory.files:
31-
print('checking file', file.filepath)
27+
print("checking file", file.filepath)
3228
for imp in file.inbound_imports:
33-
print('file', imp.file.filepath)
34-
print('checking import', imp.import_statement)
29+
print("file", imp.file.filepath)
30+
print("checking import", imp.import_statement)
3531
# Check if the import is from outside the directory and is in the modified files
3632
if imp.file not in directory and imp.file.filepath in modified_files:
3733
# Skip require statements
38-
if 'require' in imp.import_statement:
34+
if "require" in imp.import_statement:
3935
continue
40-
violation = f'- Violation in `{file.filepath}`: Importing from `{imp.file.filepath}` ([link]({imp.github_url}))'
36+
violation = f"- Violation in `{file.filepath}`: Importing from `{imp.file.filepath}` ([link]({imp.github_url}))"
4137
violations.append(violation)
4238
logger.info(f"Found violation: {violation}")
43-
39+
4440
# Only create a PR comment if violations are found
4541
if violations:
4642
review_attention_message = "## Dev Import Violations Found\n\n"
4743
review_attention_message += "The following files have imports that violate development overlay rules:\n\n"
4844
review_attention_message += "\n".join(violations)
4945
review_attention_message += "\n\nPlease ensure that development imports are not imported in production code."
50-
46+
5147
# Create PR comment with the formatted message
5248
codebase._op.create_pr_comment(event.pull_request.number, review_attention_message)
5349

5450

5551
def review_with_codegen_agent(codebase: Codebase, event: PullRequestLabeledEvent):
56-
review_initial_message = f"CodegenBot is starting to review the PR please wait..."
57-
comment = codebase._op.create_pr_comment(event.number, review_initial_message)
58-
# Define tools first
59-
pr_tools = [
60-
GithubViewPRTool(codebase),
61-
GithubCreatePRCommentTool(codebase),
62-
GithubCreatePRReviewCommentTool(codebase),
63-
]
64-
65-
# Create agent with the defined tools
66-
agent = CodeAgent(codebase=codebase, tools=pr_tools)
67-
68-
# Using a prompt from SWE Bench
69-
prompt = f"""
52+
review_initial_message = "CodegenBot is starting to review the PR please wait..."
53+
comment = codebase._op.create_pr_comment(event.number, review_initial_message)
54+
# Define tools first
55+
pr_tools = [
56+
GithubViewPRTool(codebase),
57+
GithubCreatePRCommentTool(codebase),
58+
GithubCreatePRReviewCommentTool(codebase),
59+
]
60+
61+
# Create agent with the defined tools
62+
agent = CodeAgent(codebase=codebase, tools=pr_tools)
63+
64+
# Using a prompt from SWE Bench
65+
prompt = f"""
7066
Hey CodegenBot!
7167
7268
Here's a SWE task for you. Please Review this pull request!
@@ -77,6 +73,6 @@ def review_with_codegen_agent(codebase: Codebase, event: PullRequestLabeledEvent
7773
be explicit about the changes, produce a short summary, and point out possible improvements where pressent dont be self congratulatory stick to the facts
7874
use the tools at your disposal to create propper pr reviews include code snippets if needed, and suggest improvements if feel its necesary
7975
"""
80-
# Run the agent
81-
result = agent.run(prompt)
82-
comment.delete()
76+
# Run the agent
77+
agent.run(prompt)
78+
comment.delete()

codegen-examples/examples/snapshot_event_handler/pyproject.toml

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,24 +4,24 @@ version = "0.0.0"
44
readme = "README.md"
55
requires-python = ">=3.12, <3.14"
66
dependencies = [
7-
"fastapi-utils>=0.8.0",
8-
"fastapi[standard]>=0.115.9",
9-
"modal>=0.73.72",
10-
"fastapi-restful[all]>=0.6.0",
11-
"classy-fastapi>=0.6.1",
12-
"codegen@git+https://github.com/codegen-sh/codegen-sdk.git@f398107d31bbd53fc77bc9c5f8763d2dc8fcae5b",
7+
"fastapi-utils>=0.8.0",
8+
"fastapi[standard]>=0.115.9",
9+
"modal>=0.73.72",
10+
"fastapi-restful[all]>=0.6.0",
11+
"classy-fastapi>=0.6.1",
12+
"codegen@git+https://github.com/codegen-sh/codegen-sdk.git@f398107d31bbd53fc77bc9c5f8763d2dc8fcae5b",
1313
]
1414
license = { file = "LICENSE" }
1515
classifiers = [
16-
"License :: OSI Approved :: Apache Software License",
17-
"Intended Audience :: Developers",
18-
"Programming Language :: Python :: 3.12",
19-
"Programming Language :: Python :: 3.13",
20-
"Topic :: Software Development",
21-
"Development Status :: 4 - Beta",
22-
"Environment :: MacOS X",
23-
"Programming Language :: Python :: 3",
24-
"Programming Language :: Python",
16+
"License :: OSI Approved :: Apache Software License",
17+
"Intended Audience :: Developers",
18+
"Programming Language :: Python :: 3.12",
19+
"Programming Language :: Python :: 3.13",
20+
"Topic :: Software Development",
21+
"Development Status :: 4 - Beta",
22+
"Environment :: MacOS X",
23+
"Programming Language :: Python :: 3",
24+
"Programming Language :: Python",
2525
]
2626

2727
[tool.ruff]

src/codegen/extensions/events/codegen_app.py

Lines changed: 11 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515

1616
logger = get_logger(__name__)
1717

18+
1819
class CodegenApp:
1920
"""A FastAPI-based application for handling various code-related events."""
2021

@@ -38,11 +39,9 @@ def __init__(self, name: str, repo: Optional[str] = None, tmp_dir: str = "/tmp/c
3839
# Initialize codebase cache
3940
self.codebase: Codebase | None = None
4041

41-
4242
# Register routes
4343
self._setup_routes()
4444

45-
4645
def parse_repo(self) -> None:
4746
# Parse initial repos if provided
4847
if self.repo:
@@ -57,10 +56,7 @@ def _parse_repo(self, repo_name: str, commit: str | None = None) -> None:
5756
try:
5857
logger.info(f"[CODEBASE] Parsing repository: {repo_name}")
5958
config = CodebaseConfig(sync_enabled=True)
60-
secrets = SecretsConfig(
61-
github_token=os.environ.get("GITHUB_ACCESS_TOKEN"),
62-
linear_api_key=os.environ.get("LINEAR_ACCESS_TOKEN")
63-
)
59+
secrets = SecretsConfig(github_token=os.environ.get("GITHUB_ACCESS_TOKEN"), linear_api_key=os.environ.get("LINEAR_ACCESS_TOKEN"))
6460
self.codebase = Codebase.from_repo(repo_full_name=repo_name, tmp_dir=self.tmp_dir, commit=commit, config=config, secrets=secrets)
6561
logger.info(f"[CODEBASE] Successfully parsed and cached: {repo_name}")
6662
except Exception as e:
@@ -80,7 +76,7 @@ def get_codebase(self) -> Codebase:
8076
KeyError: If the repository hasn't been parsed
8177
"""
8278
if not self.codebase:
83-
msg = f"Repository has not been parsed"
79+
msg = "Repository has not been parsed"
8480
raise KeyError(msg)
8581
return self.codebase
8682

@@ -111,10 +107,10 @@ async def simulate_event(self, provider: str, event_type: str, payload: dict) ->
111107

112108
handler = provider_map[provider]
113109
return await handler.handle(payload)
114-
110+
115111
async def root(self):
116-
"""Render the main page."""
117-
return """
112+
"""Render the main page."""
113+
return """
118114
<!DOCTYPE html>
119115
<html>
120116
<head>
@@ -142,17 +138,17 @@ async def root(self):
142138
</body>
143139
</html>
144140
"""
145-
141+
146142
async def handle_slack_event(self, request: Request):
147-
"""Handle incoming Slack events."""
148-
payload = await request.json()
149-
return await self.slack.handle(payload)
143+
"""Handle incoming Slack events."""
144+
payload = await request.json()
145+
return await self.slack.handle(payload)
150146

151147
async def handle_github_event(self, request: Request):
152148
"""Handle incoming GitHub events."""
153149
payload = await request.json()
154150
return await self.github.handle(payload, request)
155-
151+
156152
async def handle_linear_event(self, request: Request):
157153
"""Handle incoming Linear events."""
158154
payload = await request.json()
@@ -176,8 +172,6 @@ async def _handle_github_event(request: Request):
176172
@self.app.post("/{org}/{repo}/linear/events")
177173
async def handle_linear_event(request: Request):
178174
return await self.handle_linear_event(request)
179-
180-
181175

182176
def run(self, host: str = "0.0.0.0", port: int = 8000, **kwargs):
183177
"""Run the FastAPI application."""

0 commit comments

Comments
 (0)