static_source.rs

  1//! A source of runnables, based on a static configuration, deserialized from the runnables config file, and related infrastructure for tracking changes to the file.
  2
  3use std::{
  4    path::{Path, PathBuf},
  5    sync::Arc,
  6};
  7
  8use collections::HashMap;
  9use futures::StreamExt;
 10use gpui::{AppContext, Context, Model, ModelContext, Subscription};
 11use schemars::{gen::SchemaSettings, JsonSchema};
 12use serde::{Deserialize, Serialize};
 13use util::ResultExt;
 14
 15use crate::{Runnable, Source, StaticRunnable};
 16use futures::channel::mpsc::UnboundedReceiver;
 17
 18/// The source of runnables defined in a runnables config file.
 19pub struct StaticSource {
 20    runnables: Vec<StaticRunnable>,
 21    _definitions: Model<TrackedFile<DefinitionProvider>>,
 22    _subscription: Subscription,
 23}
 24
 25/// Static runnable definition from the runnables config file.
 26#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
 27pub(crate) struct Definition {
 28    /// Human readable name of the runnable to display in the UI.
 29    pub label: String,
 30    /// Executable command to spawn.
 31    pub command: String,
 32    /// Arguments to the command.
 33    #[serde(default)]
 34    pub args: Vec<String>,
 35    /// Env overrides for the command, will be appended to the terminal's environment from the settings.
 36    #[serde(default)]
 37    pub env: HashMap<String, String>,
 38    /// Current working directory to spawn the command into, defaults to current project root.
 39    #[serde(default)]
 40    pub cwd: Option<PathBuf>,
 41    /// Whether to use a new terminal tab or reuse the existing one to spawn the process.
 42    #[serde(default)]
 43    pub use_new_terminal: bool,
 44    /// Whether to allow multiple instances of the same runnable to be run, or rather wait for the existing ones to finish.
 45    #[serde(default)]
 46    pub allow_concurrent_runs: bool,
 47}
 48
 49/// A group of Runnables defined in a JSON file.
 50#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
 51pub struct DefinitionProvider {
 52    version: String,
 53    runnables: Vec<Definition>,
 54}
 55
 56impl DefinitionProvider {
 57    /// Generates JSON schema of Runnables JSON definition format.
 58    pub fn generate_json_schema() -> serde_json_lenient::Value {
 59        let schema = SchemaSettings::draft07()
 60            .with(|settings| settings.option_add_null_type = false)
 61            .into_generator()
 62            .into_root_schema_for::<Self>();
 63
 64        serde_json_lenient::to_value(schema).unwrap()
 65    }
 66}
 67/// A Wrapper around deserializable T that keeps track of it's contents
 68/// via a provided channel. Once T value changes, the observers of [`TrackedFile`] are
 69/// notified.
 70struct TrackedFile<T> {
 71    parsed_contents: T,
 72}
 73
 74impl<T: for<'a> Deserialize<'a> + PartialEq + 'static> TrackedFile<T> {
 75    fn new(
 76        parsed_contents: T,
 77        mut tracker: UnboundedReceiver<String>,
 78        cx: &mut AppContext,
 79    ) -> Model<Self> {
 80        cx.new_model(move |cx| {
 81            cx.spawn(|tracked_file, mut cx| async move {
 82                while let Some(new_contents) = tracker.next().await {
 83                    if !new_contents.trim().is_empty() {
 84                        let Some(new_contents) =
 85                            serde_json_lenient::from_str(&new_contents).log_err()
 86                        else {
 87                            continue;
 88                        };
 89                        tracked_file.update(&mut cx, |tracked_file: &mut TrackedFile<T>, cx| {
 90                            if tracked_file.parsed_contents != new_contents {
 91                                tracked_file.parsed_contents = new_contents;
 92                                cx.notify();
 93                            };
 94                        })?;
 95                    }
 96                }
 97                anyhow::Ok(())
 98            })
 99            .detach_and_log_err(cx);
100            Self { parsed_contents }
101        })
102    }
103
104    fn get(&self) -> &T {
105        &self.parsed_contents
106    }
107}
108
109impl StaticSource {
110    /// Initializes the static source, reacting on runnables config changes.
111    pub fn new(
112        runnables_file_tracker: UnboundedReceiver<String>,
113        cx: &mut AppContext,
114    ) -> Model<Box<dyn Source>> {
115        let definitions =
116            TrackedFile::new(DefinitionProvider::default(), runnables_file_tracker, cx);
117        cx.new_model(|cx| {
118            let _subscription = cx.observe(
119                &definitions,
120                |source: &mut Box<(dyn Source + 'static)>, new_definitions, cx| {
121                    if let Some(static_source) = source.as_any().downcast_mut::<Self>() {
122                        static_source.runnables = new_definitions
123                            .read(cx)
124                            .get()
125                            .runnables
126                            .clone()
127                            .into_iter()
128                            .enumerate()
129                            .map(|(id, definition)| StaticRunnable::new(id, definition))
130                            .collect();
131                        cx.notify();
132                    }
133                },
134            );
135            Box::new(Self {
136                runnables: Vec::new(),
137                _definitions: definitions,
138                _subscription,
139            })
140        })
141    }
142}
143
144impl Source for StaticSource {
145    fn runnables_for_path(
146        &mut self,
147        _: Option<&Path>,
148        _: &mut ModelContext<Box<dyn Source>>,
149    ) -> Vec<Arc<dyn Runnable>> {
150        self.runnables
151            .clone()
152            .into_iter()
153            .map(|runnable| Arc::new(runnable) as Arc<dyn Runnable>)
154            .collect()
155    }
156
157    fn as_any(&mut self) -> &mut dyn std::any::Any {
158        self
159    }
160}