ratatui_toolkit/widgets/markdown_widget/state/git_stats_state/methods/
update.rs

1//! Update git stats method for GitStatsState.
2
3use std::path::Path;
4use std::time::Instant;
5
6use crate::widgets::markdown_widget::foundation::types::GitStats;
7use crate::widgets::markdown_widget::state::git_stats_state::helpers::compute_git_stats;
8use crate::widgets::markdown_widget::state::git_stats_state::GitStatsState;
9
10/// Update interval for git stats (in seconds).
11const GIT_STATS_UPDATE_INTERVAL_SECS: u64 = 2;
12
13impl GitStatsState {
14    /// Update git stats if show is enabled and enough time has passed.
15    ///
16    /// This method should be called periodically (e.g., in the render loop).
17    /// It only computes stats every 2 seconds to avoid excessive git calls.
18    ///
19    /// # Arguments
20    ///
21    /// * `source_path` - The path to the source file, if any.
22    ///
23    /// # Returns
24    ///
25    /// `true` if stats were updated, `false` otherwise.
26    pub fn update(&mut self, source_path: Option<&Path>) -> bool {
27        if !self.show {
28            return false;
29        }
30
31        let should_update = match self.last_update {
32            Some(last_update) => last_update.elapsed().as_secs() >= GIT_STATS_UPDATE_INTERVAL_SECS,
33            None => true, // First update
34        };
35
36        if should_update {
37            let (adds, modified, dels) = compute_git_stats(source_path);
38            self.cache = Some(GitStats {
39                additions: adds,
40                modified,
41                deletions: dels,
42            });
43            self.last_update = Some(Instant::now());
44            true
45        } else {
46            false
47        }
48    }
49}