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(Vec<Definition>);
52
53impl DefinitionProvider {
54 /// Generates JSON schema of Tasks JSON definition format.
55 pub fn generate_json_schema() -> serde_json_lenient::Value {
56 let schema = SchemaSettings::draft07()
57 .with(|settings| settings.option_add_null_type = false)
58 .into_generator()
59 .into_root_schema_for::<Self>();
60
61 serde_json_lenient::to_value(schema).unwrap()
62 }
63}
64/// A Wrapper around deserializable T that keeps track of it's contents
65/// via a provided channel. Once T value changes, the observers of [`TrackedFile`] are
66/// notified.
67struct TrackedFile<T> {
68 parsed_contents: T,
69}
70
71impl<T: for<'a> Deserialize<'a> + PartialEq + 'static> TrackedFile<T> {
72 fn new(
73 parsed_contents: T,
74 mut tracker: UnboundedReceiver<String>,
75 cx: &mut AppContext,
76 ) -> Model<Self> {
77 cx.new_model(move |cx| {
78 cx.spawn(|tracked_file, mut cx| async move {
79 while let Some(new_contents) = tracker.next().await {
80 if !new_contents.trim().is_empty() {
81 let Some(new_contents) =
82 serde_json_lenient::from_str(&new_contents).log_err()
83 else {
84 continue;
85 };
86 tracked_file.update(&mut cx, |tracked_file: &mut TrackedFile<T>, cx| {
87 if tracked_file.parsed_contents != new_contents {
88 tracked_file.parsed_contents = new_contents;
89 cx.notify();
90 };
91 })?;
92 }
93 }
94 anyhow::Ok(())
95 })
96 .detach_and_log_err(cx);
97 Self { parsed_contents }
98 })
99 }
100
101 fn get(&self) -> &T {
102 &self.parsed_contents
103 }
104}
105
106impl StaticSource {
107 /// Initializes the static source, reacting on tasks config changes.
108 pub fn new(
109 tasks_file_tracker: UnboundedReceiver<String>,
110 cx: &mut AppContext,
111 ) -> Model<Box<dyn Source>> {
112 let definitions = TrackedFile::new(DefinitionProvider::default(), tasks_file_tracker, cx);
113 cx.new_model(|cx| {
114 let _subscription = cx.observe(
115 &definitions,
116 |source: &mut Box<(dyn Source + 'static)>, new_definitions, cx| {
117 if let Some(static_source) = source.as_any().downcast_mut::<Self>() {
118 static_source.tasks = new_definitions
119 .read(cx)
120 .get()
121 .0
122 .clone()
123 .into_iter()
124 .enumerate()
125 .map(|(id, definition)| StaticTask::new(id, definition))
126 .collect();
127 cx.notify();
128 }
129 },
130 );
131 Box::new(Self {
132 tasks: Vec::new(),
133 _definitions: definitions,
134 _subscription,
135 })
136 })
137 }
138}
139
140impl Source for StaticSource {
141 fn tasks_for_path(
142 &mut self,
143 _: Option<&Path>,
144 _: &mut ModelContext<Box<dyn Source>>,
145 ) -> Vec<Arc<dyn Task>> {
146 self.tasks
147 .clone()
148 .into_iter()
149 .map(|task| Arc::new(task) as Arc<dyn Task>)
150 .collect()
151 }
152
153 fn as_any(&mut self) -> &mut dyn std::any::Any {
154 self
155 }
156}