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;
  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    pub original_task: TaskTemplate,
 59    /// Full, unshortened label of the task after all resolutions are made.
 60    pub resolved_label: String,
 61    /// Further actions that need to take place after the resolved task is spawned,
 62    /// with all task variables resolved.
 63    pub resolved: Option<SpawnInTerminal>,
 64}
 65
 66/// Variables, available for use in [`TaskContext`] when a Zed's [`TaskTemplate`] gets resolved into a [`ResolvedTask`].
 67#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
 68pub enum VariableName {
 69    /// An absolute path of the currently opened file.
 70    File,
 71    /// An absolute path of the currently opened worktree, that contains the file.
 72    WorktreeRoot,
 73    /// A symbol text, that contains latest cursor/selection position.
 74    Symbol,
 75    /// A row with the latest cursor/selection position.
 76    Row,
 77    /// A column with the latest cursor/selection position.
 78    Column,
 79    /// Text from the latest selection.
 80    SelectedText,
 81    /// Custom variable, provided by the plugin or other external source.
 82    /// Will be printed with `ZED_` prefix to avoid potential conflicts with other variables.
 83    Custom(Cow<'static, str>),
 84}
 85
 86impl VariableName {
 87    /// Generates a `$VARIABLE`-like string value to be used in templates.
 88    /// Custom variables are wrapped in `${}` to avoid substitution issues with whitespaces.
 89    pub fn template_value(&self) -> String {
 90        if matches!(self, Self::Custom(_)) {
 91            format!("${{{self}}}")
 92        } else {
 93            format!("${self}")
 94        }
 95    }
 96}
 97
 98/// A prefix that all [`VariableName`] variants are prefixed with when used in environment variables and similar template contexts.
 99pub const ZED_VARIABLE_NAME_PREFIX: &str = "ZED_";
100
101impl std::fmt::Display for VariableName {
102    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
103        match self {
104            Self::File => write!(f, "{ZED_VARIABLE_NAME_PREFIX}FILE"),
105            Self::WorktreeRoot => write!(f, "{ZED_VARIABLE_NAME_PREFIX}WORKTREE_ROOT"),
106            Self::Symbol => write!(f, "{ZED_VARIABLE_NAME_PREFIX}SYMBOL"),
107            Self::Row => write!(f, "{ZED_VARIABLE_NAME_PREFIX}ROW"),
108            Self::Column => write!(f, "{ZED_VARIABLE_NAME_PREFIX}COLUMN"),
109            Self::SelectedText => write!(f, "{ZED_VARIABLE_NAME_PREFIX}SELECTED_TEXT"),
110            Self::Custom(s) => write!(f, "{ZED_VARIABLE_NAME_PREFIX}CUSTOM_{s}"),
111        }
112    }
113}
114
115/// Container for predefined environment variables that describe state of Zed at the time the task was spawned.
116#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
117pub struct TaskVariables(HashMap<VariableName, String>);
118
119impl TaskVariables {
120    /// Converts the container into a map of environment variables and their values.
121    fn into_env_variables(self) -> HashMap<String, String> {
122        self.0
123            .into_iter()
124            .map(|(name, value)| (name.to_string(), value))
125            .collect()
126    }
127
128    /// Inserts another variable into the container, overwriting the existing one if it already exists — in this case, the old value is returned.
129    pub fn insert(&mut self, variable: VariableName, value: String) -> Option<String> {
130        self.0.insert(variable, value)
131    }
132
133    /// Extends the container with another one, overwriting the existing variables on collision.
134    pub fn extend(&mut self, other: Self) {
135        self.0.extend(other.0);
136    }
137}
138
139impl FromIterator<(VariableName, String)> for TaskVariables {
140    fn from_iter<T: IntoIterator<Item = (VariableName, String)>>(iter: T) -> Self {
141        Self(HashMap::from_iter(iter))
142    }
143}
144
145/// Keeps track of the file associated with a task and context of tasks execution (i.e. current file or current function).
146/// Keeps all Zed-related state inside, used to produce a resolved task out of its template.
147#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
148pub struct TaskContext {
149    /// A path to a directory in which the task should be executed.
150    pub cwd: Option<PathBuf>,
151    /// Additional environment variables associated with a given task.
152    pub task_variables: TaskVariables,
153}
154
155/// [`Source`] produces tasks that can be scheduled.
156///
157/// Implementations of this trait could be e.g. [`StaticSource`] that parses tasks from a .json files and provides process templates to be spawned;
158/// another one could be a language server providing lenses with tests or build server listing all targets for a given project.
159pub trait TaskSource: Any {
160    /// A way to erase the type of the source, processing and storing them generically.
161    fn as_any(&mut self) -> &mut dyn Any;
162    /// Collects all tasks available for scheduling.
163    fn tasks_to_schedule(&mut self, cx: &mut ModelContext<Box<dyn TaskSource>>) -> TaskTemplates;
164}