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    /// If the resolution produced a task with the command, returns a string, combined from its command and arguments.
 80    pub fn resolved_command(&self) -> Option<String> {
 81        self.resolved.as_ref().map(|resolved| {
 82            let mut command = resolved.command.clone();
 83            for arg in &resolved.args {
 84                command.push(' ');
 85                command.push_str(arg);
 86            }
 87            command
 88        })
 89    }
 90
 91    /// A human-readable label to display in the UI.
 92    pub fn display_label(&self) -> &str {
 93        self.resolved
 94            .as_ref()
 95            .map(|resolved| resolved.label.as_str())
 96            .unwrap_or_else(|| self.resolved_label.as_str())
 97    }
 98}
 99
100/// Variables, available for use in [`TaskContext`] when a Zed's [`TaskTemplate`] gets resolved into a [`ResolvedTask`].
101#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
102pub enum VariableName {
103    /// An absolute path of the currently opened file.
104    File,
105    /// An absolute path of the currently opened worktree, that contains the file.
106    WorktreeRoot,
107    /// A symbol text, that contains latest cursor/selection position.
108    Symbol,
109    /// A row with the latest cursor/selection position.
110    Row,
111    /// A column with the latest cursor/selection position.
112    Column,
113    /// Text from the latest selection.
114    SelectedText,
115    /// Custom variable, provided by the plugin or other external source.
116    /// Will be printed with `ZED_` prefix to avoid potential conflicts with other variables.
117    Custom(Cow<'static, str>),
118}
119
120impl VariableName {
121    /// Generates a `$VARIABLE`-like string value to be used in templates.
122    /// Custom variables are wrapped in `${}` to avoid substitution issues with whitespaces.
123    pub fn template_value(&self) -> String {
124        if matches!(self, Self::Custom(_)) {
125            format!("${{{self}}}")
126        } else {
127            format!("${self}")
128        }
129    }
130}
131
132/// A prefix that all [`VariableName`] variants are prefixed with when used in environment variables and similar template contexts.
133pub const ZED_VARIABLE_NAME_PREFIX: &str = "ZED_";
134
135impl std::fmt::Display for VariableName {
136    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
137        match self {
138            Self::File => write!(f, "{ZED_VARIABLE_NAME_PREFIX}FILE"),
139            Self::WorktreeRoot => write!(f, "{ZED_VARIABLE_NAME_PREFIX}WORKTREE_ROOT"),
140            Self::Symbol => write!(f, "{ZED_VARIABLE_NAME_PREFIX}SYMBOL"),
141            Self::Row => write!(f, "{ZED_VARIABLE_NAME_PREFIX}ROW"),
142            Self::Column => write!(f, "{ZED_VARIABLE_NAME_PREFIX}COLUMN"),
143            Self::SelectedText => write!(f, "{ZED_VARIABLE_NAME_PREFIX}SELECTED_TEXT"),
144            Self::Custom(s) => write!(f, "{ZED_VARIABLE_NAME_PREFIX}CUSTOM_{s}"),
145        }
146    }
147}
148
149/// Container for predefined environment variables that describe state of Zed at the time the task was spawned.
150#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
151pub struct TaskVariables(HashMap<VariableName, String>);
152
153impl TaskVariables {
154    /// Inserts another variable into the container, overwriting the existing one if it already exists — in this case, the old value is returned.
155    pub fn insert(&mut self, variable: VariableName, value: String) -> Option<String> {
156        self.0.insert(variable, value)
157    }
158
159    /// Extends the container with another one, overwriting the existing variables on collision.
160    pub fn extend(&mut self, other: Self) {
161        self.0.extend(other.0);
162    }
163}
164
165impl FromIterator<(VariableName, String)> for TaskVariables {
166    fn from_iter<T: IntoIterator<Item = (VariableName, String)>>(iter: T) -> Self {
167        Self(HashMap::from_iter(iter))
168    }
169}
170
171/// Keeps track of the file associated with a task and context of tasks execution (i.e. current file or current function).
172/// Keeps all Zed-related state inside, used to produce a resolved task out of its template.
173#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
174pub struct TaskContext {
175    /// A path to a directory in which the task should be executed.
176    pub cwd: Option<PathBuf>,
177    /// Additional environment variables associated with a given task.
178    pub task_variables: TaskVariables,
179}
180
181/// [`Source`] produces tasks that can be scheduled.
182///
183/// Implementations of this trait could be e.g. [`StaticSource`] that parses tasks from a .json files and provides process templates to be spawned;
184/// another one could be a language server providing lenses with tests or build server listing all targets for a given project.
185pub trait TaskSource: Any {
186    /// A way to erase the type of the source, processing and storing them generically.
187    fn as_any(&mut self) -> &mut dyn Any;
188    /// Collects all tasks available for scheduling.
189    fn tasks_to_schedule(&mut self, cx: &mut ModelContext<Box<dyn TaskSource>>) -> TaskTemplates;
190}