ratatui_toolkit/widgets/code_diff/widget/constructors/
from_git.rs

1//! Create CodeDiff from current git repository diff.
2
3use crate::widgets::code_diff::helpers::get_git_diff;
4use crate::widgets::code_diff::DiffConfig;
5
6use super::super::CodeDiff;
7
8impl CodeDiff {
9    /// Create a CodeDiff from the current git repository's diff.
10    ///
11    /// Tries in order:
12    /// 1. Unstaged changes (`git diff`)
13    /// 2. Staged changes (`git diff --cached`)
14    /// 3. Last commit (`git diff HEAD~1`)
15    ///
16    /// Returns an empty CodeDiff if not in a git repo or no changes found.
17    ///
18    /// # Example
19    ///
20    /// ```rust,no_run
21    /// use ratatui_toolkit::code_diff::CodeDiff;
22    ///
23    /// // Create a diff widget from current git changes
24    /// let diff = CodeDiff::from_git();
25    /// ```
26    pub fn from_git() -> Self {
27        let diff = get_git_diff();
28        if diff.trim().is_empty() {
29            Self::new()
30        } else {
31            Self::from_multi_file_diff(&diff)
32        }
33    }
34
35    /// Create a CodeDiff from git with custom config.
36    ///
37    /// This is a convenience method that combines `from_git()` with `with_config()`.
38    ///
39    /// # Example
40    ///
41    /// ```rust,no_run
42    /// use ratatui_toolkit::code_diff::{CodeDiff, DiffConfig};
43    ///
44    /// let diff = CodeDiff::from_git_with_config(
45    ///     DiffConfig::new()
46    ///         .sidebar_enabled(true)
47    ///         .show_line_numbers(true)
48    /// );
49    /// ```
50    pub fn from_git_with_config(config: DiffConfig) -> Self {
51        let diff = get_git_diff();
52        if diff.trim().is_empty() {
53            Self::new().with_config(config)
54        } else {
55            Self::from_multi_file_diff(&diff).with_config(config)
56        }
57    }
58}