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