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/// Contains all information needed by Zed to spawn a new terminal tab for the given task.
 23#[derive(Debug, Clone, PartialEq, Eq)]
 24pub struct SpawnInTerminal {
 25    /// Id of the task to use when determining task tab affinity.
 26    pub id: TaskId,
 27    /// Full unshortened form of `label` field.
 28    pub full_label: String,
 29    /// Human readable name of the terminal tab.
 30    pub label: String,
 31    /// Executable command to spawn.
 32    pub command: String,
 33    /// Arguments to the command, potentially unsubstituted,
 34    /// to let the shell that spawns the command to do the substitution, if needed.
 35    pub args: Vec<String>,
 36    /// A human-readable label, containing command and all of its arguments, joined and substituted.
 37    pub command_label: String,
 38    /// Current working directory to spawn the command into.
 39    pub cwd: Option<PathBuf>,
 40    /// Env overrides for the command, will be appended to the terminal's environment from the settings.
 41    pub env: HashMap<String, String>,
 42    /// Whether to use a new terminal tab or reuse the existing one to spawn the process.
 43    pub use_new_terminal: bool,
 44    /// Whether to allow multiple instances of the same task to be run, or rather wait for the existing ones to finish.
 45    pub allow_concurrent_runs: bool,
 46    /// What to do with the terminal pane and tab, after the command was started.
 47    pub reveal: RevealStrategy,
 48}
 49
 50/// A final form of the [`TaskTemplate`], that got resolved with a particualar [`TaskContext`] and now is ready to spawn the actual task.
 51#[derive(Clone, Debug, PartialEq, Eq)]
 52pub struct ResolvedTask {
 53    /// A way to distinguish tasks produced by the same template, but different contexts.
 54    /// NOTE: Resolved tasks may have the same labels, commands and do the same things,
 55    /// but still may have different ids if the context was different during the resolution.
 56    /// Since the template has `env` field, for a generic task that may be a bash command,
 57    /// so it's impossible to determine the id equality without more context in a generic case.
 58    pub id: TaskId,
 59    /// A template the task got resolved from.
 60    original_task: TaskTemplate,
 61    /// Full, unshortened label of the task after all resolutions are made.
 62    pub resolved_label: String,
 63    /// Variables that were substituted during the task template resolution.
 64    substituted_variables: HashSet<VariableName>,
 65    /// Further actions that need to take place after the resolved task is spawned,
 66    /// with all task variables resolved.
 67    pub resolved: Option<SpawnInTerminal>,
 68}
 69
 70impl ResolvedTask {
 71    /// A task template before the resolution.
 72    pub fn original_task(&self) -> &TaskTemplate {
 73        &self.original_task
 74    }
 75
 76    /// Variables that were substituted during the task template resolution.
 77    pub fn substituted_variables(&self) -> &HashSet<VariableName> {
 78        &self.substituted_variables
 79    }
 80
 81    /// A human-readable label to display in the UI.
 82    pub fn display_label(&self) -> &str {
 83        self.resolved
 84            .as_ref()
 85            .map(|resolved| resolved.label.as_str())
 86            .unwrap_or_else(|| self.resolved_label.as_str())
 87    }
 88}
 89
 90/// Variables, available for use in [`TaskContext`] when a Zed's [`TaskTemplate`] gets resolved into a [`ResolvedTask`].
 91#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
 92pub enum VariableName {
 93    /// An absolute path of the currently opened file.
 94    File,
 95    /// An absolute path of the currently opened worktree, that contains the file.
 96    WorktreeRoot,
 97    /// A symbol text, that contains latest cursor/selection position.
 98    Symbol,
 99    /// A row with the latest cursor/selection position.
100    Row,
101    /// A column with the latest cursor/selection position.
102    Column,
103    /// Text from the latest selection.
104    SelectedText,
105    /// The symbol selected by the symbol tagging system, specifically the @run capture in a runnables.scm
106    RunnableSymbol,
107    /// Custom variable, provided by the plugin or other external source.
108    /// Will be printed with `ZED_` prefix to avoid potential conflicts with other variables.
109    Custom(Cow<'static, str>),
110}
111
112impl VariableName {
113    /// Generates a `$VARIABLE`-like string value to be used in templates.
114    /// Custom variables are wrapped in `${}` to avoid substitution issues with whitespaces.
115    pub fn template_value(&self) -> String {
116        if matches!(self, Self::Custom(_)) {
117            format!("${{{self}}}")
118        } else {
119            format!("${self}")
120        }
121    }
122}
123
124/// A prefix that all [`VariableName`] variants are prefixed with when used in environment variables and similar template contexts.
125pub const ZED_VARIABLE_NAME_PREFIX: &str = "ZED_";
126
127impl std::fmt::Display for VariableName {
128    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
129        match self {
130            Self::File => write!(f, "{ZED_VARIABLE_NAME_PREFIX}FILE"),
131            Self::WorktreeRoot => write!(f, "{ZED_VARIABLE_NAME_PREFIX}WORKTREE_ROOT"),
132            Self::Symbol => write!(f, "{ZED_VARIABLE_NAME_PREFIX}SYMBOL"),
133            Self::Row => write!(f, "{ZED_VARIABLE_NAME_PREFIX}ROW"),
134            Self::Column => write!(f, "{ZED_VARIABLE_NAME_PREFIX}COLUMN"),
135            Self::SelectedText => write!(f, "{ZED_VARIABLE_NAME_PREFIX}SELECTED_TEXT"),
136            Self::RunnableSymbol => write!(f, "{ZED_VARIABLE_NAME_PREFIX}RUNNABLE_SYMBOL"),
137            Self::Custom(s) => write!(f, "{ZED_VARIABLE_NAME_PREFIX}CUSTOM_{s}"),
138        }
139    }
140}
141
142/// Container for predefined environment variables that describe state of Zed at the time the task was spawned.
143#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
144pub struct TaskVariables(HashMap<VariableName, String>);
145
146impl TaskVariables {
147    /// Inserts another variable into the container, overwriting the existing one if it already exists — in this case, the old value is returned.
148    pub fn insert(&mut self, variable: VariableName, value: String) -> Option<String> {
149        self.0.insert(variable, value)
150    }
151
152    /// Extends the container with another one, overwriting the existing variables on collision.
153    pub fn extend(&mut self, other: Self) {
154        self.0.extend(other.0);
155    }
156}
157
158impl FromIterator<(VariableName, String)> for TaskVariables {
159    fn from_iter<T: IntoIterator<Item = (VariableName, String)>>(iter: T) -> Self {
160        Self(HashMap::from_iter(iter))
161    }
162}
163
164/// Keeps track of the file associated with a task and context of tasks execution (i.e. current file or current function).
165/// Keeps all Zed-related state inside, used to produce a resolved task out of its template.
166#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
167pub struct TaskContext {
168    /// A path to a directory in which the task should be executed.
169    pub cwd: Option<PathBuf>,
170    /// Additional environment variables associated with a given task.
171    pub task_variables: TaskVariables,
172}
173
174/// This is a new type representing a 'tag' on a 'runnable symbol', typically a test of main() function, found via treesitter.
175#[derive(Clone, Debug)]
176pub struct RunnableTag(pub SharedString);