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