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;
6pub mod static_source;
7mod task_template;
8mod vscode_debug_format;
9mod vscode_format;
10
11use anyhow::Context as _;
12use collections::{HashMap, HashSet, hash_map};
13use gpui::SharedString;
14use serde::{Deserialize, Serialize};
15use std::borrow::Cow;
16use std::path::PathBuf;
17use std::str::FromStr;
18
19pub use adapter_schema::{AdapterSchema, AdapterSchemas};
20pub use debug_format::{
21 AttachRequest, BuildTaskDefinition, DebugRequest, DebugScenario, DebugTaskFile, LaunchRequest,
22 Request, TcpArgumentsTemplate, ZedDebugConfig,
23};
24pub use task_template::{
25 DebugArgsRequest, HideStrategy, RevealStrategy, TaskTemplate, TaskTemplates,
26 substitute_variables_in_map, substitute_variables_in_str,
27};
28pub use util::shell::{Shell, ShellKind};
29pub use util::shell_builder::ShellBuilder;
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
319pub fn shell_from_proto(proto: proto::Shell) -> anyhow::Result<Shell> {
320 let shell_type = proto.shell_type.context("invalid shell type")?;
321 let shell = match shell_type {
322 proto::shell::ShellType::System(_) => Shell::System,
323 proto::shell::ShellType::Program(program) => Shell::Program(program),
324 proto::shell::ShellType::WithArguments(program) => Shell::WithArguments {
325 program: program.program,
326 args: program.args,
327 title_override: None,
328 },
329 };
330 Ok(shell)
331}
332
333pub fn shell_to_proto(shell: Shell) -> proto::Shell {
334 let shell_type = match shell {
335 Shell::System => proto::shell::ShellType::System(proto::System {}),
336 Shell::Program(program) => proto::shell::ShellType::Program(program),
337 Shell::WithArguments {
338 program,
339 args,
340 title_override: _,
341 } => proto::shell::ShellType::WithArguments(proto::shell::WithArguments { program, args }),
342 };
343 proto::Shell {
344 shell_type: Some(shell_type),
345 }
346}
347
348type VsCodeEnvVariable = String;
349type ZedEnvVariable = String;
350
351struct EnvVariableReplacer {
352 variables: HashMap<VsCodeEnvVariable, ZedEnvVariable>,
353}
354
355impl EnvVariableReplacer {
356 fn new(variables: HashMap<VsCodeEnvVariable, ZedEnvVariable>) -> Self {
357 Self { variables }
358 }
359
360 fn replace_value(&self, input: serde_json::Value) -> serde_json::Value {
361 match input {
362 serde_json::Value::String(s) => serde_json::Value::String(self.replace(&s)),
363 serde_json::Value::Array(arr) => {
364 serde_json::Value::Array(arr.into_iter().map(|v| self.replace_value(v)).collect())
365 }
366 serde_json::Value::Object(obj) => serde_json::Value::Object(
367 obj.into_iter()
368 .map(|(k, v)| (self.replace(&k), self.replace_value(v)))
369 .collect(),
370 ),
371 _ => input,
372 }
373 }
374 // Replaces occurrences of VsCode-specific environment variables with Zed equivalents.
375 fn replace(&self, input: &str) -> String {
376 shellexpand::env_with_context_no_errors(&input, |var: &str| {
377 // 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.
378 let colon_position = var.find(':').unwrap_or(var.len());
379 let (left, right) = var.split_at(colon_position);
380 if left == "env" && !right.is_empty() {
381 let variable_name = &right[1..];
382 return Some(format!("${{{variable_name}}}"));
383 }
384 let (variable_name, default) = (left, right);
385 let append_previous_default = |ret: &mut String| {
386 if !default.is_empty() {
387 ret.push_str(default);
388 }
389 };
390 if let Some(substitution) = self.variables.get(variable_name) {
391 // Got a VSCode->Zed hit, perform a substitution
392 let mut name = format!("${{{substitution}");
393 append_previous_default(&mut name);
394 name.push('}');
395 return Some(name);
396 }
397 // This is an unknown variable.
398 // 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.
399 // If there's a default, we need to return the string verbatim as otherwise shellexpand will apply that default for us.
400 if !default.is_empty() {
401 return Some(format!("${{{var}}}"));
402 }
403 // Else we can just return None and that variable will be left as is.
404 None
405 })
406 .into_owned()
407 }
408}