1use std::process::Command;
13use serde::Serialize;
14
15#[derive(Debug, Clone, Serialize)]
18pub struct BranchResult {
19 pub success: bool,
20 pub branch_name: String,
21 pub message: String,
22}
23
24#[derive(Debug, Clone, Serialize)]
25pub struct CommitResult {
26 pub success: bool,
27 pub commit_hash: Option<String>,
28 pub message: String,
29 pub files_staged: Vec<String>,
30}
31
32#[derive(Debug, Clone, Serialize)]
33pub struct PullRequestResult {
34 pub success: bool,
35 pub pr_number: Option<u64>,
36 pub pr_url: Option<String>,
37 pub message: String,
38}
39
40#[derive(Debug, Clone, Serialize)]
41pub struct PrStatusResult {
42 pub success: bool,
43 pub state: String,
44 pub mergeable: Option<bool>,
45 pub ci_status: String,
46 pub message: String,
47}
48
49fn sanitize_branch_name(name: &str) -> String {
54 let sanitized: String = name
55 .chars()
56 .map(|c| {
57 if c.is_alphanumeric() || c == '-' || c == '_' || c == '/' {
58 c
59 } else {
60 '-'
61 }
62 })
63 .collect();
64
65 let collapsed: String = sanitized
66 .split('-')
67 .filter(|s| !s.is_empty())
68 .collect::<Vec<_>>()
69 .join("-");
70
71 let trimmed = collapsed
72 .split('/')
73 .filter(|s| !s.is_empty() && *s != "..")
74 .collect::<Vec<_>>()
75 .join("/");
76
77 let final_name = trimmed.trim_matches(|c| c == '/' || c == '-' || c == '.');
78
79 if final_name.is_empty() || final_name.ends_with(".lock") {
80 "fix/tokenectomy-patch".to_string()
81 } else {
82 final_name.to_string()
83 }
84}
85
86fn sanitize_commit_message(msg: &str) -> String {
88 msg.chars().filter(|c| *c != '\0').take(500).collect()
89}
90
91fn ensure_git_repo() -> Result<(), String> {
95 let output = Command::new("git")
96 .args(["rev-parse", "--is-inside-work-tree"])
97 .output()
98 .map_err(|e| format!("git not found: {}", e))?;
99
100 if output.status.success() {
101 Ok(())
102 } else {
103 Err("Not inside a git repository".to_string())
104 }
105}
106
107fn detect_github_remote() -> Option<(String, String)> {
110 let output = Command::new("git")
111 .args(["remote", "get-url", "origin"])
112 .output()
113 .ok()?;
114
115 if !output.status.success() {
116 return None;
117 }
118
119 let url = String::from_utf8_lossy(&output.stdout).trim().to_string();
120
121 if !url.contains("github.com") {
122 return None;
123 }
124
125 let tail = if url.starts_with("git@") {
126 url.trim_end_matches(".git").split(':').last()?.to_string()
127 } else {
128 url.trim_end_matches(".git")
129 .split("github.com/")
130 .last()?
131 .to_string()
132 };
133
134 let parts: Vec<&str> = tail.split('/').collect();
135 if parts.len() >= 2 {
136 Some((parts[0].to_string(), parts[1].to_string()))
137 } else {
138 None
139 }
140}
141
142fn get_current_branch() -> Option<String> {
144 Command::new("git")
145 .args(["rev-parse", "--abbrev-ref", "HEAD"])
146 .output()
147 .ok()
148 .and_then(|o| {
149 if o.status.success() {
150 Some(String::from_utf8_lossy(&o.stdout).trim().to_string())
151 } else {
152 None
153 }
154 })
155}
156
157pub fn create_fix_branch(branch_name: &str) -> BranchResult {
162 let safe_name = sanitize_branch_name(branch_name);
163
164 if let Err(msg) = ensure_git_repo() {
165 return BranchResult {
166 success: false,
167 branch_name: safe_name,
168 message: msg,
169 };
170 }
171
172 let has_changes = Command::new("git")
173 .args(["status", "--porcelain"])
174 .output()
175 .map(|o| !String::from_utf8_lossy(&o.stdout).trim().is_empty())
176 .unwrap_or(false);
177
178 let result = Command::new("git")
179 .args(["checkout", "-b", &safe_name])
180 .output();
181
182 match result {
183 Ok(output) if output.status.success() => BranchResult {
184 success: true,
185 branch_name: safe_name.clone(),
186 message: format!(
187 "Branch '{}' created and checked out successfully{}",
188 safe_name,
189 if has_changes {
190 " (note: working directory has uncommitted changes)"
191 } else {
192 ""
193 }
194 ),
195 },
196 Ok(output) => {
197 let stderr = String::from_utf8_lossy(&output.stderr);
198 if stderr.contains("already exists") {
199 match Command::new("git")
200 .args(["checkout", &safe_name])
201 .output()
202 {
203 Ok(o) if o.status.success() => BranchResult {
204 success: true,
205 branch_name: safe_name.clone(),
206 message: format!(
207 "Branch '{}' already exists, switched to it",
208 safe_name
209 ),
210 },
211 _ => BranchResult {
212 success: false,
213 branch_name: safe_name,
214 message: format!(
215 "Branch already exists and could not switch: {}",
216 stderr.trim()
217 ),
218 },
219 }
220 } else {
221 BranchResult {
222 success: false,
223 branch_name: safe_name,
224 message: format!("Failed to create branch: {}", stderr.trim()),
225 }
226 }
227 }
228 Err(e) => BranchResult {
229 success: false,
230 branch_name: safe_name,
231 message: format!("Git command failed: {}", e),
232 },
233 }
234}
235
236pub fn commit_fix(
239 files: &[String],
240 message: &str,
241 surgery_report: Option<&str>,
242) -> CommitResult {
243 let safe_message = sanitize_commit_message(message);
244
245 let full_message = if let Some(report) = surgery_report {
246 let safe_report = crate::redact::redact_secrets(report);
247 format!(
248 "{}\n\n--- Tokenectomy Surgery Report ---\n{}",
249 safe_message, safe_report
250 )
251 } else {
252 safe_message.clone()
253 };
254
255 let mut staged: Vec<String> = Vec::new();
256 for file in files {
257 if !crate::safety::is_path_safe(file) {
258 return CommitResult {
259 success: false,
260 commit_hash: None,
261 message: format!(
262 "Security Error: file '{}' is outside the current working directory",
263 file
264 ),
265 files_staged: staged,
266 };
267 }
268
269 match Command::new("git").args(["add", file]).output() {
270 Ok(output) if output.status.success() => {
271 staged.push(file.clone());
272 }
273 Ok(output) => {
274 let stderr = String::from_utf8_lossy(&output.stderr);
275 return CommitResult {
276 success: false,
277 commit_hash: None,
278 message: format!("Failed to stage '{}': {}", file, stderr.trim()),
279 files_staged: staged,
280 };
281 }
282 Err(e) => {
283 return CommitResult {
284 success: false,
285 commit_hash: None,
286 message: format!("Git add failed: {}", e),
287 files_staged: staged,
288 };
289 }
290 }
291 }
292
293 if staged.is_empty() {
294 return CommitResult {
295 success: false,
296 commit_hash: None,
297 message: "No files were staged for commit".to_string(),
298 files_staged: staged,
299 };
300 }
301
302 match Command::new("git")
303 .args(["commit", "-m", &full_message])
304 .output()
305 {
306 Ok(output) if output.status.success() => {
307 let hash = Command::new("git")
308 .args(["rev-parse", "--short", "HEAD"])
309 .output()
310 .ok()
311 .and_then(|o| {
312 if o.status.success() {
313 Some(String::from_utf8_lossy(&o.stdout).trim().to_string())
314 } else {
315 None
316 }
317 });
318
319 CommitResult {
320 success: true,
321 commit_hash: hash,
322 message: format!("Committed {} file(s) successfully", staged.len()),
323 files_staged: staged,
324 }
325 }
326 Ok(output) => {
327 let stderr = String::from_utf8_lossy(&output.stderr);
328 CommitResult {
329 success: false,
330 commit_hash: None,
331 message: format!("Commit failed: {}", stderr.trim()),
332 files_staged: staged,
333 }
334 }
335 Err(e) => CommitResult {
336 success: false,
337 commit_hash: None,
338 message: format!("Git commit failed: {}", e),
339 files_staged: staged,
340 },
341 }
342}
343
344pub async fn open_pull_request(
349 title: &str,
350 body: &str,
351 base_branch: Option<&str>,
352 head_branch: Option<&str>,
353) -> PullRequestResult {
354 let github_token = match std::env::var("GITHUB_TOKEN") {
355 Ok(t) if !t.is_empty() => t,
356 _ => {
357 return PullRequestResult {
358 success: false,
359 pr_number: None,
360 pr_url: None,
361 message: "GITHUB_TOKEN environment variable is not set.\n\
362 Set it to create PRs:\n \
363 export GITHUB_TOKEN=your_personal_access_token"
364 .to_string(),
365 }
366 }
367 };
368
369 let (owner, repo) = match detect_github_remote() {
370 Some(r) => r,
371 None => {
372 return PullRequestResult {
373 success: false,
374 pr_number: None,
375 pr_url: None,
376 message: "Could not detect GitHub remote. Ensure 'origin' points to a github.com repository."
377 .to_string(),
378 }
379 }
380 };
381
382 let head = head_branch
383 .map(|s| s.to_string())
384 .or_else(get_current_branch)
385 .unwrap_or_else(|| "fix/tokenectomy-patch".to_string());
386
387 let base = base_branch.unwrap_or("main");
388
389 let push = tokio::process::Command::new("git")
391 .args(["push", "-u", "origin", &head])
392 .output()
393 .await;
394
395 match push {
396 Ok(o) if !o.status.success() => {
397 let stderr = String::from_utf8_lossy(&o.stderr);
398 return PullRequestResult {
399 success: false,
400 pr_number: None,
401 pr_url: None,
402 message: format!("Failed to push branch '{}' to origin: {}", head, stderr.trim()),
403 };
404 }
405 Err(e) => {
406 return PullRequestResult {
407 success: false,
408 pr_number: None,
409 pr_url: None,
410 message: format!("Git push command failed: {}", e),
411 };
412 }
413 _ => {}
414 }
415
416 let safe_body = crate::redact::redact_secrets(body);
418
419 let pr_payload = serde_json::json!({
420 "title": title,
421 "body": safe_body,
422 "head": head,
423 "base": base
424 });
425
426 let client = match reqwest::Client::builder()
427 .timeout(std::time::Duration::from_secs(15))
428 .build()
429 {
430 Ok(c) => c,
431 Err(e) => {
432 return PullRequestResult {
433 success: false,
434 pr_number: None,
435 pr_url: None,
436 message: format!("Failed to create HTTP client: {}", e),
437 }
438 }
439 };
440
441 let url = format!(
442 "https://api.github.com/repos/{}/{}/pulls",
443 owner, repo
444 );
445
446 let resp = client
447 .post(&url)
448 .header("Authorization", format!("Bearer {}", github_token))
449 .header("Accept", "application/vnd.github+json")
450 .header("User-Agent", "tokenectomy-git")
451 .header("X-GitHub-Api-Version", "2022-11-28")
452 .json(&pr_payload)
453 .send()
454 .await;
455
456 match resp {
457 Ok(r) if r.status().is_success() => {
458 let json: serde_json::Value = r.json().await.unwrap_or_default();
459 let pr_number = json.get("number").and_then(|n| n.as_u64());
460 let pr_url = json
461 .get("html_url")
462 .and_then(|u| u.as_str())
463 .map(|s| s.to_string());
464
465 PullRequestResult {
466 success: true,
467 pr_number,
468 pr_url: pr_url.clone(),
469 message: format!(
470 "✅ Pull Request created successfully: {}",
471 pr_url.as_deref().unwrap_or("(url unavailable)")
472 ),
473 }
474 }
475 Ok(r) => {
476 let status = r.status();
477 let err_body = r.text().await.unwrap_or_default();
478 PullRequestResult {
479 success: false,
480 pr_number: None,
481 pr_url: None,
482 message: format!("GitHub API error ({}): {}", status, err_body),
483 }
484 }
485 Err(e) => PullRequestResult {
486 success: false,
487 pr_number: None,
488 pr_url: None,
489 message: format!("GitHub API request failed: {}", e),
490 },
491 }
492}
493
494pub async fn get_pr_status(pr_number: u64) -> PrStatusResult {
496 let github_token = match std::env::var("GITHUB_TOKEN") {
497 Ok(t) if !t.is_empty() => t,
498 _ => {
499 return PrStatusResult {
500 success: false,
501 state: "unknown".to_string(),
502 mergeable: None,
503 ci_status: "unknown".to_string(),
504 message: "GITHUB_TOKEN not set".to_string(),
505 }
506 }
507 };
508
509 let (owner, repo) = match detect_github_remote() {
510 Some(r) => r,
511 None => {
512 return PrStatusResult {
513 success: false,
514 state: "unknown".to_string(),
515 mergeable: None,
516 ci_status: "unknown".to_string(),
517 message: "Could not detect GitHub remote".to_string(),
518 }
519 }
520 };
521
522 let client = match reqwest::Client::builder()
523 .timeout(std::time::Duration::from_secs(15))
524 .build()
525 {
526 Ok(c) => c,
527 Err(e) => {
528 return PrStatusResult {
529 success: false,
530 state: "unknown".to_string(),
531 mergeable: None,
532 ci_status: "unknown".to_string(),
533 message: format!("HTTP client error: {}", e),
534 }
535 }
536 };
537
538 let url = format!(
539 "https://api.github.com/repos/{}/{}/pulls/{}",
540 owner, repo, pr_number
541 );
542
543 let resp = client
544 .get(&url)
545 .header("Authorization", format!("Bearer {}", github_token))
546 .header("Accept", "application/vnd.github+json")
547 .header("User-Agent", "tokenectomy-git")
548 .header("X-GitHub-Api-Version", "2022-11-28")
549 .send()
550 .await;
551
552 match resp {
553 Ok(r) if r.status().is_success() => {
554 let json: serde_json::Value = r.json().await.unwrap_or_default();
555 let state = json
556 .get("state")
557 .and_then(|s| s.as_str())
558 .unwrap_or("unknown")
559 .to_string();
560 let mergeable = json.get("mergeable").and_then(|m| m.as_bool());
561
562 let head_sha = json
563 .get("head")
564 .and_then(|h| h.get("sha"))
565 .and_then(|s| s.as_str())
566 .unwrap_or("");
567
568 let ci_status = if !head_sha.is_empty() {
569 let ci_url = format!(
570 "https://api.github.com/repos/{}/{}/commits/{}/status",
571 owner, repo, head_sha
572 );
573 match client
574 .get(&ci_url)
575 .header("Authorization", format!("Bearer {}", github_token))
576 .header("Accept", "application/vnd.github+json")
577 .header("User-Agent", "tokenectomy-git")
578 .header("X-GitHub-Api-Version", "2022-11-28")
579 .send()
580 .await
581 {
582 Ok(cr) if cr.status().is_success() => {
583 let ci_json: serde_json::Value =
584 cr.json().await.unwrap_or_default();
585 ci_json
586 .get("state")
587 .and_then(|s| s.as_str())
588 .unwrap_or("unknown")
589 .to_string()
590 }
591 _ => "unknown".to_string(),
592 }
593 } else {
594 "unknown".to_string()
595 };
596
597 PrStatusResult {
598 success: true,
599 state: state.clone(),
600 mergeable,
601 ci_status: ci_status.clone(),
602 message: format!(
603 "PR #{}: state={}, mergeable={:?}, CI={}",
604 pr_number, state, mergeable, ci_status
605 ),
606 }
607 }
608 Ok(r) => {
609 let status = r.status();
610 PrStatusResult {
611 success: false,
612 state: "unknown".to_string(),
613 mergeable: None,
614 ci_status: "unknown".to_string(),
615 message: format!("GitHub API error: {}", status),
616 }
617 }
618 Err(e) => PrStatusResult {
619 success: false,
620 state: "unknown".to_string(),
621 mergeable: None,
622 ci_status: "unknown".to_string(),
623 message: format!("GitHub API request failed: {}", e),
624 },
625 }
626}
627
628#[cfg(test)]
629mod tests {
630 use super::*;
631
632 #[test]
633 fn test_sanitize_branch_name() {
634 assert_eq!(sanitize_branch_name("fix/my-bug"), "fix/my-bug");
635 assert_eq!(sanitize_branch_name("fix: some bug!"), "fix-some-bug");
636 assert_eq!(
637 sanitize_branch_name("feat/hello world 123"),
638 "feat/hello-world-123"
639 );
640 assert_eq!(sanitize_branch_name(""), "fix/tokenectomy-patch");
641 assert_eq!(sanitize_branch_name("---"), "fix/tokenectomy-patch");
642 }
643
644 #[test]
645 fn test_sanitize_commit_message() {
646 let msg = "fix: resolve null pointer\0 issue";
647 let sanitized = sanitize_commit_message(msg);
648 assert!(!sanitized.contains('\0'));
649 assert!(sanitized.contains("fix: resolve null pointer issue"));
650 }
651
652 #[test]
653 fn test_sanitize_commit_message_truncates() {
654 let long_msg = "a".repeat(1000);
655 let sanitized = sanitize_commit_message(&long_msg);
656 assert_eq!(sanitized.len(), 500);
657 }
658
659 #[test]
660 fn test_adversary_fuzz_branch_name_edge_cases() {
661 let evil_input = "/evil/branch//";
663 let res = sanitize_branch_name(evil_input);
664 assert!(!res.starts_with('/'), "Branch name should not start with slash: {}", res);
665 assert!(!res.ends_with('/'), "Branch name should not end with slash: {}", res);
666 }
667}