lib.rs

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