1//! Baseline interface of Tasks in Zed: all tasks in Zed are intended to use those for implementing their own logic.
2
3mod debug_format;
4mod serde_helpers;
5pub mod static_source;
6mod task_template;
7mod vscode_debug_format;
8mod vscode_format;
9
10use collections::{HashMap, HashSet, hash_map};
11use gpui::SharedString;
12use schemars::JsonSchema;
13use serde::{Deserialize, Serialize};
14use std::borrow::Cow;
15use std::path::PathBuf;
16use std::str::FromStr;
17
18pub use debug_format::{
19 AttachRequest, DebugRequest, DebugScenario, DebugTaskFile, LaunchRequest, TcpArgumentsTemplate,
20};
21pub use task_template::{
22 DebugArgsRequest, HideStrategy, RevealStrategy, TaskModal, TaskTemplate, TaskTemplates,
23};
24pub use vscode_debug_format::VsCodeDebugTaskFile;
25pub use vscode_format::VsCodeTaskFile;
26pub use zed_actions::RevealTarget;
27
28/// Task identifier, unique within the application.
29/// Based on it, task reruns and terminal tabs are managed.
30#[derive(Default, Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Deserialize)]
31pub struct TaskId(pub String);
32
33/// Contains all information needed by Zed to spawn a new terminal tab for the given task.
34#[derive(Default, Debug, Clone, PartialEq, Eq)]
35pub struct SpawnInTerminal {
36 /// Id of the task to use when determining task tab affinity.
37 pub id: TaskId,
38 /// Full unshortened form of `label` field.
39 pub full_label: String,
40 /// Human readable name of the terminal tab.
41 pub label: String,
42 /// Executable command to spawn.
43 pub command: String,
44 /// Arguments to the command, potentially unsubstituted,
45 /// to let the shell that spawns the command to do the substitution, if needed.
46 pub args: Vec<String>,
47 /// A human-readable label, containing command and all of its arguments, joined and substituted.
48 pub command_label: String,
49 /// Current working directory to spawn the command into.
50 pub cwd: Option<PathBuf>,
51 /// Env overrides for the command, will be appended to the terminal's environment from the settings.
52 pub env: HashMap<String, String>,
53 /// Whether to use a new terminal tab or reuse the existing one to spawn the process.
54 pub use_new_terminal: bool,
55 /// Whether to allow multiple instances of the same task to be run, or rather wait for the existing ones to finish.
56 pub allow_concurrent_runs: bool,
57 /// What to do with the terminal pane and tab, after the command was started.
58 pub reveal: RevealStrategy,
59 /// Where to show tasks' terminal output.
60 pub reveal_target: RevealTarget,
61 /// What to do with the terminal pane and tab, after the command had finished.
62 pub hide: HideStrategy,
63 /// Which shell to use when spawning the task.
64 pub shell: Shell,
65 /// Whether to show the task summary line in the task output (sucess/failure).
66 pub show_summary: bool,
67 /// Whether to show the command line in the task output.
68 pub show_command: bool,
69 /// Whether to show the rerun button in the terminal tab.
70 pub show_rerun: bool,
71}
72
73impl SpawnInTerminal {
74 pub fn to_proto(&self) -> proto::SpawnInTerminal {
75 proto::SpawnInTerminal {
76 label: self.label.clone(),
77 command: self.command.clone(),
78 args: self.args.clone(),
79 env: self
80 .env
81 .iter()
82 .map(|(k, v)| (k.clone(), v.clone()))
83 .collect(),
84 cwd: self
85 .cwd
86 .clone()
87 .map(|cwd| cwd.to_string_lossy().into_owned()),
88 }
89 }
90
91 pub fn from_proto(proto: proto::SpawnInTerminal) -> Self {
92 Self {
93 label: proto.label.clone(),
94 command: proto.command.clone(),
95 args: proto.args.clone(),
96 env: proto.env.into_iter().collect(),
97 cwd: proto.cwd.map(PathBuf::from).clone(),
98 ..Default::default()
99 }
100 }
101}
102
103/// A final form of the [`TaskTemplate`], that got resolved with a particular [`TaskContext`] and now is ready to spawn the actual task.
104#[derive(Clone, Debug, PartialEq, Eq)]
105pub struct ResolvedTask {
106 /// A way to distinguish tasks produced by the same template, but different contexts.
107 /// NOTE: Resolved tasks may have the same labels, commands and do the same things,
108 /// but still may have different ids if the context was different during the resolution.
109 /// Since the template has `env` field, for a generic task that may be a bash command,
110 /// so it's impossible to determine the id equality without more context in a generic case.
111 pub id: TaskId,
112 /// A template the task got resolved from.
113 original_task: TaskTemplate,
114 /// Full, unshortened label of the task after all resolutions are made.
115 pub resolved_label: String,
116 /// Variables that were substituted during the task template resolution.
117 substituted_variables: HashSet<VariableName>,
118 /// Further actions that need to take place after the resolved task is spawned,
119 /// with all task variables resolved.
120 pub resolved: SpawnInTerminal,
121}
122
123impl ResolvedTask {
124 /// A task template before the resolution.
125 pub fn original_task(&self) -> &TaskTemplate {
126 &self.original_task
127 }
128
129 /// Variables that were substituted during the task template resolution.
130 pub fn substituted_variables(&self) -> &HashSet<VariableName> {
131 &self.substituted_variables
132 }
133
134 /// A human-readable label to display in the UI.
135 pub fn display_label(&self) -> &str {
136 self.resolved.label.as_str()
137 }
138}
139
140/// Variables, available for use in [`TaskContext`] when a Zed's [`TaskTemplate`] gets resolved into a [`ResolvedTask`].
141/// Name of the variable must be a valid shell variable identifier, which generally means that it is
142/// a word consisting only of alphanumeric characters and underscores,
143/// and beginning with an alphabetic character or an underscore.
144#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
145pub enum VariableName {
146 /// An absolute path of the currently opened file.
147 File,
148 /// A path of the currently opened file (relative to worktree root).
149 RelativeFile,
150 /// The currently opened filename.
151 Filename,
152 /// The path to a parent directory of a currently opened file.
153 Dirname,
154 /// Stem (filename without extension) of the currently opened file.
155 Stem,
156 /// An absolute path of the currently opened worktree, that contains the file.
157 WorktreeRoot,
158 /// A symbol text, that contains latest cursor/selection position.
159 Symbol,
160 /// A row with the latest cursor/selection position.
161 Row,
162 /// A column with the latest cursor/selection position.
163 Column,
164 /// Text from the latest selection.
165 SelectedText,
166 /// The symbol selected by the symbol tagging system, specifically the @run capture in a runnables.scm
167 RunnableSymbol,
168 /// Custom variable, provided by the plugin or other external source.
169 /// Will be printed with `CUSTOM_` prefix to avoid potential conflicts with other variables.
170 Custom(Cow<'static, str>),
171}
172
173impl VariableName {
174 /// Generates a `$VARIABLE`-like string value to be used in templates.
175 pub fn template_value(&self) -> String {
176 format!("${self}")
177 }
178 /// Generates a `"$VARIABLE"`-like string, to be used instead of `Self::template_value` when expanded value could contain spaces or special characters.
179 pub fn template_value_with_whitespace(&self) -> String {
180 format!("\"${self}\"")
181 }
182}
183
184impl FromStr for VariableName {
185 type Err = ();
186
187 fn from_str(s: &str) -> Result<Self, Self::Err> {
188 let without_prefix = s.strip_prefix(ZED_VARIABLE_NAME_PREFIX).ok_or(())?;
189 let value = match without_prefix {
190 "FILE" => Self::File,
191 "FILENAME" => Self::Filename,
192 "RELATIVE_FILE" => Self::RelativeFile,
193 "DIRNAME" => Self::Dirname,
194 "STEM" => Self::Stem,
195 "WORKTREE_ROOT" => Self::WorktreeRoot,
196 "SYMBOL" => Self::Symbol,
197 "RUNNABLE_SYMBOL" => Self::RunnableSymbol,
198 "SELECTED_TEXT" => Self::SelectedText,
199 "ROW" => Self::Row,
200 "COLUMN" => Self::Column,
201 _ => {
202 if let Some(custom_name) =
203 without_prefix.strip_prefix(ZED_CUSTOM_VARIABLE_NAME_PREFIX)
204 {
205 Self::Custom(Cow::Owned(custom_name.to_owned()))
206 } else {
207 return Err(());
208 }
209 }
210 };
211 Ok(value)
212 }
213}
214
215/// A prefix that all [`VariableName`] variants are prefixed with when used in environment variables and similar template contexts.
216pub const ZED_VARIABLE_NAME_PREFIX: &str = "ZED_";
217const ZED_CUSTOM_VARIABLE_NAME_PREFIX: &str = "CUSTOM_";
218
219impl std::fmt::Display for VariableName {
220 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
221 match self {
222 Self::File => write!(f, "{ZED_VARIABLE_NAME_PREFIX}FILE"),
223 Self::Filename => write!(f, "{ZED_VARIABLE_NAME_PREFIX}FILENAME"),
224 Self::RelativeFile => write!(f, "{ZED_VARIABLE_NAME_PREFIX}RELATIVE_FILE"),
225 Self::Dirname => write!(f, "{ZED_VARIABLE_NAME_PREFIX}DIRNAME"),
226 Self::Stem => write!(f, "{ZED_VARIABLE_NAME_PREFIX}STEM"),
227 Self::WorktreeRoot => write!(f, "{ZED_VARIABLE_NAME_PREFIX}WORKTREE_ROOT"),
228 Self::Symbol => write!(f, "{ZED_VARIABLE_NAME_PREFIX}SYMBOL"),
229 Self::Row => write!(f, "{ZED_VARIABLE_NAME_PREFIX}ROW"),
230 Self::Column => write!(f, "{ZED_VARIABLE_NAME_PREFIX}COLUMN"),
231 Self::SelectedText => write!(f, "{ZED_VARIABLE_NAME_PREFIX}SELECTED_TEXT"),
232 Self::RunnableSymbol => write!(f, "{ZED_VARIABLE_NAME_PREFIX}RUNNABLE_SYMBOL"),
233 Self::Custom(s) => write!(
234 f,
235 "{ZED_VARIABLE_NAME_PREFIX}{ZED_CUSTOM_VARIABLE_NAME_PREFIX}{s}"
236 ),
237 }
238 }
239}
240
241/// Container for predefined environment variables that describe state of Zed at the time the task was spawned.
242#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
243pub struct TaskVariables(HashMap<VariableName, String>);
244
245impl TaskVariables {
246 /// Inserts another variable into the container, overwriting the existing one if it already exists — in this case, the old value is returned.
247 pub fn insert(&mut self, variable: VariableName, value: String) -> Option<String> {
248 self.0.insert(variable, value)
249 }
250
251 /// Extends the container with another one, overwriting the existing variables on collision.
252 pub fn extend(&mut self, other: Self) {
253 self.0.extend(other.0);
254 }
255 /// Get the value associated with given variable name, if there is one.
256 pub fn get(&self, key: &VariableName) -> Option<&str> {
257 self.0.get(key).map(|s| s.as_str())
258 }
259 /// Clear out variables obtained from tree-sitter queries, which are prefixed with '_' character
260 pub fn sweep(&mut self) {
261 self.0.retain(|name, _| {
262 if let VariableName::Custom(name) = name {
263 !name.starts_with('_')
264 } else {
265 true
266 }
267 })
268 }
269}
270
271impl FromIterator<(VariableName, String)> for TaskVariables {
272 fn from_iter<T: IntoIterator<Item = (VariableName, String)>>(iter: T) -> Self {
273 Self(HashMap::from_iter(iter))
274 }
275}
276
277impl IntoIterator for TaskVariables {
278 type Item = (VariableName, String);
279
280 type IntoIter = hash_map::IntoIter<VariableName, String>;
281
282 fn into_iter(self) -> Self::IntoIter {
283 self.0.into_iter()
284 }
285}
286
287/// Keeps track of the file associated with a task and context of tasks execution (i.e. current file or current function).
288/// Keeps all Zed-related state inside, used to produce a resolved task out of its template.
289#[derive(Clone, Debug, Default, PartialEq, Eq)]
290pub struct TaskContext {
291 /// A path to a directory in which the task should be executed.
292 pub cwd: Option<PathBuf>,
293 /// Additional environment variables associated with a given task.
294 pub task_variables: TaskVariables,
295 /// Environment variables obtained when loading the project into Zed.
296 /// This is the environment one would get when `cd`ing in a terminal
297 /// into the project's root directory.
298 pub project_env: HashMap<String, String>,
299}
300
301/// This is a new type representing a 'tag' on a 'runnable symbol', typically a test of main() function, found via treesitter.
302#[derive(Clone, Debug)]
303pub struct RunnableTag(pub SharedString);
304
305/// Shell configuration to open the terminal with.
306#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
307#[serde(rename_all = "snake_case")]
308pub enum Shell {
309 /// Use the system's default terminal configuration in /etc/passwd
310 #[default]
311 System,
312 /// Use a specific program with no arguments.
313 Program(String),
314 /// Use a specific program with arguments.
315 WithArguments {
316 /// The program to run.
317 program: String,
318 /// The arguments to pass to the program.
319 args: Vec<String>,
320 /// An optional string to override the title of the terminal tab
321 title_override: Option<SharedString>,
322 },
323}
324
325#[cfg(target_os = "windows")]
326#[derive(Debug, Clone, Copy, PartialEq, Eq)]
327enum WindowsShellType {
328 Powershell,
329 Cmd,
330 Other,
331}
332
333/// ShellBuilder is used to turn a user-requested task into a
334/// program that can be executed by the shell.
335pub struct ShellBuilder {
336 program: String,
337 args: Vec<String>,
338}
339
340pub static DEFAULT_REMOTE_SHELL: &str = "\"${SHELL:-sh}\"";
341
342impl ShellBuilder {
343 /// Create a new ShellBuilder as configured.
344 pub fn new(is_local: bool, shell: &Shell) -> Self {
345 let (program, args) = match shell {
346 Shell::System => {
347 if is_local {
348 (Self::system_shell(), Vec::new())
349 } else {
350 (DEFAULT_REMOTE_SHELL.to_string(), Vec::new())
351 }
352 }
353 Shell::Program(shell) => (shell.clone(), Vec::new()),
354 Shell::WithArguments { program, args, .. } => (program.clone(), args.clone()),
355 };
356 Self { program, args }
357 }
358}
359
360#[cfg(not(target_os = "windows"))]
361impl ShellBuilder {
362 /// Returns the label to show in the terminal tab
363 pub fn command_label(&self, command_label: &str) -> String {
364 format!("{} -i -c '{}'", self.program, command_label)
365 }
366
367 /// Returns the program and arguments to run this task in a shell.
368 pub fn build(mut self, task_command: String, task_args: &Vec<String>) -> (String, Vec<String>) {
369 let combined_command = task_args
370 .into_iter()
371 .fold(task_command, |mut command, arg| {
372 command.push(' ');
373 command.push_str(&arg);
374 command
375 });
376 self.args
377 .extend(["-i".to_owned(), "-c".to_owned(), combined_command]);
378
379 (self.program, self.args)
380 }
381
382 fn system_shell() -> String {
383 std::env::var("SHELL").unwrap_or("/bin/sh".to_string())
384 }
385}
386
387#[cfg(target_os = "windows")]
388impl ShellBuilder {
389 /// Returns the label to show in the terminal tab
390 pub fn command_label(&self, command_label: &str) -> String {
391 match self.windows_shell_type() {
392 WindowsShellType::Powershell => {
393 format!("{} -C '{}'", self.program, command_label)
394 }
395 WindowsShellType::Cmd => {
396 format!("{} /C '{}'", self.program, command_label)
397 }
398 WindowsShellType::Other => {
399 format!("{} -i -c '{}'", self.program, command_label)
400 }
401 }
402 }
403
404 /// Returns the program and arguments to run this task in a shell.
405 pub fn build(mut self, task_command: String, task_args: &Vec<String>) -> (String, Vec<String>) {
406 let combined_command = task_args
407 .into_iter()
408 .fold(task_command, |mut command, arg| {
409 command.push(' ');
410 command.push_str(&self.to_windows_shell_variable(arg.to_string()));
411 command
412 });
413
414 match self.windows_shell_type() {
415 WindowsShellType::Powershell => self.args.extend(["-C".to_owned(), combined_command]),
416 WindowsShellType::Cmd => self.args.extend(["/C".to_owned(), combined_command]),
417 WindowsShellType::Other => {
418 self.args
419 .extend(["-i".to_owned(), "-c".to_owned(), combined_command])
420 }
421 }
422
423 (self.program, self.args)
424 }
425 fn windows_shell_type(&self) -> WindowsShellType {
426 if self.program == "powershell"
427 || self.program.ends_with("powershell.exe")
428 || self.program == "pwsh"
429 || self.program.ends_with("pwsh.exe")
430 {
431 WindowsShellType::Powershell
432 } else if self.program == "cmd" || self.program.ends_with("cmd.exe") {
433 WindowsShellType::Cmd
434 } else {
435 // Someother shell detected, the user might install and use a
436 // unix-like shell.
437 WindowsShellType::Other
438 }
439 }
440
441 // `alacritty_terminal` uses this as default on Windows. See:
442 // https://github.com/alacritty/alacritty/blob/0d4ab7bca43213d96ddfe40048fc0f922543c6f8/alacritty_terminal/src/tty/windows/mod.rs#L130
443 // We could use `util::get_windows_system_shell()` here, but we are running tasks here, so leave it to `powershell.exe`
444 // should be okay.
445 fn system_shell() -> String {
446 "powershell.exe".to_string()
447 }
448
449 fn to_windows_shell_variable(&self, input: String) -> String {
450 match self.windows_shell_type() {
451 WindowsShellType::Powershell => Self::to_powershell_variable(input),
452 WindowsShellType::Cmd => Self::to_cmd_variable(input),
453 WindowsShellType::Other => input,
454 }
455 }
456
457 fn to_cmd_variable(input: String) -> String {
458 if let Some(var_str) = input.strip_prefix("${") {
459 if var_str.find(':').is_none() {
460 // If the input starts with "${", remove the trailing "}"
461 format!("%{}%", &var_str[..var_str.len() - 1])
462 } else {
463 // `${SOME_VAR:-SOME_DEFAULT}`, we currently do not handle this situation,
464 // which will result in the task failing to run in such cases.
465 input
466 }
467 } else if let Some(var_str) = input.strip_prefix('$') {
468 // If the input starts with "$", directly append to "$env:"
469 format!("%{}%", var_str)
470 } else {
471 // If no prefix is found, return the input as is
472 input
473 }
474 }
475
476 fn to_powershell_variable(input: String) -> String {
477 if let Some(var_str) = input.strip_prefix("${") {
478 if var_str.find(':').is_none() {
479 // If the input starts with "${", remove the trailing "}"
480 format!("$env:{}", &var_str[..var_str.len() - 1])
481 } else {
482 // `${SOME_VAR:-SOME_DEFAULT}`, we currently do not handle this situation,
483 // which will result in the task failing to run in such cases.
484 input
485 }
486 } else if let Some(var_str) = input.strip_prefix('$') {
487 // If the input starts with "$", directly append to "$env:"
488 format!("$env:{}", var_str)
489 } else {
490 // If no prefix is found, return the input as is
491 input
492 }
493 }
494}
495
496type VsCodeEnvVariable = String;
497type ZedEnvVariable = String;
498
499struct EnvVariableReplacer {
500 variables: HashMap<VsCodeEnvVariable, ZedEnvVariable>,
501}
502
503impl EnvVariableReplacer {
504 fn new(variables: HashMap<VsCodeEnvVariable, ZedEnvVariable>) -> Self {
505 Self { variables }
506 }
507 // Replaces occurrences of VsCode-specific environment variables with Zed equivalents.
508 fn replace(&self, input: &str) -> String {
509 shellexpand::env_with_context_no_errors(&input, |var: &str| {
510 // 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.
511 let colon_position = var.find(':').unwrap_or(var.len());
512 let (left, right) = var.split_at(colon_position);
513 if left == "env" && !right.is_empty() {
514 let variable_name = &right[1..];
515 return Some(format!("${{{variable_name}}}"));
516 }
517 let (variable_name, default) = (left, right);
518 let append_previous_default = |ret: &mut String| {
519 if !default.is_empty() {
520 ret.push_str(default);
521 }
522 };
523 if let Some(substitution) = self.variables.get(variable_name) {
524 // Got a VSCode->Zed hit, perform a substitution
525 let mut name = format!("${{{substitution}");
526 append_previous_default(&mut name);
527 name.push('}');
528 return Some(name);
529 }
530 // This is an unknown variable.
531 // 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.
532 // If there's a default, we need to return the string verbatim as otherwise shellexpand will apply that default for us.
533 if !default.is_empty() {
534 return Some(format!("${{{var}}}"));
535 }
536 // Else we can just return None and that variable will be left as is.
537 None
538 })
539 .into_owned()
540 }
541}