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.filter(|s| !s.is_empty()) {
83 let Some(new_contents) = serde_json_lenient::from_str(&new_contents).log_err()
84 else {
85 continue;
86 };
87 tracked_file.update(&mut cx, |tracked_file: &mut TrackedFile<T>, cx| {
88 if tracked_file.parsed_contents != new_contents {
89 tracked_file.parsed_contents = new_contents;
90 cx.notify();
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 runnables config changes.
108 pub fn new(
109 runnables_file_tracker: UnboundedReceiver<String>,
110 cx: &mut AppContext,
111 ) -> Model<Box<dyn Source>> {
112 let definitions =
113 TrackedFile::new(DefinitionProvider::default(), runnables_file_tracker, cx);
114 cx.new_model(|cx| {
115 let _subscription = cx.observe(
116 &definitions,
117 |source: &mut Box<(dyn Source + 'static)>, new_definitions, cx| {
118 if let Some(static_source) = source.as_any().downcast_mut::<Self>() {
119 static_source.runnables = new_definitions
120 .read(cx)
121 .get()
122 .runnables
123 .clone()
124 .into_iter()
125 .enumerate()
126 .map(|(id, definition)| StaticRunnable::new(id, definition))
127 .collect();
128 cx.notify();
129 }
130 },
131 );
132 Box::new(Self {
133 runnables: Vec::new(),
134 _definitions: definitions,
135 _subscription,
136 })
137 })
138 }
139}
140
141impl Source for StaticSource {
142 fn runnables_for_path(
143 &mut self,
144 _: Option<&Path>,
145 _: &mut ModelContext<Box<dyn Source>>,
146 ) -> Vec<Arc<dyn Runnable>> {
147 self.runnables
148 .clone()
149 .into_iter()
150 .map(|runnable| Arc::new(runnable) as Arc<dyn Runnable>)
151 .collect()
152 }
153
154 fn as_any(&mut self) -> &mut dyn std::any::Any {
155 self
156 }
157}