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