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