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