static_source.rs

  1//! A source of tasks, based on a static configuration, deserialized from the tasks 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::{Source, StaticTask, Task};
 16use futures::channel::mpsc::UnboundedReceiver;
 17
 18/// The source of tasks defined in a tasks config file.
 19pub struct StaticSource {
 20    tasks: Vec<StaticTask>,
 21    _definitions: Model<TrackedFile<DefinitionProvider>>,
 22    _subscription: Subscription,
 23}
 24
 25/// Static task definition from the tasks config file.
 26#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
 27pub(crate) struct Definition {
 28    /// Human readable name of the task 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 task 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 Tasks defined in a JSON file.
 50#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
 51pub struct DefinitionProvider {
 52    version: String,
 53    tasks: Vec<Definition>,
 54}
 55
 56impl DefinitionProvider {
 57    /// Generates JSON schema of Tasks 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 tasks config changes.
111    pub fn new(
112        tasks_file_tracker: UnboundedReceiver<String>,
113        cx: &mut AppContext,
114    ) -> Model<Box<dyn Source>> {
115        let definitions = TrackedFile::new(DefinitionProvider::default(), tasks_file_tracker, cx);
116        cx.new_model(|cx| {
117            let _subscription = cx.observe(
118                &definitions,
119                |source: &mut Box<(dyn Source + 'static)>, new_definitions, cx| {
120                    if let Some(static_source) = source.as_any().downcast_mut::<Self>() {
121                        static_source.tasks = new_definitions
122                            .read(cx)
123                            .get()
124                            .tasks
125                            .clone()
126                            .into_iter()
127                            .enumerate()
128                            .map(|(id, definition)| StaticTask::new(id, definition))
129                            .collect();
130                        cx.notify();
131                    }
132                },
133            );
134            Box::new(Self {
135                tasks: Vec::new(),
136                _definitions: definitions,
137                _subscription,
138            })
139        })
140    }
141}
142
143impl Source for StaticSource {
144    fn tasks_for_path(
145        &mut self,
146        _: Option<&Path>,
147        _: &mut ModelContext<Box<dyn Source>>,
148    ) -> Vec<Arc<dyn Task>> {
149        self.tasks
150            .clone()
151            .into_iter()
152            .map(|task| Arc::new(task) as Arc<dyn Task>)
153            .collect()
154    }
155
156    fn as_any(&mut self) -> &mut dyn std::any::Any {
157        self
158    }
159}