gnostr_asyncgit/
branches.rs

1use std::sync::{Arc, Mutex};
2
3use crate::{
4    asyncjob::{AsyncJob, RunParams},
5    error::Result,
6    sync::{branch::get_branches_info, BranchInfo, RepoPath},
7    AsyncGitNotification,
8};
9
10enum JobState {
11    Request {
12        local_branches: bool,
13        repo: RepoPath,
14    },
15    Response(Result<Vec<BranchInfo>>),
16}
17
18///
19#[derive(Clone, Default)]
20pub struct AsyncBranchesJob {
21    state: Arc<Mutex<Option<JobState>>>,
22}
23
24///
25impl AsyncBranchesJob {
26    ///
27    pub fn new(repo: RepoPath, local_branches: bool) -> Self {
28        Self {
29            state: Arc::new(Mutex::new(Some(JobState::Request {
30                repo,
31                local_branches,
32            }))),
33        }
34    }
35
36    ///
37    pub fn result(&self) -> Option<Result<Vec<BranchInfo>>> {
38        if let Ok(mut state) = self.state.lock() {
39            if let Some(state) = state.take() {
40                return match state {
41                    JobState::Request { .. } => None,
42                    JobState::Response(result) => Some(result),
43                };
44            }
45        }
46
47        None
48    }
49}
50
51impl AsyncJob for AsyncBranchesJob {
52    type Notification = AsyncGitNotification;
53    type Progress = ();
54
55    fn run(
56        &mut self,
57        _params: RunParams<Self::Notification, Self::Progress>,
58    ) -> Result<Self::Notification> {
59        if let Ok(mut state) = self.state.lock() {
60            *state = state.take().map(|state| match state {
61                JobState::Request {
62                    local_branches,
63                    repo,
64                } => {
65                    let branches = get_branches_info(&repo, local_branches);
66
67                    JobState::Response(branches)
68                }
69                JobState::Response(result) => JobState::Response(result),
70            });
71        }
72
73        Ok(AsyncGitNotification::Branches)
74    }
75}