detect_targets/
desired_targets.rs

1use crate::detect_targets;
2
3use std::sync::Arc;
4
5use tokio::sync::OnceCell;
6
7#[derive(Debug)]
8enum DesiredTargetsInner {
9    AutoDetect(Arc<OnceCell<Vec<String>>>),
10    Initialized(Vec<String>),
11}
12
13#[derive(Debug)]
14pub struct DesiredTargets(DesiredTargetsInner);
15
16impl DesiredTargets {
17    fn initialized(targets: Vec<String>) -> Self {
18        Self(DesiredTargetsInner::Initialized(targets))
19    }
20
21    fn auto_detect() -> Self {
22        let arc = Arc::new(OnceCell::new());
23
24        let once_cell = arc.clone();
25        tokio::spawn(async move {
26            once_cell.get_or_init(detect_targets).await;
27        });
28
29        Self(DesiredTargetsInner::AutoDetect(arc))
30    }
31
32    pub async fn get(&self) -> &[String] {
33        use DesiredTargetsInner::*;
34
35        match &self.0 {
36            Initialized(targets) => targets,
37
38            // This will mostly just wait for the spawned task,
39            // on rare occausion though, it will poll the future
40            // returned by `detect_targets`.
41            AutoDetect(once_cell) => once_cell.get_or_init(detect_targets).await,
42        }
43    }
44
45    /// If `DesiredTargets` is provided with a list of desired targets instead
46    /// of detecting the targets, then this function would return `Some`.
47    pub fn get_initialized(&self) -> Option<&[String]> {
48        use DesiredTargetsInner::*;
49
50        match &self.0 {
51            Initialized(targets) => Some(targets),
52            AutoDetect(..) => None,
53        }
54    }
55}
56
57/// If opts_targets is `Some`, then it will be used.
58/// Otherwise, call `detect_targets` using `tokio::spawn` to detect targets.
59///
60/// Since `detect_targets` internally spawns a process and wait for it,
61/// it's pretty costy, it is recommended to run this fn ASAP and
62/// reuse the result.
63pub fn get_desired_targets(opts_targets: Option<Vec<String>>) -> DesiredTargets {
64    if let Some(targets) = opts_targets {
65        DesiredTargets::initialized(targets)
66    } else {
67        DesiredTargets::auto_detect()
68    }
69}