astro_run/
astro_run.rs

1use crate::{
2  Action, ActionDriver, ExecutionContext, ExecutionContextBuilder, GithubAuthorization, JobId,
3  Plugin, PluginDriver, Result, Runner, SharedActionDriver, SharedPluginDriver, SignalManager,
4};
5use std::{collections::HashMap, sync::Arc};
6
7#[derive(Clone)]
8pub struct AstroRun {
9  runner: Arc<Box<dyn Runner>>,
10  github_auth: Option<GithubAuthorization>,
11  plugin_driver: SharedPluginDriver,
12  action_driver: SharedActionDriver,
13  signal_manager: SignalManager,
14}
15
16impl AstroRun {
17  pub fn builder() -> AstroRunBuilder {
18    AstroRunBuilder::new()
19  }
20
21  pub fn cancel_job(&self, job_id: &JobId) -> Result<()> {
22    self.signal_manager.cancel_job(job_id)
23  }
24
25  pub fn execution_context(&self) -> ExecutionContextBuilder {
26    let mut builder = ExecutionContext::builder()
27      .runner(self.runner.clone())
28      .signal_manager(self.signal_manager.clone())
29      .plugin_driver(self.plugin_driver());
30
31    if let Some(github_auth) = &self.github_auth {
32      builder = builder.github_auth(github_auth.clone());
33    }
34
35    builder
36  }
37
38  pub(crate) fn plugin_driver(&self) -> SharedPluginDriver {
39    Arc::clone(&self.plugin_driver)
40  }
41
42  pub(crate) fn action_driver(&self) -> SharedActionDriver {
43    Arc::clone(&self.action_driver)
44  }
45}
46
47#[derive(Default)]
48pub struct AstroRunBuilder {
49  runner: Option<Box<dyn Runner>>,
50  plugins: Vec<Box<dyn Plugin>>,
51  actions: HashMap<String, Box<dyn Action>>,
52  github_auth: Option<GithubAuthorization>,
53}
54
55impl AstroRunBuilder {
56  pub fn new() -> Self {
57    Self::default()
58  }
59
60  pub fn runner<T>(mut self, runner: T) -> Self
61  where
62    T: Runner + 'static,
63  {
64    self.runner = Some(Box::new(runner));
65    self
66  }
67
68  pub fn plugin<P: Plugin + 'static>(mut self, plugin: P) -> Self {
69    self.plugins.push(Box::new(plugin));
70
71    self
72  }
73
74  pub fn action(mut self, name: impl Into<String>, action: impl Action + 'static) -> Self {
75    self.actions.insert(name.into(), Box::new(action));
76
77    self
78  }
79
80  pub fn github_personal_token(mut self, token: impl Into<String>) -> Self {
81    self.github_auth = Some(GithubAuthorization::PersonalAccessToken(token.into()));
82    self
83  }
84
85  pub fn github_app(mut self, app_id: u64, private_key: impl Into<String>) -> Self {
86    self.github_auth = Some(GithubAuthorization::GithubApp {
87      app_id,
88      private_key: private_key.into(),
89    });
90
91    self
92  }
93
94  pub fn build(self) -> AstroRun {
95    let runner = self.runner.unwrap();
96
97    AstroRun {
98      runner: Arc::new(runner),
99      plugin_driver: Arc::new(PluginDriver::new(self.plugins)),
100      action_driver: Arc::new(ActionDriver::new(self.actions)),
101      signal_manager: SignalManager::new(),
102      github_auth: self.github_auth,
103    }
104  }
105}