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