1#![deny(unsafe_code)]
13
14use crate::prompts::template_context::TemplateContext;
15use crate::prompts::template_engine::Template;
16use std::collections::HashMap;
17use std::fmt::Write;
18use std::fs;
19use std::path::Path;
20
21#[derive(Debug, Clone)]
23pub struct FileConflict {
24 pub conflict_content: String,
26 pub current_content: String,
28}
29
30#[cfg(test)]
46pub fn build_conflict_resolution_prompt(
47 conflicts: &HashMap<String, FileConflict>,
48 prompt_md_content: Option<&str>,
49 plan_content: Option<&str>,
50) -> String {
51 let template_content = include_str!("templates/conflict_resolution.txt");
52 let template = Template::new(template_content);
53
54 let context = format_context_section(prompt_md_content, plan_content);
55 let conflicts_section = format_conflicts_section(conflicts);
56
57 let variables = HashMap::from([
58 ("CONTEXT", context),
59 ("CONFLICTS", conflicts_section.clone()),
60 ]);
61
62 template.render(&variables).unwrap_or_else(|e| {
63 eprintln!("Warning: Failed to render conflict resolution template: {e}");
64 let fallback_template_content = include_str!("templates/conflict_resolution_fallback.txt");
66 let fallback_template = Template::new(fallback_template_content);
67 fallback_template.render(&variables).unwrap_or_else(|e| {
68 eprintln!("Critical: Failed to render fallback template: {e}");
69 format!(
71 "# MERGE CONFLICT RESOLUTION\n\nResolve these conflicts:\n\n{}",
72 &conflicts_section
73 )
74 })
75 })
76}
77
78pub fn build_conflict_resolution_prompt_with_context(
90 context: &TemplateContext,
91 conflicts: &HashMap<String, FileConflict>,
92 prompt_md_content: Option<&str>,
93 plan_content: Option<&str>,
94) -> String {
95 let template_content = context
96 .registry()
97 .get_template("conflict_resolution")
98 .unwrap_or_else(|_| include_str!("templates/conflict_resolution.txt").to_string());
99 let template = Template::new(&template_content);
100
101 let ctx_section = format_context_section(prompt_md_content, plan_content);
102 let conflicts_section = format_conflicts_section(conflicts);
103
104 let variables = HashMap::from([
105 ("CONTEXT", ctx_section),
106 ("CONFLICTS", conflicts_section.clone()),
107 ]);
108
109 template.render(&variables).unwrap_or_else(|e| {
110 eprintln!("Warning: Failed to render conflict resolution template: {e}");
111 let fallback_template_content = context
113 .registry()
114 .get_template("conflict_resolution_fallback")
115 .unwrap_or_else(|_| {
116 include_str!("templates/conflict_resolution_fallback.txt").to_string()
117 });
118 let fallback_template = Template::new(&fallback_template_content);
119 fallback_template.render(&variables).unwrap_or_else(|e| {
120 eprintln!("Critical: Failed to render fallback template: {e}");
121 format!(
123 "# MERGE CONFLICT RESOLUTION\n\nResolve these conflicts:\n\n{}",
124 &conflicts_section
125 )
126 })
127 })
128}
129
130fn format_context_section(prompt_md_content: Option<&str>, plan_content: Option<&str>) -> String {
135 let mut context = String::new();
136
137 if let Some(prompt_md) = prompt_md_content {
139 context.push_str("## Task Context\n\n");
140 context.push_str("The user was working on the following task:\n\n");
141 context.push_str("```\n");
142 context.push_str(prompt_md);
143 context.push_str("\n```\n\n");
144 }
145
146 if let Some(plan) = plan_content {
148 context.push_str("## Implementation Plan\n\n");
149 context.push_str("The following plan was being implemented:\n\n");
150 context.push_str("```\n");
151 context.push_str(plan);
152 context.push_str("\n```\n\n");
153 }
154
155 context
156}
157
158fn format_conflicts_section(conflicts: &HashMap<String, FileConflict>) -> String {
163 let mut section = String::new();
164
165 for (path, conflict) in conflicts {
166 writeln!(section, "### {path}\n\n").unwrap();
167 section.push_str("Current state (with conflict markers):\n\n");
168 section.push_str("```");
169 section.push_str(&get_language_marker(path));
170 section.push('\n');
171 section.push_str(&conflict.current_content);
172 section.push_str("\n```\n\n");
173
174 if !conflict.conflict_content.is_empty() {
175 section.push_str("Conflict sections:\n\n");
176 section.push_str("```\n");
177 section.push_str(&conflict.conflict_content);
178 section.push_str("\n```\n\n");
179 }
180 }
181
182 section
183}
184
185fn get_language_marker(path: &str) -> String {
187 let ext = Path::new(path)
188 .extension()
189 .and_then(|e| e.to_str())
190 .unwrap_or("");
191
192 match ext {
193 "rs" => "rust",
194 "py" => "python",
195 "js" | "jsx" => "javascript",
196 "ts" | "tsx" => "typescript",
197 "go" => "go",
198 "java" => "java",
199 "c" | "h" => "c",
200 "cpp" | "hpp" | "cc" | "cxx" => "cpp",
201 "cs" => "csharp",
202 "php" => "php",
203 "rb" => "ruby",
204 "swift" => "swift",
205 "kt" => "kotlin",
206 "scala" => "scala",
207 "sh" | "bash" | "zsh" => "bash",
208 "fish" => "fish",
209 "yaml" | "yml" => "yaml",
210 "json" => "json",
211 "toml" => "toml",
212 "md" | "markdown" => "markdown",
213 "txt" => "text",
214 "html" => "html",
215 "css" | "scss" | "less" => "css",
216 "xml" => "xml",
217 "sql" => "sql",
218 _ => "",
219 }
220 .to_string()
221}
222
223#[derive(Debug, Clone)]
225pub struct BranchInfo {
226 pub current_branch: String,
228 pub upstream_branch: String,
230 pub current_commits: Vec<String>,
232 pub upstream_commits: Vec<String>,
234 pub diverging_count: usize,
236}
237
238pub fn build_enhanced_conflict_resolution_prompt(
251 context: &TemplateContext,
252 conflicts: &HashMap<String, FileConflict>,
253 branch_info: Option<&BranchInfo>,
254 prompt_md_content: Option<&str>,
255 plan_content: Option<&str>,
256) -> String {
257 let template_content = context
258 .registry()
259 .get_template("conflict_resolution")
260 .unwrap_or_else(|_| include_str!("templates/conflict_resolution.txt").to_string());
261 let template = Template::new(&template_content);
262
263 let mut ctx_section = format_context_section(prompt_md_content, plan_content);
264
265 if let Some(info) = branch_info {
267 ctx_section.push_str(&format_branch_info_section(info));
268 }
269
270 let conflicts_section = format_conflicts_section(conflicts);
271
272 let variables = HashMap::from([
273 ("CONTEXT", ctx_section),
274 ("CONFLICTS", conflicts_section.clone()),
275 ]);
276
277 template.render(&variables).unwrap_or_else(|e| {
278 eprintln!("Warning: Failed to render conflict resolution template: {e}");
279 let fallback_template_content = context
281 .registry()
282 .get_template("conflict_resolution_fallback")
283 .unwrap_or_else(|_| {
284 include_str!("templates/conflict_resolution_fallback.txt").to_string()
285 });
286 let fallback_template = Template::new(&fallback_template_content);
287 fallback_template.render(&variables).unwrap_or_else(|e| {
288 eprintln!("Critical: Failed to render fallback template: {e}");
289 format!(
291 "# MERGE CONFLICT RESOLUTION\n\nResolve these conflicts:\n\n{}",
292 &conflicts_section
293 )
294 })
295 })
296}
297
298fn format_branch_info_section(info: &BranchInfo) -> String {
303 let mut section = String::new();
304
305 section.push_str("## Branch Information\n\n");
306 section.push_str(&format!(
307 "- **Current branch**: `{}`\n",
308 info.current_branch
309 ));
310 section.push_str(&format!(
311 "- **Target branch**: `{}`\n",
312 info.upstream_branch
313 ));
314 section.push_str(&format!(
315 "- **Diverging commits**: {}\n\n",
316 info.diverging_count
317 ));
318
319 if !info.current_commits.is_empty() {
320 section.push_str("### Recent commits on current branch:\n\n");
321 for (i, msg) in info.current_commits.iter().enumerate().take(5) {
322 section.push_str(&format!("{}. {}\n", i + 1, msg));
323 }
324 section.push('\n');
325 }
326
327 if !info.upstream_commits.is_empty() {
328 section.push_str("### Recent commits on target branch:\n\n");
329 for (i, msg) in info.upstream_commits.iter().enumerate().take(5) {
330 section.push_str(&format!("{}. {}\n", i + 1, msg));
331 }
332 section.push('\n');
333 }
334
335 section
336}
337
338pub fn collect_branch_info(upstream_branch: &str) -> std::io::Result<BranchInfo> {
350 use std::process::Command;
351
352 let current_branch = Command::new("git")
354 .args(["rev-parse", "--abbrev-ref", "HEAD"])
355 .output()
356 .map_err(|e| std::io::Error::other(format!("git rev-parse failed: {e}")))?;
357
358 let current_branch = String::from_utf8_lossy(¤t_branch.stdout)
359 .trim()
360 .to_string();
361
362 let current_log = Command::new("git")
364 .args(["log", "--oneline", "-10", "HEAD"])
365 .output()
366 .map_err(|e| std::io::Error::other(format!("git log failed: {e}")))?;
367
368 let current_commits: Vec<String> = String::from_utf8_lossy(¤t_log.stdout)
369 .lines()
370 .map(|s| s.to_string())
371 .collect();
372
373 let upstream_log = Command::new("git")
375 .args(["log", "--oneline", "-10", upstream_branch])
376 .output()
377 .map_err(|e| std::io::Error::other(format!("git log failed: {e}")))?;
378
379 let upstream_commits: Vec<String> = String::from_utf8_lossy(&upstream_log.stdout)
380 .lines()
381 .map(|s| s.to_string())
382 .collect();
383
384 let diverging = Command::new("git")
386 .args([
387 "rev-list",
388 "--count",
389 "--left-right",
390 &format!("HEAD...{upstream_branch}"),
391 ])
392 .output()
393 .map_err(|e| std::io::Error::other(format!("git rev-list failed: {e}")))?;
394
395 let diverging_count = String::from_utf8_lossy(&diverging.stdout)
396 .split_whitespace()
397 .map(|s| s.parse::<usize>().unwrap_or(0))
398 .sum::<usize>();
399
400 Ok(BranchInfo {
401 current_branch,
402 upstream_branch: upstream_branch.to_string(),
403 current_commits,
404 upstream_commits,
405 diverging_count,
406 })
407}
408
409pub fn collect_conflict_info(
423 conflicted_paths: &[String],
424) -> std::io::Result<HashMap<String, FileConflict>> {
425 let mut conflicts = HashMap::new();
426
427 for path in conflicted_paths {
428 let current_content = fs::read_to_string(path)?;
430
431 let conflict_content = crate::git_helpers::get_conflict_markers_for_file(Path::new(path))?;
433
434 conflicts.insert(
435 path.clone(),
436 FileConflict {
437 conflict_content,
438 current_content,
439 },
440 );
441 }
442
443 Ok(conflicts)
444}
445
446#[cfg(test)]
447mod tests {
448 use super::*;
449
450 #[test]
451 fn test_build_conflict_resolution_prompt_no_mentions_rebase() {
452 let conflicts = HashMap::new();
453 let prompt = build_conflict_resolution_prompt(&conflicts, None, None);
454
455 assert!(!prompt.to_lowercase().contains("rebase"));
457 assert!(!prompt.to_lowercase().contains("rebasing"));
458
459 assert!(prompt.to_lowercase().contains("merge conflict"));
461 }
462
463 #[test]
464 fn test_build_conflict_resolution_prompt_with_context() {
465 let mut conflicts = HashMap::new();
466 conflicts.insert(
467 "test.rs".to_string(),
468 FileConflict {
469 conflict_content: "<<<<<<< ours\nfn foo() {}\n=======\nfn bar() {}\n>>>>>>> theirs"
470 .to_string(),
471 current_content: "<<<<<<< ours\nfn foo() {}\n=======\nfn bar() {}\n>>>>>>> theirs"
472 .to_string(),
473 },
474 );
475
476 let prompt_md = "Add a new feature";
477 let plan = "1. Create foo function\n2. Create bar function";
478
479 let prompt = build_conflict_resolution_prompt(&conflicts, Some(prompt_md), Some(plan));
480
481 assert!(prompt.contains("Add a new feature"));
483
484 assert!(prompt.contains("Create foo function"));
486 assert!(prompt.contains("Create bar function"));
487
488 assert!(prompt.contains("test.rs"));
490
491 assert!(!prompt.to_lowercase().contains("rebase"));
493 }
494
495 #[test]
496 fn test_get_language_marker() {
497 assert_eq!(get_language_marker("file.rs"), "rust");
498 assert_eq!(get_language_marker("file.py"), "python");
499 assert_eq!(get_language_marker("file.js"), "javascript");
500 assert_eq!(get_language_marker("file.ts"), "typescript");
501 assert_eq!(get_language_marker("file.go"), "go");
502 assert_eq!(get_language_marker("file.java"), "java");
503 assert_eq!(get_language_marker("file.cpp"), "cpp");
504 assert_eq!(get_language_marker("file.md"), "markdown");
505 assert_eq!(get_language_marker("file.yaml"), "yaml");
506 assert_eq!(get_language_marker("file.unknown"), "");
507 }
508
509 #[test]
510 fn test_format_context_section_with_both() {
511 let prompt_md = "Test prompt";
512 let plan = "Test plan";
513 let context = format_context_section(Some(prompt_md), Some(plan));
514
515 assert!(context.contains("## Task Context"));
516 assert!(context.contains("Test prompt"));
517 assert!(context.contains("## Implementation Plan"));
518 assert!(context.contains("Test plan"));
519 }
520
521 #[test]
522 fn test_format_context_section_with_prompt_only() {
523 let prompt_md = "Test prompt";
524 let context = format_context_section(Some(prompt_md), None);
525
526 assert!(context.contains("## Task Context"));
527 assert!(context.contains("Test prompt"));
528 assert!(!context.contains("## Implementation Plan"));
529 }
530
531 #[test]
532 fn test_format_context_section_with_plan_only() {
533 let plan = "Test plan";
534 let context = format_context_section(None, Some(plan));
535
536 assert!(!context.contains("## Task Context"));
537 assert!(context.contains("## Implementation Plan"));
538 assert!(context.contains("Test plan"));
539 }
540
541 #[test]
542 fn test_format_context_section_empty() {
543 let context = format_context_section(None, None);
544 assert!(context.is_empty());
545 }
546
547 #[test]
548 fn test_format_conflicts_section() {
549 let mut conflicts = HashMap::new();
550 conflicts.insert(
551 "src/test.rs".to_string(),
552 FileConflict {
553 conflict_content: "<<<<<<< ours\nx\n=======\ny\n>>>>>>> theirs".to_string(),
554 current_content: "<<<<<<< ours\nx\n=======\ny\n>>>>>>> theirs".to_string(),
555 },
556 );
557
558 let section = format_conflicts_section(&conflicts);
559
560 assert!(section.contains("### src/test.rs"));
561 assert!(section.contains("Current state (with conflict markers)"));
562 assert!(section.contains("```rust"));
563 assert!(section.contains("<<<<<<< ours"));
564 assert!(section.contains("Conflict sections"));
565 }
566
567 #[test]
568 fn test_template_is_used() {
569 let conflicts = HashMap::new();
571 let prompt = build_conflict_resolution_prompt(&conflicts, None, None);
572
573 assert!(prompt.contains("# MERGE CONFLICT RESOLUTION"));
575 assert!(prompt.contains("## Conflict Resolution Instructions"));
576 assert!(prompt.contains("## Optional JSON Output Format"));
577 assert!(prompt.contains("resolved_files"));
578 }
579
580 #[test]
581 fn test_build_conflict_resolution_prompt_with_registry_context() {
582 let context = TemplateContext::default();
583 let conflicts = HashMap::new();
584 let prompt =
585 build_conflict_resolution_prompt_with_context(&context, &conflicts, None, None);
586
587 assert!(!prompt.to_lowercase().contains("rebase"));
589 assert!(!prompt.to_lowercase().contains("rebasing"));
590
591 assert!(prompt.to_lowercase().contains("merge conflict"));
593 }
594
595 #[test]
596 fn test_build_conflict_resolution_prompt_with_registry_context_and_content() {
597 let context = TemplateContext::default();
598 let mut conflicts = HashMap::new();
599 conflicts.insert(
600 "test.rs".to_string(),
601 FileConflict {
602 conflict_content: "<<<<<<< ours\nfn foo() {}\n=======\nfn bar() {}\n>>>>>>> theirs"
603 .to_string(),
604 current_content: "<<<<<<< ours\nfn foo() {}\n=======\nfn bar() {}\n>>>>>>> theirs"
605 .to_string(),
606 },
607 );
608
609 let prompt_md = "Add a new feature";
610 let plan = "1. Create foo function\n2. Create bar function";
611
612 let prompt = build_conflict_resolution_prompt_with_context(
613 &context,
614 &conflicts,
615 Some(prompt_md),
616 Some(plan),
617 );
618
619 assert!(prompt.contains("Add a new feature"));
621
622 assert!(prompt.contains("Create foo function"));
624 assert!(prompt.contains("Create bar function"));
625
626 assert!(prompt.contains("test.rs"));
628
629 assert!(!prompt.to_lowercase().contains("rebase"));
631 }
632
633 #[test]
634 fn test_registry_context_based_matches_regular() {
635 let context = TemplateContext::default();
636 let mut conflicts = HashMap::new();
637 conflicts.insert(
638 "test.rs".to_string(),
639 FileConflict {
640 conflict_content: "conflict".to_string(),
641 current_content: "current".to_string(),
642 },
643 );
644
645 let regular = build_conflict_resolution_prompt(&conflicts, Some("prompt"), Some("plan"));
646 let with_context = build_conflict_resolution_prompt_with_context(
647 &context,
648 &conflicts,
649 Some("prompt"),
650 Some("plan"),
651 );
652 assert_eq!(regular, with_context);
654 }
655
656 #[test]
657 fn test_branch_info_struct_exists() {
658 let info = BranchInfo {
659 current_branch: "feature".to_string(),
660 upstream_branch: "main".to_string(),
661 current_commits: vec!["abc123 feat: add thing".to_string()],
662 upstream_commits: vec!["def456 fix: bug".to_string()],
663 diverging_count: 5,
664 };
665 assert_eq!(info.current_branch, "feature");
666 assert_eq!(info.diverging_count, 5);
667 }
668
669 #[test]
670 fn test_format_branch_info_section() {
671 let info = BranchInfo {
672 current_branch: "feature".to_string(),
673 upstream_branch: "main".to_string(),
674 current_commits: vec!["abc123 feat: add thing".to_string()],
675 upstream_commits: vec!["def456 fix: bug".to_string()],
676 diverging_count: 5,
677 };
678
679 let section = format_branch_info_section(&info);
680
681 assert!(section.contains("Branch Information"));
682 assert!(section.contains("feature"));
683 assert!(section.contains("main"));
684 assert!(section.contains("5"));
685 assert!(section.contains("abc123"));
686 assert!(section.contains("def456"));
687 }
688
689 #[test]
690 fn test_enhanced_prompt_with_branch_info() {
691 let context = TemplateContext::default();
692 let mut conflicts = HashMap::new();
693 conflicts.insert(
694 "test.rs".to_string(),
695 FileConflict {
696 conflict_content: "conflict".to_string(),
697 current_content: "current".to_string(),
698 },
699 );
700
701 let branch_info = BranchInfo {
702 current_branch: "feature".to_string(),
703 upstream_branch: "main".to_string(),
704 current_commits: vec!["abc123 my change".to_string()],
705 upstream_commits: vec!["def456 their change".to_string()],
706 diverging_count: 3,
707 };
708
709 let prompt = build_enhanced_conflict_resolution_prompt(
710 &context,
711 &conflicts,
712 Some(&branch_info),
713 None,
714 None,
715 );
716
717 assert!(prompt.contains("Branch Information"));
719 assert!(prompt.contains("feature"));
720 assert!(prompt.contains("main"));
721 assert!(prompt.contains("3")); assert!(!prompt.to_lowercase().contains("rebase"));
725 }
726}