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