1//! Baseline interface of Tasks in Zed: all tasks in Zed are intended to use those for implementing their own logic.
2
3mod adapter_schema;
4mod debug_format;
5mod serde_helpers;
6mod shell_builder;
7pub mod static_source;
8mod task_template;
9mod vscode_debug_format;
10mod vscode_format;
11
12use collections::{HashMap, HashSet, hash_map};
13use gpui::SharedString;
14use schemars::JsonSchema;
15use serde::{Deserialize, Serialize};
16use std::borrow::Cow;
17use std::path::PathBuf;
18use std::str::FromStr;
19
20pub use adapter_schema::{AdapterSchema, AdapterSchemas};
21pub use debug_format::{
22 AttachRequest, BuildTaskDefinition, DebugRequest, DebugScenario, DebugTaskFile, LaunchRequest,
23 Request, TcpArgumentsTemplate, ZedDebugConfig,
24};
25pub use shell_builder::{ShellBuilder, ShellKind};
26pub use task_template::{
27 DebugArgsRequest, HideStrategy, RevealStrategy, TaskTemplate, TaskTemplates,
28 substitute_variables_in_map, substitute_variables_in_str,
29};
30pub use vscode_debug_format::VsCodeDebugTaskFile;
31pub use vscode_format::VsCodeTaskFile;
32pub use zed_actions::RevealTarget;
33
34/// Task identifier, unique within the application.
35/// Based on it, task reruns and terminal tabs are managed.
36#[derive(Default, Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Deserialize)]
37pub struct TaskId(pub String);
38
39/// Contains all information needed by Zed to spawn a new terminal tab for the given task.
40#[derive(Default, Debug, Clone, PartialEq, Eq)]
41pub struct SpawnInTerminal {
42 /// Id of the task to use when determining task tab affinity.
43 pub id: TaskId,
44 /// Full unshortened form of `label` field.
45 pub full_label: String,
46 /// Human readable name of the terminal tab.
47 pub label: String,
48 /// Executable command to spawn.
49 pub command: Option<String>,
50 /// Arguments to the command, potentially unsubstituted,
51 /// to let the shell that spawns the command to do the substitution, if needed.
52 pub args: Vec<String>,
53 /// A human-readable label, containing command and all of its arguments, joined and substituted.
54 pub command_label: String,
55 /// Current working directory to spawn the command into.
56 pub cwd: Option<PathBuf>,
57 /// Env overrides for the command, will be appended to the terminal's environment from the settings.
58 pub env: HashMap<String, String>,
59 /// Whether to use a new terminal tab or reuse the existing one to spawn the process.
60 pub use_new_terminal: bool,
61 /// Whether to allow multiple instances of the same task to be run, or rather wait for the existing ones to finish.
62 pub allow_concurrent_runs: bool,
63 /// What to do with the terminal pane and tab, after the command was started.
64 pub reveal: RevealStrategy,
65 /// Where to show tasks' terminal output.
66 pub reveal_target: RevealTarget,
67 /// What to do with the terminal pane and tab, after the command had finished.
68 pub hide: HideStrategy,
69 /// Which shell to use when spawning the task.
70 pub shell: Shell,
71 /// Whether to show the task summary line in the task output (sucess/failure).
72 pub show_summary: bool,
73 /// Whether to show the command line in the task output.
74 pub show_command: bool,
75 /// Whether to show the rerun button in the terminal tab.
76 pub show_rerun: bool,
77}
78
79impl SpawnInTerminal {
80 pub fn to_proto(&self) -> proto::SpawnInTerminal {
81 proto::SpawnInTerminal {
82 label: self.label.clone(),
83 command: self.command.clone(),
84 args: self.args.clone(),
85 env: self
86 .env
87 .iter()
88 .map(|(k, v)| (k.clone(), v.clone()))
89 .collect(),
90 cwd: self
91 .cwd
92 .clone()
93 .map(|cwd| cwd.to_string_lossy().into_owned()),
94 }
95 }
96
97 pub fn from_proto(proto: proto::SpawnInTerminal) -> Self {
98 Self {
99 label: proto.label.clone(),
100 command: proto.command.clone(),
101 args: proto.args.clone(),
102 env: proto.env.into_iter().collect(),
103 cwd: proto.cwd.map(PathBuf::from),
104 ..Default::default()
105 }
106 }
107}
108
109/// A final form of the [`TaskTemplate`], that got resolved with a particular [`TaskContext`] and now is ready to spawn the actual task.
110#[derive(Clone, Debug, PartialEq, Eq)]
111pub struct ResolvedTask {
112 /// A way to distinguish tasks produced by the same template, but different contexts.
113 /// NOTE: Resolved tasks may have the same labels, commands and do the same things,
114 /// but still may have different ids if the context was different during the resolution.
115 /// Since the template has `env` field, for a generic task that may be a bash command,
116 /// so it's impossible to determine the id equality without more context in a generic case.
117 pub id: TaskId,
118 /// A template the task got resolved from.
119 original_task: TaskTemplate,
120 /// Full, unshortened label of the task after all resolutions are made.
121 pub resolved_label: String,
122 /// Variables that were substituted during the task template resolution.
123 substituted_variables: HashSet<VariableName>,
124 /// Further actions that need to take place after the resolved task is spawned,
125 /// with all task variables resolved.
126 pub resolved: SpawnInTerminal,
127}
128
129impl ResolvedTask {
130 /// A task template before the resolution.
131 pub fn original_task(&self) -> &TaskTemplate {
132 &self.original_task
133 }
134
135 /// Variables that were substituted during the task template resolution.
136 pub fn substituted_variables(&self) -> &HashSet<VariableName> {
137 &self.substituted_variables
138 }
139
140 /// A human-readable label to display in the UI.
141 pub fn display_label(&self) -> &str {
142 self.resolved.label.as_str()
143 }
144}
145
146/// Variables, available for use in [`TaskContext`] when a Zed's [`TaskTemplate`] gets resolved into a [`ResolvedTask`].
147/// Name of the variable must be a valid shell variable identifier, which generally means that it is
148/// a word consisting only of alphanumeric characters and underscores,
149/// and beginning with an alphabetic character or an underscore.
150#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
151pub enum VariableName {
152 /// An absolute path of the currently opened file.
153 File,
154 /// A path of the currently opened file (relative to worktree root).
155 RelativeFile,
156 /// A path of the currently opened file's directory (relative to worktree root).
157 RelativeDir,
158 /// The currently opened filename.
159 Filename,
160 /// The path to a parent directory of a currently opened file.
161 Dirname,
162 /// Stem (filename without extension) of the currently opened file.
163 Stem,
164 /// An absolute path of the currently opened worktree, that contains the file.
165 WorktreeRoot,
166 /// A symbol text, that contains latest cursor/selection position.
167 Symbol,
168 /// A row with the latest cursor/selection position.
169 Row,
170 /// A column with the latest cursor/selection position.
171 Column,
172 /// Text from the latest selection.
173 SelectedText,
174 /// The symbol selected by the symbol tagging system, specifically the @run capture in a runnables.scm
175 RunnableSymbol,
176 /// Custom variable, provided by the plugin or other external source.
177 /// Will be printed with `CUSTOM_` prefix to avoid potential conflicts with other variables.
178 Custom(Cow<'static, str>),
179}
180
181impl VariableName {
182 /// Generates a `$VARIABLE`-like string value to be used in templates.
183 pub fn template_value(&self) -> String {
184 format!("${self}")
185 }
186 /// Generates a `"$VARIABLE"`-like string, to be used instead of `Self::template_value` when expanded value could contain spaces or special characters.
187 pub fn template_value_with_whitespace(&self) -> String {
188 format!("\"${self}\"")
189 }
190}
191
192impl FromStr for VariableName {
193 type Err = ();
194
195 fn from_str(s: &str) -> Result<Self, Self::Err> {
196 let without_prefix = s.strip_prefix(ZED_VARIABLE_NAME_PREFIX).ok_or(())?;
197 let value = match without_prefix {
198 "FILE" => Self::File,
199 "FILENAME" => Self::Filename,
200 "RELATIVE_FILE" => Self::RelativeFile,
201 "RELATIVE_DIR" => Self::RelativeDir,
202 "DIRNAME" => Self::Dirname,
203 "STEM" => Self::Stem,
204 "WORKTREE_ROOT" => Self::WorktreeRoot,
205 "SYMBOL" => Self::Symbol,
206 "RUNNABLE_SYMBOL" => Self::RunnableSymbol,
207 "SELECTED_TEXT" => Self::SelectedText,
208 "ROW" => Self::Row,
209 "COLUMN" => Self::Column,
210 _ => {
211 if let Some(custom_name) =
212 without_prefix.strip_prefix(ZED_CUSTOM_VARIABLE_NAME_PREFIX)
213 {
214 Self::Custom(Cow::Owned(custom_name.to_owned()))
215 } else {
216 return Err(());
217 }
218 }
219 };
220 Ok(value)
221 }
222}
223
224/// A prefix that all [`VariableName`] variants are prefixed with when used in environment variables and similar template contexts.
225pub const ZED_VARIABLE_NAME_PREFIX: &str = "ZED_";
226const ZED_CUSTOM_VARIABLE_NAME_PREFIX: &str = "CUSTOM_";
227
228impl std::fmt::Display for VariableName {
229 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
230 match self {
231 Self::File => write!(f, "{ZED_VARIABLE_NAME_PREFIX}FILE"),
232 Self::Filename => write!(f, "{ZED_VARIABLE_NAME_PREFIX}FILENAME"),
233 Self::RelativeFile => write!(f, "{ZED_VARIABLE_NAME_PREFIX}RELATIVE_FILE"),
234 Self::RelativeDir => write!(f, "{ZED_VARIABLE_NAME_PREFIX}RELATIVE_DIR"),
235 Self::Dirname => write!(f, "{ZED_VARIABLE_NAME_PREFIX}DIRNAME"),
236 Self::Stem => write!(f, "{ZED_VARIABLE_NAME_PREFIX}STEM"),
237 Self::WorktreeRoot => write!(f, "{ZED_VARIABLE_NAME_PREFIX}WORKTREE_ROOT"),
238 Self::Symbol => write!(f, "{ZED_VARIABLE_NAME_PREFIX}SYMBOL"),
239 Self::Row => write!(f, "{ZED_VARIABLE_NAME_PREFIX}ROW"),
240 Self::Column => write!(f, "{ZED_VARIABLE_NAME_PREFIX}COLUMN"),
241 Self::SelectedText => write!(f, "{ZED_VARIABLE_NAME_PREFIX}SELECTED_TEXT"),
242 Self::RunnableSymbol => write!(f, "{ZED_VARIABLE_NAME_PREFIX}RUNNABLE_SYMBOL"),
243 Self::Custom(s) => write!(
244 f,
245 "{ZED_VARIABLE_NAME_PREFIX}{ZED_CUSTOM_VARIABLE_NAME_PREFIX}{s}"
246 ),
247 }
248 }
249}
250
251/// Container for predefined environment variables that describe state of Zed at the time the task was spawned.
252#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
253pub struct TaskVariables(HashMap<VariableName, String>);
254
255impl TaskVariables {
256 /// Inserts another variable into the container, overwriting the existing one if it already exists — in this case, the old value is returned.
257 pub fn insert(&mut self, variable: VariableName, value: String) -> Option<String> {
258 self.0.insert(variable, value)
259 }
260
261 /// Extends the container with another one, overwriting the existing variables on collision.
262 pub fn extend(&mut self, other: Self) {
263 self.0.extend(other.0);
264 }
265 /// Get the value associated with given variable name, if there is one.
266 pub fn get(&self, key: &VariableName) -> Option<&str> {
267 self.0.get(key).map(|s| s.as_str())
268 }
269 /// Clear out variables obtained from tree-sitter queries, which are prefixed with '_' character
270 pub fn sweep(&mut self) {
271 self.0.retain(|name, _| {
272 if let VariableName::Custom(name) = name {
273 !name.starts_with('_')
274 } else {
275 true
276 }
277 })
278 }
279
280 pub fn iter(&self) -> impl Iterator<Item = (&VariableName, &String)> {
281 self.0.iter()
282 }
283}
284
285impl FromIterator<(VariableName, String)> for TaskVariables {
286 fn from_iter<T: IntoIterator<Item = (VariableName, String)>>(iter: T) -> Self {
287 Self(HashMap::from_iter(iter))
288 }
289}
290
291impl IntoIterator for TaskVariables {
292 type Item = (VariableName, String);
293
294 type IntoIter = hash_map::IntoIter<VariableName, String>;
295
296 fn into_iter(self) -> Self::IntoIter {
297 self.0.into_iter()
298 }
299}
300
301/// Keeps track of the file associated with a task and context of tasks execution (i.e. current file or current function).
302/// Keeps all Zed-related state inside, used to produce a resolved task out of its template.
303#[derive(Clone, Debug, Default, PartialEq, Eq)]
304pub struct TaskContext {
305 /// A path to a directory in which the task should be executed.
306 pub cwd: Option<PathBuf>,
307 /// Additional environment variables associated with a given task.
308 pub task_variables: TaskVariables,
309 /// Environment variables obtained when loading the project into Zed.
310 /// This is the environment one would get when `cd`ing in a terminal
311 /// into the project's root directory.
312 pub project_env: HashMap<String, String>,
313}
314
315/// This is a new type representing a 'tag' on a 'runnable symbol', typically a test of main() function, found via treesitter.
316#[derive(Clone, Debug)]
317pub struct RunnableTag(pub SharedString);
318
319/// Shell configuration to open the terminal with.
320#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
321#[serde(rename_all = "snake_case")]
322pub enum Shell {
323 /// Use the system's default terminal configuration in /etc/passwd
324 #[default]
325 System,
326 /// Use a specific program with no arguments.
327 Program(String),
328 /// Use a specific program with arguments.
329 WithArguments {
330 /// The program to run.
331 program: String,
332 /// The arguments to pass to the program.
333 args: Vec<String>,
334 /// An optional string to override the title of the terminal tab
335 title_override: Option<SharedString>,
336 },
337}
338
339type VsCodeEnvVariable = String;
340type ZedEnvVariable = String;
341
342struct EnvVariableReplacer {
343 variables: HashMap<VsCodeEnvVariable, ZedEnvVariable>,
344}
345
346impl EnvVariableReplacer {
347 fn new(variables: HashMap<VsCodeEnvVariable, ZedEnvVariable>) -> Self {
348 Self { variables }
349 }
350
351 fn replace_value(&self, input: serde_json::Value) -> serde_json::Value {
352 match input {
353 serde_json::Value::String(s) => serde_json::Value::String(self.replace(&s)),
354 serde_json::Value::Array(arr) => {
355 serde_json::Value::Array(arr.into_iter().map(|v| self.replace_value(v)).collect())
356 }
357 serde_json::Value::Object(obj) => serde_json::Value::Object(
358 obj.into_iter()
359 .map(|(k, v)| (self.replace(&k), self.replace_value(v)))
360 .collect(),
361 ),
362 _ => input,
363 }
364 }
365 // Replaces occurrences of VsCode-specific environment variables with Zed equivalents.
366 fn replace(&self, input: &str) -> String {
367 shellexpand::env_with_context_no_errors(&input, |var: &str| {
368 // Colons denote a default value in case the variable is not set. We want to preserve that default, as otherwise shellexpand will substitute it for us.
369 let colon_position = var.find(':').unwrap_or(var.len());
370 let (left, right) = var.split_at(colon_position);
371 if left == "env" && !right.is_empty() {
372 let variable_name = &right[1..];
373 return Some(format!("${{{variable_name}}}"));
374 }
375 let (variable_name, default) = (left, right);
376 let append_previous_default = |ret: &mut String| {
377 if !default.is_empty() {
378 ret.push_str(default);
379 }
380 };
381 if let Some(substitution) = self.variables.get(variable_name) {
382 // Got a VSCode->Zed hit, perform a substitution
383 let mut name = format!("${{{substitution}");
384 append_previous_default(&mut name);
385 name.push('}');
386 return Some(name);
387 }
388 // This is an unknown variable.
389 // We should not error out, as they may come from user environment (e.g. $PATH). That means that the variable substitution might not be perfect.
390 // If there's a default, we need to return the string verbatim as otherwise shellexpand will apply that default for us.
391 if !default.is_empty() {
392 return Some(format!("${{{var}}}"));
393 }
394 // Else we can just return None and that variable will be left as is.
395 None
396 })
397 .into_owned()
398 }
399}