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 /// Open a Picker to select a process ID to use in place
177 /// Can only be used to debug configurations
178 PickProcessId,
179 /// Custom variable, provided by the plugin or other external source.
180 /// Will be printed with `CUSTOM_` prefix to avoid potential conflicts with other variables.
181 Custom(Cow<'static, str>),
182}
183
184impl VariableName {
185 /// Generates a `$VARIABLE`-like string value to be used in templates.
186 pub fn template_value(&self) -> String {
187 format!("${self}")
188 }
189 /// Generates a `"$VARIABLE"`-like string, to be used instead of `Self::template_value` when expanded value could contain spaces or special characters.
190 pub fn template_value_with_whitespace(&self) -> String {
191 format!("\"${self}\"")
192 }
193}
194
195impl FromStr for VariableName {
196 type Err = ();
197
198 fn from_str(s: &str) -> Result<Self, Self::Err> {
199 let without_prefix = s.strip_prefix(ZED_VARIABLE_NAME_PREFIX).ok_or(())?;
200 let value = match without_prefix {
201 "FILE" => Self::File,
202 "FILENAME" => Self::Filename,
203 "RELATIVE_FILE" => Self::RelativeFile,
204 "RELATIVE_DIR" => Self::RelativeDir,
205 "DIRNAME" => Self::Dirname,
206 "STEM" => Self::Stem,
207 "WORKTREE_ROOT" => Self::WorktreeRoot,
208 "SYMBOL" => Self::Symbol,
209 "RUNNABLE_SYMBOL" => Self::RunnableSymbol,
210 "SELECTED_TEXT" => Self::SelectedText,
211 "ROW" => Self::Row,
212 "COLUMN" => Self::Column,
213 _ => {
214 if let Some(custom_name) =
215 without_prefix.strip_prefix(ZED_CUSTOM_VARIABLE_NAME_PREFIX)
216 {
217 Self::Custom(Cow::Owned(custom_name.to_owned()))
218 } else {
219 return Err(());
220 }
221 }
222 };
223 Ok(value)
224 }
225}
226
227/// A prefix that all [`VariableName`] variants are prefixed with when used in environment variables and similar template contexts.
228pub const ZED_VARIABLE_NAME_PREFIX: &str = "ZED_";
229const ZED_CUSTOM_VARIABLE_NAME_PREFIX: &str = "CUSTOM_";
230
231impl std::fmt::Display for VariableName {
232 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
233 match self {
234 Self::File => write!(f, "{ZED_VARIABLE_NAME_PREFIX}FILE"),
235 Self::Filename => write!(f, "{ZED_VARIABLE_NAME_PREFIX}FILENAME"),
236 Self::RelativeFile => write!(f, "{ZED_VARIABLE_NAME_PREFIX}RELATIVE_FILE"),
237 Self::RelativeDir => write!(f, "{ZED_VARIABLE_NAME_PREFIX}RELATIVE_DIR"),
238 Self::Dirname => write!(f, "{ZED_VARIABLE_NAME_PREFIX}DIRNAME"),
239 Self::Stem => write!(f, "{ZED_VARIABLE_NAME_PREFIX}STEM"),
240 Self::WorktreeRoot => write!(f, "{ZED_VARIABLE_NAME_PREFIX}WORKTREE_ROOT"),
241 Self::Symbol => write!(f, "{ZED_VARIABLE_NAME_PREFIX}SYMBOL"),
242 Self::Row => write!(f, "{ZED_VARIABLE_NAME_PREFIX}ROW"),
243 Self::Column => write!(f, "{ZED_VARIABLE_NAME_PREFIX}COLUMN"),
244 Self::SelectedText => write!(f, "{ZED_VARIABLE_NAME_PREFIX}SELECTED_TEXT"),
245 Self::RunnableSymbol => write!(f, "{ZED_VARIABLE_NAME_PREFIX}RUNNABLE_SYMBOL"),
246 Self::PickProcessId => write!(f, "{ZED_VARIABLE_NAME_PREFIX}PICK_PID"),
247 Self::Custom(s) => write!(
248 f,
249 "{ZED_VARIABLE_NAME_PREFIX}{ZED_CUSTOM_VARIABLE_NAME_PREFIX}{s}"
250 ),
251 }
252 }
253}
254
255/// Container for predefined environment variables that describe state of Zed at the time the task was spawned.
256#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
257pub struct TaskVariables(HashMap<VariableName, String>);
258
259impl TaskVariables {
260 /// Inserts another variable into the container, overwriting the existing one if it already exists — in this case, the old value is returned.
261 pub fn insert(&mut self, variable: VariableName, value: String) -> Option<String> {
262 self.0.insert(variable, value)
263 }
264
265 /// Extends the container with another one, overwriting the existing variables on collision.
266 pub fn extend(&mut self, other: Self) {
267 self.0.extend(other.0);
268 }
269 /// Get the value associated with given variable name, if there is one.
270 pub fn get(&self, key: &VariableName) -> Option<&str> {
271 self.0.get(key).map(|s| s.as_str())
272 }
273 /// Clear out variables obtained from tree-sitter queries, which are prefixed with '_' character
274 pub fn sweep(&mut self) {
275 self.0.retain(|name, _| {
276 if let VariableName::Custom(name) = name {
277 !name.starts_with('_')
278 } else {
279 true
280 }
281 })
282 }
283
284 pub fn iter(&self) -> impl Iterator<Item = (&VariableName, &String)> {
285 self.0.iter()
286 }
287}
288
289impl FromIterator<(VariableName, String)> for TaskVariables {
290 fn from_iter<T: IntoIterator<Item = (VariableName, String)>>(iter: T) -> Self {
291 Self(HashMap::from_iter(iter))
292 }
293}
294
295impl IntoIterator for TaskVariables {
296 type Item = (VariableName, String);
297
298 type IntoIter = hash_map::IntoIter<VariableName, String>;
299
300 fn into_iter(self) -> Self::IntoIter {
301 self.0.into_iter()
302 }
303}
304
305/// Keeps track of the file associated with a task and context of tasks execution (i.e. current file or current function).
306/// Keeps all Zed-related state inside, used to produce a resolved task out of its template.
307#[derive(Clone, Debug, Default, PartialEq, Eq)]
308pub struct TaskContext {
309 /// A path to a directory in which the task should be executed.
310 pub cwd: Option<PathBuf>,
311 /// Additional environment variables associated with a given task.
312 pub task_variables: TaskVariables,
313 /// Environment variables obtained when loading the project into Zed.
314 /// This is the environment one would get when `cd`ing in a terminal
315 /// into the project's root directory.
316 pub project_env: HashMap<String, String>,
317}
318
319/// This is a new type representing a 'tag' on a 'runnable symbol', typically a test of main() function, found via treesitter.
320#[derive(Clone, Debug)]
321pub struct RunnableTag(pub SharedString);
322
323pub fn shell_from_proto(proto: proto::Shell) -> anyhow::Result<Shell> {
324 let shell_type = proto.shell_type.context("invalid shell type")?;
325 let shell = match shell_type {
326 proto::shell::ShellType::System(_) => Shell::System,
327 proto::shell::ShellType::Program(program) => Shell::Program(program),
328 proto::shell::ShellType::WithArguments(program) => Shell::WithArguments {
329 program: program.program,
330 args: program.args,
331 title_override: None,
332 },
333 };
334 Ok(shell)
335}
336
337pub fn shell_to_proto(shell: Shell) -> proto::Shell {
338 let shell_type = match shell {
339 Shell::System => proto::shell::ShellType::System(proto::System {}),
340 Shell::Program(program) => proto::shell::ShellType::Program(program),
341 Shell::WithArguments {
342 program,
343 args,
344 title_override: _,
345 } => proto::shell::ShellType::WithArguments(proto::shell::WithArguments { program, args }),
346 };
347 proto::Shell {
348 shell_type: Some(shell_type),
349 }
350}
351
352type VsCodeEnvVariable = String;
353type VsCodeCommand = String;
354type ZedEnvVariable = String;
355
356struct EnvVariableReplacer {
357 variables: HashMap<VsCodeEnvVariable, ZedEnvVariable>,
358 commands: HashMap<VsCodeCommand, ZedEnvVariable>,
359}
360
361impl EnvVariableReplacer {
362 fn new(variables: HashMap<VsCodeEnvVariable, ZedEnvVariable>) -> Self {
363 Self {
364 variables,
365 commands: HashMap::default(),
366 }
367 }
368
369 fn with_commands(
370 mut self,
371 commands: impl IntoIterator<Item = (VsCodeCommand, ZedEnvVariable)>,
372 ) -> Self {
373 self.commands = commands.into_iter().collect();
374 self
375 }
376
377 fn replace_value(&self, input: serde_json::Value) -> serde_json::Value {
378 match input {
379 serde_json::Value::String(s) => serde_json::Value::String(self.replace(&s)),
380 serde_json::Value::Array(arr) => {
381 serde_json::Value::Array(arr.into_iter().map(|v| self.replace_value(v)).collect())
382 }
383 serde_json::Value::Object(obj) => serde_json::Value::Object(
384 obj.into_iter()
385 .map(|(k, v)| (self.replace(&k), self.replace_value(v)))
386 .collect(),
387 ),
388 _ => input,
389 }
390 }
391 // Replaces occurrences of VsCode-specific environment variables with Zed equivalents.
392 fn replace(&self, input: &str) -> String {
393 shellexpand::env_with_context_no_errors(&input, |var: &str| {
394 // 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.
395 let colon_position = var.find(':').unwrap_or(var.len());
396 let (left, right) = var.split_at(colon_position);
397 if left == "env" && !right.is_empty() {
398 let variable_name = &right[1..];
399 return Some(format!("${{{variable_name}}}"));
400 } else if left == "command" && !right.is_empty() {
401 let command_name = &right[1..];
402 if let Some(replacement_command) = self.commands.get(command_name) {
403 return Some(format!("${{{replacement_command}}}"));
404 }
405 }
406
407 let (variable_name, default) = (left, right);
408 let append_previous_default = |ret: &mut String| {
409 if !default.is_empty() {
410 ret.push_str(default);
411 }
412 };
413 if let Some(substitution) = self.variables.get(variable_name) {
414 // Got a VSCode->Zed hit, perform a substitution
415 let mut name = format!("${{{substitution}");
416 append_previous_default(&mut name);
417 name.push('}');
418 return Some(name);
419 }
420 // This is an unknown variable.
421 // 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.
422 // If there's a default, we need to return the string verbatim as otherwise shellexpand will apply that default for us.
423 if !default.is_empty() {
424 return Some(format!("${{{var}}}"));
425 }
426 // Else we can just return None and that variable will be left as is.
427 None
428 })
429 .into_owned()
430 }
431}