-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgithub_cmd.rs
More file actions
650 lines (551 loc) · 21.5 KB
/
github_cmd.rs
File metadata and controls
650 lines (551 loc) · 21.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
//! GitHub integration commands.
//!
//! Provides commands for GitHub Actions integration:
//! - `Cortex github install` - Install GitHub Actions workflow
//! - `Cortex github run` - Run GitHub agent in Actions context
//! - `Cortex github status` - Check installation status
use anyhow::{Context, Result, bail};
use clap::Parser;
use std::path::PathBuf;
/// GitHub integration CLI.
#[derive(Debug, Parser)]
pub struct GitHubCli {
#[command(subcommand)]
pub subcommand: GitHubSubcommand,
}
/// GitHub subcommands.
#[derive(Debug, clap::Subcommand)]
pub enum GitHubSubcommand {
/// Install GitHub Actions workflow for Cortex CI/CD automation.
Install(InstallArgs),
/// Run GitHub agent in Actions context.
///
/// This command is designed to be called from within a GitHub Actions workflow.
/// It processes GitHub events (issues, pull requests, comments) and responds
/// automatically using the Cortex AI agent.
///
/// Typically, you don't run this command manually. Instead, use `cortex github install`
/// to set up the workflow that will call this command automatically.
Run(RunArgs),
/// Check GitHub Actions installation status.
Status(StatusArgs),
}
/// Arguments for install command.
#[derive(Debug, Parser)]
pub struct InstallArgs {
/// Path to the repository root (defaults to current directory).
#[arg(short, long)]
pub path: Option<PathBuf>,
/// Force overwrite existing workflow file.
#[arg(short, long)]
pub force: bool,
/// Enable PR review automation: posts welcome messages on new PRs, enables
/// /cortex review command in PR comments, and triggers re-review on new commits.
/// Adds pull_request and pull_request_review event triggers to the workflow.
#[arg(long, default_value_t = true)]
pub pr_review: bool,
/// Include issue automation.
#[arg(long, default_value_t = true)]
pub issue_automation: bool,
/// Custom workflow name.
#[arg(long, default_value = "Cortex")]
pub workflow_name: String,
}
/// Arguments for run command.
#[derive(Debug, Parser)]
#[command(
about = "Run GitHub agent in Actions context",
long_about = "Run GitHub agent in Actions context.\n\n\
This command is designed to be called from within a GitHub Actions workflow. \
It processes GitHub events (issues, pull requests, comments) and responds \
automatically using the Cortex AI agent.\n\n\
USAGE:\n\
Typically, you don't run this command manually. Use `cortex github install` \
to set up the workflow that will call this command automatically.\n\n\
ENVIRONMENT VARIABLES:\n\
The following environment variables are automatically set by GitHub Actions:\n\
GITHUB_TOKEN - Token for GitHub API access (required)\n\
GITHUB_EVENT_PATH - Path to the event payload JSON file (required)\n\
GITHUB_REPOSITORY - Repository in owner/repo format (required)\n\
GITHUB_RUN_ID - The workflow run ID (optional)\n\n\
EXAMPLES:\n\
# Typical invocation from a GitHub Actions workflow:\n\
cortex github run --event ${{ github.event_name }} \\\n\
--token ${{ secrets.GITHUB_TOKEN }} \\\n\
--event-path ${{ github.event_path }} \\\n\
--repository ${{ github.repository }}\n\n\
# Test locally with a dry run:\n\
cortex github run --event issue_comment \\\n\
--token ghp_xxxx \\\n\
--event-path ./event.json \\\n\
--repository owner/repo \\\n\
--dry-run\n\n\
SUPPORTED EVENTS:\n\
issue_comment - Triggered on issue or PR comments\n\
pull_request - Triggered on PR open, sync, or reopen\n\
pull_request_review - Triggered on PR review submission\n\
issues - Triggered when issues are opened\n\n\
SEE ALSO:\n\
cortex github install - Install the workflow file\n\
cortex github status - Check installation status"
)]
pub struct RunArgs {
/// GitHub event type.
#[arg(long, short, value_parser = clap::builder::PossibleValuesParser::new(["issue_comment", "pull_request", "pull_request_review", "issues"]))]
pub event: String,
/// GitHub token for API access (or set GITHUB_TOKEN env var).
#[arg(long, short, env = "GITHUB_TOKEN")]
pub token: Option<String>,
/// Path to the event payload JSON file (or set GITHUB_EVENT_PATH env var).
#[arg(long, env = "GITHUB_EVENT_PATH")]
pub event_path: Option<PathBuf>,
/// GitHub repository in owner/repo format (or set GITHUB_REPOSITORY env var).
#[arg(long, env = "GITHUB_REPOSITORY")]
pub repository: Option<String>,
/// GitHub workflow run ID (or set GITHUB_RUN_ID env var).
#[arg(long, env = "GITHUB_RUN_ID")]
pub run_id: Option<String>,
/// Dry run mode - don't execute, just show what would happen.
#[arg(long)]
pub dry_run: bool,
}
/// Arguments for status command.
#[derive(Debug, Parser)]
pub struct StatusArgs {
/// Path to the repository root (defaults to current directory).
#[arg(short, long)]
pub path: Option<PathBuf>,
/// Output as JSON.
#[arg(long)]
pub json: bool,
}
impl GitHubCli {
/// Run the GitHub command.
pub async fn run(self) -> Result<()> {
match self.subcommand {
GitHubSubcommand::Install(args) => run_install(args).await,
GitHubSubcommand::Run(args) => run_github_agent(args).await,
GitHubSubcommand::Status(args) => run_status(args).await,
}
}
}
/// Install GitHub Actions workflow.
async fn run_install(args: InstallArgs) -> Result<()> {
use cortex_engine::github::{WorkflowConfig, generate_workflow};
let repo_path = args.path.unwrap_or_else(|| PathBuf::from("."));
// Check if we're in a git repository
if !repo_path.join(".git").exists() {
bail!(
"Not a git repository. GitHub Actions workflows should only be installed in a git repository."
);
}
let workflows_dir = repo_path.join(".github").join("workflows");
let workflow_file = workflows_dir.join(format!("{}.yml", args.workflow_name));
// Check if workflow already exists
if workflow_file.exists() && !args.force {
bail!(
"Workflow file already exists: {}\nUse --force to overwrite.",
workflow_file.display()
);
}
// Generate workflow configuration
let config = WorkflowConfig {
name: args.workflow_name.clone(),
pr_review: args.pr_review,
issue_automation: args.issue_automation,
};
let workflow_content = generate_workflow(&config);
// Create directories if needed
std::fs::create_dir_all(&workflows_dir)
.with_context(|| format!("Failed to create directory: {}", workflows_dir.display()))?;
// Write workflow file
std::fs::write(&workflow_file, &workflow_content)
.with_context(|| format!("Failed to write workflow file: {}", workflow_file.display()))?;
println!("✅ GitHub Actions workflow installed!");
println!(" Location: {}", workflow_file.display());
println!();
println!("Next steps:");
println!(" 1. Add cortex_API_KEY to your repository secrets");
println!(" Settings → Secrets and variables → Actions → New repository secret");
println!();
println!(" 2. Commit and push the workflow file:");
println!(" git add .github/workflows/{}.yml", args.workflow_name);
println!(" git commit -m \"Add Cortex CI/CD automation\"");
println!(" git push");
println!();
println!("Features enabled:");
if args.pr_review {
println!(" • PR review automation (triggered on pull_request events)");
}
if args.issue_automation {
println!(" • Issue automation (triggered on issue_comment events)");
}
Ok(())
}
/// Run GitHub agent in Actions context.
async fn run_github_agent(args: RunArgs) -> Result<()> {
use cortex_engine::github::{GitHubEvent, parse_event};
let token = args.token.ok_or_else(|| {
anyhow::anyhow!("GitHub token required. Set GITHUB_TOKEN env var or use --token")
})?;
let repository = args.repository.ok_or_else(|| {
anyhow::anyhow!(
"GitHub repository required. Set GITHUB_REPOSITORY env var or use --repository"
)
})?;
// Parse the event payload
let event_path = args.event_path.ok_or_else(|| {
anyhow::anyhow!(
"Event payload path required. Set GITHUB_EVENT_PATH env var or use --event-path"
)
})?;
let event_content = std::fs::read_to_string(&event_path)
.with_context(|| format!("Failed to read event file: {}", event_path.display()))?;
let event = parse_event(&args.event, &event_content)
.with_context(|| format!("Failed to parse {} event", args.event))?;
println!("🤖 Cortex GitHub Agent");
println!("{}", "=".repeat(40));
println!("Repository: {}", repository);
println!("Event type: {}", args.event);
if let Some(ref run_id) = args.run_id {
println!("Run ID: {}", run_id);
}
println!();
if args.dry_run {
println!("🔍 Dry run mode - not executing");
println!();
print_event_summary(&event);
return Ok(());
}
// Execute the appropriate agent based on event type
match event {
GitHubEvent::IssueComment(comment) => {
handle_issue_comment(&token, &repository, &comment).await?;
}
GitHubEvent::PullRequest(pr) => {
handle_pull_request(&token, &repository, &pr).await?;
}
GitHubEvent::PullRequestReview(review) => {
handle_pull_request_review(&token, &repository, &review).await?;
}
GitHubEvent::Issues(issue) => {
handle_issue(&token, &repository, &issue).await?;
}
GitHubEvent::Unknown(event_type) => {
println!("⚠️ Unknown event type: {}", event_type);
println!(
" Supported events: issue_comment, pull_request, pull_request_review, issues"
);
}
}
Ok(())
}
/// Print event summary for dry run mode.
fn print_event_summary(event: &cortex_engine::github::GitHubEvent) {
use cortex_engine::github::GitHubEvent;
match event {
GitHubEvent::IssueComment(comment) => {
println!("Event: Issue Comment");
println!(" Action: {}", comment.action);
println!(" Issue #: {}", comment.issue_number);
println!(" Author: {}", comment.author);
println!(
" Body preview: {}...",
comment.body.chars().take(100).collect::<String>()
);
}
GitHubEvent::PullRequest(pr) => {
println!("Event: Pull Request");
println!(" Action: {}", pr.action);
println!(" PR #: {}", pr.number);
println!(" Title: {}", pr.title);
println!(" Author: {}", pr.author);
println!(" Base: {} ← Head: {}", pr.base_branch, pr.head_branch);
}
GitHubEvent::PullRequestReview(review) => {
println!("Event: Pull Request Review");
println!(" Action: {}", review.action);
println!(" PR #: {}", review.pr_number);
println!(" Reviewer: {}", review.reviewer);
println!(" State: {}", review.state);
}
GitHubEvent::Issues(issue) => {
println!("Event: Issue");
println!(" Action: {}", issue.action);
println!(" Issue #: {}", issue.number);
println!(" Title: {}", issue.title);
println!(" Author: {}", issue.author);
}
GitHubEvent::Unknown(event_type) => {
println!("Event: Unknown ({})", event_type);
}
}
}
/// Handle issue comment events.
async fn handle_issue_comment(
token: &str,
repository: &str,
comment: &cortex_engine::github::IssueCommentEvent,
) -> Result<()> {
use cortex_engine::github::GitHubClient;
println!("📝 Processing issue comment on #{}", comment.issue_number);
println!(" Author: {}", comment.author);
println!(" Action: {}", comment.action);
// Only process new comments (not edits or deletions)
if comment.action != "created" {
println!(" Skipping: action is '{}'", comment.action);
return Ok(());
}
// Check if comment mentions Cortex or starts with /Cortex
let is_cortex_mention = comment.body.contains("@Cortex")
|| comment.body.starts_with("/Cortex")
|| comment.body.to_lowercase().contains("Cortex help");
if !is_cortex_mention {
println!(" Skipping: no Cortex mention detected");
return Ok(());
}
println!(" 🤖 Cortex command detected!");
// Initialize GitHub client
let client = GitHubClient::new(token, repository)?;
// Parse the command from the comment
let command = parse_cortex_command(&comment.body);
// Add reaction to show we're processing
client.add_reaction(comment.comment_id, "eyes").await?;
// Process the command
let response = match command.as_str() {
"help" => get_help_message(),
"review" => {
if comment.is_pull_request {
"Starting code review... (not yet implemented)".to_string()
} else {
"This command is only available on pull requests.".to_string()
}
}
"fix" => "Analyzing and suggesting fixes... (not yet implemented)".to_string(),
_ => format!(
"Unknown command: `{}`\n\nUse `/Cortex help` to see available commands.",
command
),
};
// Post response comment
client
.create_comment(comment.issue_number, &response)
.await?;
// Add success reaction
client.add_reaction(comment.comment_id, "rocket").await?;
println!(" ✅ Response posted");
Ok(())
}
/// Handle pull request events.
async fn handle_pull_request(
token: &str,
repository: &str,
pr: &cortex_engine::github::PullRequestEvent,
) -> Result<()> {
use cortex_engine::github::GitHubClient;
println!("🔀 Processing pull request #{}", pr.number);
println!(" Title: {}", pr.title);
println!(" Action: {}", pr.action);
println!(" Author: {}", pr.author);
// Only process opened or synchronized PRs
if !matches!(pr.action.as_str(), "opened" | "synchronize" | "reopened") {
println!(" Skipping: action is '{}'", pr.action);
return Ok(());
}
let client = GitHubClient::new(token, repository)?;
// Auto-review on PR open (if enabled)
if pr.action == "opened" {
println!(" 📋 New PR opened - preparing welcome message");
let welcome_message = format!(
"👋 Thanks for opening this PR, @{}!\n\n\
I'm Cortex, your AI coding assistant. I can help with:\n\
- `/Cortex review` - Get a code review\n\
- `/Cortex help` - See all available commands\n\n\
I'll analyze this PR automatically when ready.",
pr.author
);
client.create_comment(pr.number, &welcome_message).await?;
}
// For synchronize events (new commits pushed)
if pr.action == "synchronize" {
println!(" 🔄 New commits pushed to PR");
// Could trigger re-review here
}
Ok(())
}
/// Handle pull request review events.
async fn handle_pull_request_review(
_token: &str,
_repository: &str,
review: &cortex_engine::github::PullRequestReviewEvent,
) -> Result<()> {
println!("📝 Processing PR review on #{}", review.pr_number);
println!(" Reviewer: {}", review.reviewer);
println!(" State: {}", review.state);
println!(" Action: {}", review.action);
// Could respond to review requests here
println!(" ℹ️ PR review events not yet implemented");
Ok(())
}
/// Handle issue events.
async fn handle_issue(
token: &str,
repository: &str,
issue: &cortex_engine::github::IssueEvent,
) -> Result<()> {
use cortex_engine::github::GitHubClient;
println!("📋 Processing issue #{}", issue.number);
println!(" Title: {}", issue.title);
println!(" Action: {}", issue.action);
// Only greet on new issues
if issue.action != "opened" {
println!(" Skipping: action is '{}'", issue.action);
return Ok(());
}
let client = GitHubClient::new(token, repository)?;
// Check if issue mentions Cortex
let is_cortex_related = issue.title.to_lowercase().contains("Cortex")
|| issue.body.to_lowercase().contains("Cortex")
|| issue
.labels
.iter()
.any(|l| l.to_lowercase().contains("Cortex"));
if is_cortex_related {
let greeting = format!(
"👋 Thanks for opening this issue, @{}!\n\n\
I'm Cortex, your AI coding assistant. I'll analyze this issue and provide suggestions.\n\n\
In the meantime, you can use `/Cortex help` to see what I can do.",
issue.author
);
client.create_comment(issue.number, &greeting).await?;
}
Ok(())
}
/// Parse a Cortex command from comment text.
fn parse_cortex_command(text: &str) -> String {
// Look for /Cortex <command> pattern
if let Some(pos) = text.find("/Cortex") {
let after_Cortex = &text[pos + 7..];
let command = after_Cortex.split_whitespace().next().unwrap_or("help");
return command.to_string();
}
// Look for @Cortex <command> pattern
if let Some(pos) = text.find("@Cortex") {
let after_Cortex = &text[pos + 7..];
let command = after_Cortex.split_whitespace().next().unwrap_or("help");
return command.to_string();
}
"help".to_string()
}
/// Get help message for Cortex commands.
fn get_help_message() -> String {
r#"## 🤖 Cortex Commands
| Command | Description |
|---------|-------------|
| `/Cortex help` | Show this help message |
| `/Cortex review` | Request a code review (PRs only) |
| `/Cortex fix` | Suggest fixes for issues |
| `/Cortex explain` | Explain the code changes |
| `/Cortex test` | Suggest tests for changes |
### Tips
- Mention `@Cortex` anywhere in your comment to get my attention
- I automatically review new pull requests when configured
- Use labels like `Cortex:review` to trigger specific actions
[Learn more](https://docs.cortex.ai/github)"#
.to_string()
}
/// Check GitHub Actions installation status.
async fn run_status(args: StatusArgs) -> Result<()> {
let repo_path = args.path.unwrap_or_else(|| PathBuf::from("."));
let mut status = InstallationStatus::default();
// Check for workflow files
let workflows_dir = repo_path.join(".github").join("workflows");
if workflows_dir.exists() {
for entry in std::fs::read_dir(&workflows_dir)? {
let entry = entry?;
let path = entry.path();
if path.extension().is_some_and(|e| e == "yml" || e == "yaml") {
let content = std::fs::read_to_string(&path)?;
if content.contains("Cortex") {
status.workflow_installed = true;
status.workflow_path = Some(path.clone());
// Check workflow features
if content.contains("issue_comment") {
status.features.push("issue_comment".to_string());
}
if content.contains("pull_request") {
status.features.push("pull_request".to_string());
}
if content.contains("issues") {
status.features.push("issues".to_string());
}
break;
}
}
}
}
// Check for .github directory
status.github_dir_exists = repo_path.join(".github").exists();
// Check if we're in a git repo
status.is_git_repo = repo_path.join(".git").exists();
if args.json {
let json = serde_json::to_string_pretty(&status)?;
println!("{}", json);
return Ok(());
}
println!("GitHub Actions Status");
println!("{}", "=".repeat(40));
println!();
if !status.is_git_repo {
println!("⚠️ Not a git repository");
println!(" Run this command from a git repository root.");
return Ok(());
}
if !status.github_dir_exists {
println!("❌ .github directory not found");
println!(" Run `Cortex github install` to set up GitHub Actions.");
return Ok(());
}
if status.workflow_installed {
println!("✅ Cortex workflow installed");
if let Some(ref path) = status.workflow_path {
println!(" Path: {}", path.display());
}
println!();
println!("Features enabled:");
for feature in &status.features {
println!(" • {}", feature);
}
} else {
println!("❌ Cortex workflow not found");
println!(" Run `Cortex github install` to set up GitHub Actions.");
}
Ok(())
}
/// Installation status information.
#[derive(Debug, Default, serde::Serialize)]
struct InstallationStatus {
is_git_repo: bool,
github_dir_exists: bool,
workflow_installed: bool,
workflow_path: Option<PathBuf>,
features: Vec<String>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_cortex_command() {
assert_eq!(parse_cortex_command("/Cortex help"), "help");
assert_eq!(parse_cortex_command("/Cortex review"), "review");
assert_eq!(parse_cortex_command("@Cortex fix"), "fix");
assert_eq!(parse_cortex_command("Please @Cortex help me"), "help");
assert_eq!(parse_cortex_command("No command here"), "help");
}
#[test]
fn test_get_help_message() {
let help = get_help_message();
assert!(help.contains("/Cortex help"));
assert!(help.contains("/Cortex review"));
}
}