gnostr_asyncgit/
branches.rs

1use std::sync::{Arc, Mutex};
2
3use crate::{
4	AsyncGitNotification,
5	asyncjob::{AsyncJob, RunParams},
6	error::Result,
7	sync::{BranchInfo, RepoPath, branch::get_branches_info},
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 =
66						get_branches_info(&repo, local_branches);
67
68					JobState::Response(branches)
69				}
70				JobState::Response(result) => {
71					JobState::Response(result)
72				}
73			});
74		}
75
76		Ok(AsyncGitNotification::Branches)
77	}
78}