ratatui_toolkit/widgets/code_diff/foundation/helpers/
get_git_diff.rs

1//! Fetch git diff from current working directory.
2
3use std::process::Command;
4
5/// Get git diff from the current working directory.
6///
7/// Tries in order:
8/// 1. Unstaged changes (`git diff`)
9/// 2. Staged changes (`git diff --cached`)
10/// 3. Last commit diff (`git diff HEAD~1`)
11///
12/// Returns empty string if not in a git repository or no changes found.
13///
14/// # Example
15///
16/// ```rust,no_run
17/// use ratatui_toolkit::code_diff::helpers::get_git_diff;
18///
19/// let diff = get_git_diff();
20/// if !diff.is_empty() {
21///     println!("Found changes:\n{}", diff);
22/// }
23/// ```
24pub fn get_git_diff() -> String {
25    // Try unstaged changes first
26    if let Ok(output) = Command::new("git").args(["diff"]).output() {
27        let diff = String::from_utf8_lossy(&output.stdout).to_string();
28        if !diff.trim().is_empty() {
29            return diff;
30        }
31    }
32
33    // Try staged changes
34    if let Ok(output) = Command::new("git").args(["diff", "--cached"]).output() {
35        let diff = String::from_utf8_lossy(&output.stdout).to_string();
36        if !diff.trim().is_empty() {
37            return diff;
38        }
39    }
40
41    // Fallback to last commit diff
42    if let Ok(output) = Command::new("git").args(["diff", "HEAD~1"]).output() {
43        let diff = String::from_utf8_lossy(&output.stdout).to_string();
44        if !diff.trim().is_empty() {
45            return diff;
46        }
47    }
48
49    // If all else fails, return empty
50    String::new()
51}