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::borrow::Cow;
 12use std::path::PathBuf;
 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    /// is_local
 38    pub fn is_local(&self) -> bool {
 39        match self {
 40            TerminalWorkDir::Local(_) => true,
 41            TerminalWorkDir::Ssh { .. } => false,
 42        }
 43    }
 44
 45    /// local_path
 46    pub fn local_path(&self) -> Option<PathBuf> {
 47        match self {
 48            TerminalWorkDir::Local(path) => Some(path.clone()),
 49            TerminalWorkDir::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    /// An absolute path of the currently opened worktree, that contains the file.
128    WorktreeRoot,
129    /// A symbol text, that contains latest cursor/selection position.
130    Symbol,
131    /// A row with the latest cursor/selection position.
132    Row,
133    /// A column with the latest cursor/selection position.
134    Column,
135    /// Text from the latest selection.
136    SelectedText,
137    /// The symbol selected by the symbol tagging system, specifically the @run capture in a runnables.scm
138    RunnableSymbol,
139    /// Custom variable, provided by the plugin or other external source.
140    /// Will be printed with `ZED_` prefix to avoid potential conflicts with other variables.
141    Custom(Cow<'static, str>),
142}
143
144impl VariableName {
145    /// Generates a `$VARIABLE`-like string value to be used in templates.
146    /// Custom variables are wrapped in `${}` to avoid substitution issues with whitespaces.
147    pub fn template_value(&self) -> String {
148        if matches!(self, Self::Custom(_)) {
149            format!("${{{self}}}")
150        } else {
151            format!("${self}")
152        }
153    }
154}
155
156/// A prefix that all [`VariableName`] variants are prefixed with when used in environment variables and similar template contexts.
157pub const ZED_VARIABLE_NAME_PREFIX: &str = "ZED_";
158
159impl std::fmt::Display for VariableName {
160    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
161        match self {
162            Self::File => write!(f, "{ZED_VARIABLE_NAME_PREFIX}FILE"),
163            Self::WorktreeRoot => write!(f, "{ZED_VARIABLE_NAME_PREFIX}WORKTREE_ROOT"),
164            Self::Symbol => write!(f, "{ZED_VARIABLE_NAME_PREFIX}SYMBOL"),
165            Self::Row => write!(f, "{ZED_VARIABLE_NAME_PREFIX}ROW"),
166            Self::Column => write!(f, "{ZED_VARIABLE_NAME_PREFIX}COLUMN"),
167            Self::SelectedText => write!(f, "{ZED_VARIABLE_NAME_PREFIX}SELECTED_TEXT"),
168            Self::RunnableSymbol => write!(f, "{ZED_VARIABLE_NAME_PREFIX}RUNNABLE_SYMBOL"),
169            Self::Custom(s) => write!(f, "{ZED_VARIABLE_NAME_PREFIX}CUSTOM_{s}"),
170        }
171    }
172}
173
174/// Container for predefined environment variables that describe state of Zed at the time the task was spawned.
175#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
176pub struct TaskVariables(HashMap<VariableName, String>);
177
178impl TaskVariables {
179    /// Inserts another variable into the container, overwriting the existing one if it already exists — in this case, the old value is returned.
180    pub fn insert(&mut self, variable: VariableName, value: String) -> Option<String> {
181        self.0.insert(variable, value)
182    }
183
184    /// Extends the container with another one, overwriting the existing variables on collision.
185    pub fn extend(&mut self, other: Self) {
186        self.0.extend(other.0);
187    }
188}
189
190impl FromIterator<(VariableName, String)> for TaskVariables {
191    fn from_iter<T: IntoIterator<Item = (VariableName, String)>>(iter: T) -> Self {
192        Self(HashMap::from_iter(iter))
193    }
194}
195
196/// Keeps track of the file associated with a task and context of tasks execution (i.e. current file or current function).
197/// Keeps all Zed-related state inside, used to produce a resolved task out of its template.
198#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
199pub struct TaskContext {
200    /// A path to a directory in which the task should be executed.
201    pub cwd: Option<PathBuf>,
202    /// Additional environment variables associated with a given task.
203    pub task_variables: TaskVariables,
204}
205
206/// This is a new type representing a 'tag' on a 'runnable symbol', typically a test of main() function, found via treesitter.
207#[derive(Clone, Debug)]
208pub struct RunnableTag(pub SharedString);