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::{hash_map, HashMap, HashSet};
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 HideStrategy, RevealStrategy, TaskModal, TaskTemplate, TaskTemplates, TaskType,
23};
24pub use vscode_format::VsCodeTaskFile;
25pub use zed_actions::RevealTarget;
26
27/// Task identifier, unique within the application.
28/// Based on it, task reruns and terminal tabs are managed.
29#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Deserialize)]
30pub struct TaskId(pub String);
31
32/// Contains all information needed by Zed to spawn a new terminal tab for the given task.
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct SpawnInTerminal {
35 /// Id of the task to use when determining task tab affinity.
36 pub id: TaskId,
37 /// Full unshortened form of `label` field.
38 pub full_label: String,
39 /// Human readable name of the terminal tab.
40 pub label: String,
41 /// Executable command to spawn.
42 pub command: String,
43 /// Arguments to the command, potentially unsubstituted,
44 /// to let the shell that spawns the command to do the substitution, if needed.
45 pub args: Vec<String>,
46 /// A human-readable label, containing command and all of its arguments, joined and substituted.
47 pub command_label: String,
48 /// Current working directory to spawn the command into.
49 pub cwd: Option<PathBuf>,
50 /// Env overrides for the command, will be appended to the terminal's environment from the settings.
51 pub env: HashMap<String, String>,
52 /// Whether to use a new terminal tab or reuse the existing one to spawn the process.
53 pub use_new_terminal: bool,
54 /// Whether to allow multiple instances of the same task to be run, or rather wait for the existing ones to finish.
55 pub allow_concurrent_runs: bool,
56 /// What to do with the terminal pane and tab, after the command was started.
57 pub reveal: RevealStrategy,
58 /// Where to show tasks' terminal output.
59 pub reveal_target: RevealTarget,
60 /// What to do with the terminal pane and tab, after the command had finished.
61 pub hide: HideStrategy,
62 /// Which shell to use when spawning the task.
63 pub shell: Shell,
64 /// Tells debug tasks which program to debug
65 pub program: Option<String>,
66 /// Whether to show the task summary line in the task output (sucess/failure).
67 pub show_summary: bool,
68 /// Whether to show the command line in the task output.
69 pub show_command: bool,
70 /// Whether to show the rerun button in the terminal tab.
71 pub show_rerun: bool,
72}
73
74/// A final form of the [`TaskTemplate`], that got resolved with a particular [`TaskContext`] and now is ready to spawn the actual task.
75#[derive(Clone, Debug, PartialEq, Eq)]
76pub struct ResolvedTask {
77 /// A way to distinguish tasks produced by the same template, but different contexts.
78 /// NOTE: Resolved tasks may have the same labels, commands and do the same things,
79 /// but still may have different ids if the context was different during the resolution.
80 /// Since the template has `env` field, for a generic task that may be a bash command,
81 /// so it's impossible to determine the id equality without more context in a generic case.
82 pub id: TaskId,
83 /// A template the task got resolved from.
84 original_task: TaskTemplate,
85 /// Full, unshortened label of the task after all resolutions are made.
86 pub resolved_label: String,
87 /// Variables that were substituted during the task template resolution.
88 substituted_variables: HashSet<VariableName>,
89 /// Further actions that need to take place after the resolved task is spawned,
90 /// with all task variables resolved.
91 pub resolved: Option<SpawnInTerminal>,
92}
93
94impl ResolvedTask {
95 /// A task template before the resolution.
96 pub fn original_task(&self) -> &TaskTemplate {
97 &self.original_task
98 }
99
100 /// Get the task type that determines what this task is used for
101 /// And where is it shown in the UI
102 pub fn task_type(&self) -> TaskType {
103 self.original_task.task_type.clone()
104 }
105
106 /// Get the configuration for the debug adapter that should be used for this task.
107 pub fn resolved_debug_adapter_config(&self) -> Option<DebugTaskDefinition> {
108 match self.original_task.task_type.clone() {
109 TaskType::Script => None,
110 TaskType::Debug(mut adapter_config) => {
111 if let Some(resolved) = &self.resolved {
112 adapter_config.label = resolved.label.clone();
113 if let DebugRequestType::Launch(ref mut launch) = adapter_config.request {
114 if let Some(program) = resolved.program.clone() {
115 launch.program = program;
116 }
117 if let Some(cwd) = resolved.cwd.clone() {
118 launch.cwd = Some(cwd);
119 }
120 }
121 }
122
123 Some(adapter_config)
124 }
125 }
126 }
127
128 /// Variables that were substituted during the task template resolution.
129 pub fn substituted_variables(&self) -> &HashSet<VariableName> {
130 &self.substituted_variables
131 }
132
133 /// A human-readable label to display in the UI.
134 pub fn display_label(&self) -> &str {
135 self.resolved
136 .as_ref()
137 .map(|resolved| resolved.label.as_str())
138 .unwrap_or_else(|| 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
273impl FromIterator<(VariableName, String)> for TaskVariables {
274 fn from_iter<T: IntoIterator<Item = (VariableName, String)>>(iter: T) -> Self {
275 Self(HashMap::from_iter(iter))
276 }
277}
278
279impl IntoIterator for TaskVariables {
280 type Item = (VariableName, String);
281
282 type IntoIter = hash_map::IntoIter<VariableName, String>;
283
284 fn into_iter(self) -> Self::IntoIter {
285 self.0.into_iter()
286 }
287}
288
289/// Keeps track of the file associated with a task and context of tasks execution (i.e. current file or current function).
290/// Keeps all Zed-related state inside, used to produce a resolved task out of its template.
291#[derive(Clone, Debug, Default, PartialEq, Eq)]
292pub struct TaskContext {
293 /// A path to a directory in which the task should be executed.
294 pub cwd: Option<PathBuf>,
295 /// Additional environment variables associated with a given task.
296 pub task_variables: TaskVariables,
297 /// Environment variables obtained when loading the project into Zed.
298 /// This is the environment one would get when `cd`ing in a terminal
299 /// into the project's root directory.
300 pub project_env: HashMap<String, String>,
301}
302
303/// This is a new type representing a 'tag' on a 'runnable symbol', typically a test of main() function, found via treesitter.
304#[derive(Clone, Debug)]
305pub struct RunnableTag(pub SharedString);
306
307/// Shell configuration to open the terminal with.
308#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
309#[serde(rename_all = "snake_case")]
310pub enum Shell {
311 /// Use the system's default terminal configuration in /etc/passwd
312 #[default]
313 System,
314 /// Use a specific program with no arguments.
315 Program(String),
316 /// Use a specific program with arguments.
317 WithArguments {
318 /// The program to run.
319 program: String,
320 /// The arguments to pass to the program.
321 args: Vec<String>,
322 /// An optional string to override the title of the terminal tab
323 title_override: Option<SharedString>,
324 },
325}
326
327#[cfg(target_os = "windows")]
328#[derive(Debug, Clone, Copy, PartialEq, Eq)]
329enum WindowsShellType {
330 Powershell,
331 Cmd,
332 Other,
333}
334
335/// ShellBuilder is used to turn a user-requested task into a
336/// program that can be executed by the shell.
337pub struct ShellBuilder {
338 program: String,
339 args: Vec<String>,
340}
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 ("\"${SHELL:-sh}\"".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::retrieve_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}