use std::sync::Mutex;
use super::env::{BatchSsh, RemoteFailure, TransportUnknown};
use super::Reply;
struct Scripted {
op: &'static str,
outcome: Result<Reply, RemoteFailure>,
}
pub(super) struct Fake {
transport: Result<BatchSsh, TransportUnknown>,
scripted: Mutex<Vec<Option<Scripted>>>,
asked: Mutex<Vec<String>>,
heard: Mutex<Vec<String>>,
}
impl Fake {
pub(super) fn answering(
transport: Result<BatchSsh, TransportUnknown>,
outcomes: impl IntoIterator<Item = (&'static str, Result<Reply, RemoteFailure>)>,
) -> Self {
Self {
transport,
scripted: Mutex::new(
outcomes
.into_iter()
.map(|(op, outcome)| Some(Scripted { op, outcome }))
.collect(),
),
asked: Mutex::new(Vec::new()),
heard: Mutex::new(Vec::new()),
}
}
pub(super) fn transport(&self) -> Result<&BatchSsh, &TransportUnknown> {
self.transport.as_ref()
}
pub(super) fn answer(&self, op: &'static str) -> Result<Reply, RemoteFailure> {
self.asked
.lock()
.expect("the fake is not shared across threads")
.push(String::from(op));
let mut scripted = self
.scripted
.lock()
.expect("the fake is not shared across threads");
let found = scripted
.iter_mut()
.find(|entry| entry.as_ref().is_some_and(|entry| entry.op == op))
.and_then(Option::take);
drop(scripted);
match found {
Some(entry) => entry.outcome,
None => panic!("nothing scripted answers `git {op}`"),
}
}
pub(super) fn asked(&self) -> Vec<String> {
self.asked
.lock()
.expect("the fake is not shared across threads")
.clone()
}
pub(super) fn hear(&self, note: &str) -> bool {
self.heard
.lock()
.expect("the fake is not shared across threads")
.push(String::from(note));
true
}
pub(super) fn heard(&self) -> Vec<String> {
self.heard
.lock()
.expect("the fake is not shared across threads")
.clone()
}
}