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