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, SpawnInTerminal, Task, TaskId};
 16use futures::channel::mpsc::UnboundedReceiver;
 17
 18/// A single config file entry with the deserialized task definition.
 19#[derive(Clone, Debug, PartialEq)]
 20struct StaticTask {
 21    id: TaskId,
 22    definition: Definition,
 23}
 24
 25impl StaticTask {
 26    pub(super) fn new(id: usize, task_definition: Definition) -> Self {
 27        Self {
 28            id: TaskId(format!("static_{}_{}", task_definition.label, id)),
 29            definition: task_definition,
 30        }
 31    }
 32}
 33
 34impl Task for StaticTask {
 35    fn exec(&self, cwd: Option<PathBuf>) -> Option<SpawnInTerminal> {
 36        Some(SpawnInTerminal {
 37            id: self.id.clone(),
 38            cwd,
 39            use_new_terminal: self.definition.use_new_terminal,
 40            allow_concurrent_runs: self.definition.allow_concurrent_runs,
 41            label: self.definition.label.clone(),
 42            command: self.definition.command.clone(),
 43            args: self.definition.args.clone(),
 44            env: self.definition.env.clone(),
 45            separate_shell: false,
 46        })
 47    }
 48
 49    fn name(&self) -> &str {
 50        &self.definition.label
 51    }
 52
 53    fn id(&self) -> &TaskId {
 54        &self.id
 55    }
 56
 57    fn cwd(&self) -> Option<&Path> {
 58        self.definition.cwd.as_deref()
 59    }
 60}
 61
 62/// The source of tasks defined in a tasks config file.
 63pub struct StaticSource {
 64    tasks: Vec<StaticTask>,
 65    _definitions: Model<TrackedFile<DefinitionProvider>>,
 66    _subscription: Subscription,
 67}
 68
 69/// Static task definition from the tasks config file.
 70#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
 71pub(crate) struct Definition {
 72    /// Human readable name of the task to display in the UI.
 73    pub label: String,
 74    /// Executable command to spawn.
 75    pub command: String,
 76    /// Arguments to the command.
 77    #[serde(default)]
 78    pub args: Vec<String>,
 79    /// Env overrides for the command, will be appended to the terminal's environment from the settings.
 80    #[serde(default)]
 81    pub env: HashMap<String, String>,
 82    /// Current working directory to spawn the command into, defaults to current project root.
 83    #[serde(default)]
 84    pub cwd: Option<PathBuf>,
 85    /// Whether to use a new terminal tab or reuse the existing one to spawn the process.
 86    #[serde(default)]
 87    pub use_new_terminal: bool,
 88    /// Whether to allow multiple instances of the same task to be run, or rather wait for the existing ones to finish.
 89    #[serde(default)]
 90    pub allow_concurrent_runs: bool,
 91}
 92
 93/// A group of Tasks defined in a JSON file.
 94#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
 95pub struct DefinitionProvider(Vec<Definition>);
 96
 97impl DefinitionProvider {
 98    /// Generates JSON schema of Tasks JSON definition format.
 99    pub fn generate_json_schema() -> serde_json_lenient::Value {
100        let schema = SchemaSettings::draft07()
101            .with(|settings| settings.option_add_null_type = false)
102            .into_generator()
103            .into_root_schema_for::<Self>();
104
105        serde_json_lenient::to_value(schema).unwrap()
106    }
107}
108/// A Wrapper around deserializable T that keeps track of it's contents
109/// via a provided channel. Once T value changes, the observers of [`TrackedFile`] are
110/// notified.
111struct TrackedFile<T> {
112    parsed_contents: T,
113}
114
115impl<T: for<'a> Deserialize<'a> + PartialEq + 'static> TrackedFile<T> {
116    fn new(
117        parsed_contents: T,
118        mut tracker: UnboundedReceiver<String>,
119        cx: &mut AppContext,
120    ) -> Model<Self> {
121        cx.new_model(move |cx| {
122            cx.spawn(|tracked_file, mut cx| async move {
123                while let Some(new_contents) = tracker.next().await {
124                    if !new_contents.trim().is_empty() {
125                        let Some(new_contents) =
126                            serde_json_lenient::from_str(&new_contents).log_err()
127                        else {
128                            continue;
129                        };
130                        tracked_file.update(&mut cx, |tracked_file: &mut TrackedFile<T>, cx| {
131                            if tracked_file.parsed_contents != new_contents {
132                                tracked_file.parsed_contents = new_contents;
133                                cx.notify();
134                            };
135                        })?;
136                    }
137                }
138                anyhow::Ok(())
139            })
140            .detach_and_log_err(cx);
141            Self { parsed_contents }
142        })
143    }
144
145    fn get(&self) -> &T {
146        &self.parsed_contents
147    }
148}
149
150impl StaticSource {
151    /// Initializes the static source, reacting on tasks config changes.
152    pub fn new(
153        tasks_file_tracker: UnboundedReceiver<String>,
154        cx: &mut AppContext,
155    ) -> Model<Box<dyn Source>> {
156        let definitions = TrackedFile::new(DefinitionProvider::default(), tasks_file_tracker, cx);
157        cx.new_model(|cx| {
158            let _subscription = cx.observe(
159                &definitions,
160                |source: &mut Box<(dyn Source + 'static)>, new_definitions, cx| {
161                    if let Some(static_source) = source.as_any().downcast_mut::<Self>() {
162                        static_source.tasks = new_definitions
163                            .read(cx)
164                            .get()
165                            .0
166                            .clone()
167                            .into_iter()
168                            .enumerate()
169                            .map(|(id, definition)| StaticTask::new(id, definition))
170                            .collect();
171                        cx.notify();
172                    }
173                },
174            );
175            Box::new(Self {
176                tasks: Vec::new(),
177                _definitions: definitions,
178                _subscription,
179            })
180        })
181    }
182}
183
184impl Source for StaticSource {
185    fn tasks_for_path(
186        &mut self,
187        _: Option<&Path>,
188        _: &mut ModelContext<Box<dyn Source>>,
189    ) -> Vec<Arc<dyn Task>> {
190        self.tasks
191            .clone()
192            .into_iter()
193            .map(|task| Arc::new(task) as Arc<dyn Task>)
194            .collect()
195    }
196
197    fn as_any(&mut self) -> &mut dyn std::any::Any {
198        self
199    }
200}