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::{HashMap, HashSet};
  9use gpui::SharedString;
 10use serde::Serialize;
 11use std::path::PathBuf;
 12use std::{borrow::Cow, path::Path};
 13
 14pub use task_template::{RevealStrategy, TaskTemplate, TaskTemplates};
 15pub use vscode_format::VsCodeTaskFile;
 16
 17/// Task identifier, unique within the application.
 18/// Based on it, task reruns and terminal tabs are managed.
 19#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
 20pub struct TaskId(pub String);
 21
 22/// TerminalWorkDir describes where a task should be run
 23#[derive(Debug, Clone, PartialEq, Eq)]
 24pub enum TerminalWorkDir {
 25    /// Local is on this machine
 26    Local(PathBuf),
 27    /// SSH runs the terminal over ssh
 28    Ssh {
 29        /// The command to run to connect
 30        ssh_command: String,
 31        /// The path on the remote server
 32        path: Option<String>,
 33    },
 34}
 35
 36impl TerminalWorkDir {
 37    /// Returns whether the terminal task is supposed to be spawned on a local machine or not.
 38    pub fn is_local(&self) -> bool {
 39        match self {
 40            Self::Local(_) => true,
 41            Self::Ssh { .. } => false,
 42        }
 43    }
 44
 45    /// Returns a local CWD if the terminal is local, None otherwise.
 46    pub fn local_path(&self) -> Option<&Path> {
 47        match self {
 48            Self::Local(path) => Some(path),
 49            Self::Ssh { .. } => None,
 50        }
 51    }
 52}
 53
 54/// Contains all information needed by Zed to spawn a new terminal tab for the given task.
 55#[derive(Debug, Clone, PartialEq, Eq)]
 56pub struct SpawnInTerminal {
 57    /// Id of the task to use when determining task tab affinity.
 58    pub id: TaskId,
 59    /// Full unshortened form of `label` field.
 60    pub full_label: String,
 61    /// Human readable name of the terminal tab.
 62    pub label: String,
 63    /// Executable command to spawn.
 64    pub command: String,
 65    /// Arguments to the command, potentially unsubstituted,
 66    /// to let the shell that spawns the command to do the substitution, if needed.
 67    pub args: Vec<String>,
 68    /// A human-readable label, containing command and all of its arguments, joined and substituted.
 69    pub command_label: String,
 70    /// Current working directory to spawn the command into.
 71    pub cwd: Option<TerminalWorkDir>,
 72    /// Env overrides for the command, will be appended to the terminal's environment from the settings.
 73    pub env: HashMap<String, String>,
 74    /// Whether to use a new terminal tab or reuse the existing one to spawn the process.
 75    pub use_new_terminal: bool,
 76    /// Whether to allow multiple instances of the same task to be run, or rather wait for the existing ones to finish.
 77    pub allow_concurrent_runs: bool,
 78    /// What to do with the terminal pane and tab, after the command was started.
 79    pub reveal: RevealStrategy,
 80}
 81
 82/// A final form of the [`TaskTemplate`], that got resolved with a particualar [`TaskContext`] and now is ready to spawn the actual task.
 83#[derive(Clone, Debug, PartialEq, Eq)]
 84pub struct ResolvedTask {
 85    /// A way to distinguish tasks produced by the same template, but different contexts.
 86    /// NOTE: Resolved tasks may have the same labels, commands and do the same things,
 87    /// but still may have different ids if the context was different during the resolution.
 88    /// Since the template has `env` field, for a generic task that may be a bash command,
 89    /// so it's impossible to determine the id equality without more context in a generic case.
 90    pub id: TaskId,
 91    /// A template the task got resolved from.
 92    original_task: TaskTemplate,
 93    /// Full, unshortened label of the task after all resolutions are made.
 94    pub resolved_label: String,
 95    /// Variables that were substituted during the task template resolution.
 96    substituted_variables: HashSet<VariableName>,
 97    /// Further actions that need to take place after the resolved task is spawned,
 98    /// with all task variables resolved.
 99    pub resolved: Option<SpawnInTerminal>,
100}
101
102impl ResolvedTask {
103    /// A task template before the resolution.
104    pub fn original_task(&self) -> &TaskTemplate {
105        &self.original_task
106    }
107
108    /// Variables that were substituted during the task template resolution.
109    pub fn substituted_variables(&self) -> &HashSet<VariableName> {
110        &self.substituted_variables
111    }
112
113    /// A human-readable label to display in the UI.
114    pub fn display_label(&self) -> &str {
115        self.resolved
116            .as_ref()
117            .map(|resolved| resolved.label.as_str())
118            .unwrap_or_else(|| self.resolved_label.as_str())
119    }
120}
121
122/// Variables, available for use in [`TaskContext`] when a Zed's [`TaskTemplate`] gets resolved into a [`ResolvedTask`].
123#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
124pub enum VariableName {
125    /// An absolute path of the currently opened file.
126    File,
127    /// A path of the currently opened file (relative to worktree root).
128    RelativeFile,
129    /// The currently opened filename.
130    Filename,
131    /// The path to a parent directory of a currently opened file.
132    Dirname,
133    /// Stem (filename without extension) of the currently opened file.
134    Stem,
135    /// An absolute path of the currently opened worktree, that contains the file.
136    WorktreeRoot,
137    /// A symbol text, that contains latest cursor/selection position.
138    Symbol,
139    /// A row with the latest cursor/selection position.
140    Row,
141    /// A column with the latest cursor/selection position.
142    Column,
143    /// Text from the latest selection.
144    SelectedText,
145    /// The symbol selected by the symbol tagging system, specifically the @run capture in a runnables.scm
146    RunnableSymbol,
147    /// Custom variable, provided by the plugin or other external source.
148    /// Will be printed with `ZED_` prefix to avoid potential conflicts with other variables.
149    Custom(Cow<'static, str>),
150}
151
152impl VariableName {
153    /// Generates a `$VARIABLE`-like string value to be used in templates.
154    /// Custom variables are wrapped in `${}` to avoid substitution issues with whitespaces.
155    pub fn template_value(&self) -> String {
156        if matches!(self, Self::Custom(_)) {
157            format!("${{{self}}}")
158        } else {
159            format!("${self}")
160        }
161    }
162}
163
164/// A prefix that all [`VariableName`] variants are prefixed with when used in environment variables and similar template contexts.
165pub const ZED_VARIABLE_NAME_PREFIX: &str = "ZED_";
166
167impl std::fmt::Display for VariableName {
168    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
169        match self {
170            Self::File => write!(f, "{ZED_VARIABLE_NAME_PREFIX}FILE"),
171            Self::Filename => write!(f, "{ZED_VARIABLE_NAME_PREFIX}FILENAME"),
172            Self::RelativeFile => write!(f, "{ZED_VARIABLE_NAME_PREFIX}RELATIVE_FILE"),
173            Self::Dirname => write!(f, "{ZED_VARIABLE_NAME_PREFIX}DIRNAME"),
174            Self::Stem => write!(f, "{ZED_VARIABLE_NAME_PREFIX}STEM"),
175            Self::WorktreeRoot => write!(f, "{ZED_VARIABLE_NAME_PREFIX}WORKTREE_ROOT"),
176            Self::Symbol => write!(f, "{ZED_VARIABLE_NAME_PREFIX}SYMBOL"),
177            Self::Row => write!(f, "{ZED_VARIABLE_NAME_PREFIX}ROW"),
178            Self::Column => write!(f, "{ZED_VARIABLE_NAME_PREFIX}COLUMN"),
179            Self::SelectedText => write!(f, "{ZED_VARIABLE_NAME_PREFIX}SELECTED_TEXT"),
180            Self::RunnableSymbol => write!(f, "{ZED_VARIABLE_NAME_PREFIX}RUNNABLE_SYMBOL"),
181            Self::Custom(s) => write!(f, "{ZED_VARIABLE_NAME_PREFIX}CUSTOM_{s}"),
182        }
183    }
184}
185
186/// Container for predefined environment variables that describe state of Zed at the time the task was spawned.
187#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
188pub struct TaskVariables(HashMap<VariableName, String>);
189
190impl TaskVariables {
191    /// Inserts another variable into the container, overwriting the existing one if it already exists — in this case, the old value is returned.
192    pub fn insert(&mut self, variable: VariableName, value: String) -> Option<String> {
193        self.0.insert(variable, value)
194    }
195
196    /// Extends the container with another one, overwriting the existing variables on collision.
197    pub fn extend(&mut self, other: Self) {
198        self.0.extend(other.0);
199    }
200    /// Get the value associated with given variable name, if there is one.
201    pub fn get(&self, key: &VariableName) -> Option<&str> {
202        self.0.get(key).map(|s| s.as_str())
203    }
204    /// Clear out variables obtained from tree-sitter queries, which are prefixed with '_' character
205    pub fn sweep(&mut self) {
206        self.0.retain(|name, _| {
207            if let VariableName::Custom(name) = name {
208                !name.starts_with('_')
209            } else {
210                true
211            }
212        })
213    }
214}
215
216impl FromIterator<(VariableName, String)> for TaskVariables {
217    fn from_iter<T: IntoIterator<Item = (VariableName, String)>>(iter: T) -> Self {
218        Self(HashMap::from_iter(iter))
219    }
220}
221
222/// Keeps track of the file associated with a task and context of tasks execution (i.e. current file or current function).
223/// Keeps all Zed-related state inside, used to produce a resolved task out of its template.
224#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
225pub struct TaskContext {
226    /// A path to a directory in which the task should be executed.
227    pub cwd: Option<PathBuf>,
228    /// Additional environment variables associated with a given task.
229    pub task_variables: TaskVariables,
230}
231
232/// This is a new type representing a 'tag' on a 'runnable symbol', typically a test of main() function, found via treesitter.
233#[derive(Clone, Debug)]
234pub struct RunnableTag(pub SharedString);