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::{hash_map, HashMap, HashSet};
  9use gpui::SharedString;
 10use schemars::JsonSchema;
 11use serde::{Deserialize, Serialize};
 12use std::borrow::Cow;
 13use std::path::PathBuf;
 14use std::str::FromStr;
 15
 16pub use task_template::{HideStrategy, RevealStrategy, TaskTemplate, TaskTemplates};
 17pub use vscode_format::VsCodeTaskFile;
 18
 19/// Task identifier, unique within the application.
 20/// Based on it, task reruns and terminal tabs are managed.
 21#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Deserialize)]
 22pub struct TaskId(pub String);
 23
 24/// Contains all information needed by Zed to spawn a new terminal tab for the given task.
 25#[derive(Debug, Clone, PartialEq, Eq)]
 26pub struct SpawnInTerminal {
 27    /// Id of the task to use when determining task tab affinity.
 28    pub id: TaskId,
 29    /// Full unshortened form of `label` field.
 30    pub full_label: String,
 31    /// Human readable name of the terminal tab.
 32    pub label: String,
 33    /// Executable command to spawn.
 34    pub command: String,
 35    /// Arguments to the command, potentially unsubstituted,
 36    /// to let the shell that spawns the command to do the substitution, if needed.
 37    pub args: Vec<String>,
 38    /// A human-readable label, containing command and all of its arguments, joined and substituted.
 39    pub command_label: String,
 40    /// Current working directory to spawn the command into.
 41    pub cwd: Option<PathBuf>,
 42    /// Env overrides for the command, will be appended to the terminal's environment from the settings.
 43    pub env: HashMap<String, String>,
 44    /// Whether to use a new terminal tab or reuse the existing one to spawn the process.
 45    pub use_new_terminal: bool,
 46    /// Whether to allow multiple instances of the same task to be run, or rather wait for the existing ones to finish.
 47    pub allow_concurrent_runs: bool,
 48    /// What to do with the terminal pane and tab, after the command was started.
 49    pub reveal: RevealStrategy,
 50    /// What to do with the terminal pane and tab, after the command had finished.
 51    pub hide: HideStrategy,
 52    /// Which shell to use when spawning the task.
 53    pub shell: Shell,
 54}
 55
 56/// A final form of the [`TaskTemplate`], that got resolved with a particualar [`TaskContext`] and now is ready to spawn the actual task.
 57#[derive(Clone, Debug, PartialEq, Eq)]
 58pub struct ResolvedTask {
 59    /// A way to distinguish tasks produced by the same template, but different contexts.
 60    /// NOTE: Resolved tasks may have the same labels, commands and do the same things,
 61    /// but still may have different ids if the context was different during the resolution.
 62    /// Since the template has `env` field, for a generic task that may be a bash command,
 63    /// so it's impossible to determine the id equality without more context in a generic case.
 64    pub id: TaskId,
 65    /// A template the task got resolved from.
 66    original_task: TaskTemplate,
 67    /// Full, unshortened label of the task after all resolutions are made.
 68    pub resolved_label: String,
 69    /// Variables that were substituted during the task template resolution.
 70    substituted_variables: HashSet<VariableName>,
 71    /// Further actions that need to take place after the resolved task is spawned,
 72    /// with all task variables resolved.
 73    pub resolved: Option<SpawnInTerminal>,
 74}
 75
 76impl ResolvedTask {
 77    /// A task template before the resolution.
 78    pub fn original_task(&self) -> &TaskTemplate {
 79        &self.original_task
 80    }
 81
 82    /// Variables that were substituted during the task template resolution.
 83    pub fn substituted_variables(&self) -> &HashSet<VariableName> {
 84        &self.substituted_variables
 85    }
 86
 87    /// A human-readable label to display in the UI.
 88    pub fn display_label(&self) -> &str {
 89        self.resolved
 90            .as_ref()
 91            .map(|resolved| resolved.label.as_str())
 92            .unwrap_or_else(|| self.resolved_label.as_str())
 93    }
 94}
 95
 96/// Variables, available for use in [`TaskContext`] when a Zed's [`TaskTemplate`] gets resolved into a [`ResolvedTask`].
 97/// Name of the variable must be a valid shell variable identifier, which generally means that it is
 98/// a word  consisting only  of alphanumeric characters and underscores,
 99/// and beginning with an alphabetic character or an  underscore.
100#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
101pub enum VariableName {
102    /// An absolute path of the currently opened file.
103    File,
104    /// A path of the currently opened file (relative to worktree root).
105    RelativeFile,
106    /// The currently opened filename.
107    Filename,
108    /// The path to a parent directory of a currently opened file.
109    Dirname,
110    /// Stem (filename without extension) of the currently opened file.
111    Stem,
112    /// An absolute path of the currently opened worktree, that contains the file.
113    WorktreeRoot,
114    /// A symbol text, that contains latest cursor/selection position.
115    Symbol,
116    /// A row with the latest cursor/selection position.
117    Row,
118    /// A column with the latest cursor/selection position.
119    Column,
120    /// Text from the latest selection.
121    SelectedText,
122    /// The symbol selected by the symbol tagging system, specifically the @run capture in a runnables.scm
123    RunnableSymbol,
124    /// Custom variable, provided by the plugin or other external source.
125    /// Will be printed with `CUSTOM_` prefix to avoid potential conflicts with other variables.
126    Custom(Cow<'static, str>),
127}
128
129impl VariableName {
130    /// Generates a `$VARIABLE`-like string value to be used in templates.
131    pub fn template_value(&self) -> String {
132        format!("${self}")
133    }
134}
135
136impl FromStr for VariableName {
137    type Err = ();
138
139    fn from_str(s: &str) -> Result<Self, Self::Err> {
140        let without_prefix = s.strip_prefix(ZED_VARIABLE_NAME_PREFIX).ok_or(())?;
141        let value = match without_prefix {
142            "FILE" => Self::File,
143            "FILENAME" => Self::Filename,
144            "RELATIVE_FILE" => Self::RelativeFile,
145            "DIRNAME" => Self::Dirname,
146            "STEM" => Self::Stem,
147            "WORKTREE_ROOT" => Self::WorktreeRoot,
148            "SYMBOL" => Self::Symbol,
149            "RUNNABLE_SYMBOL" => Self::RunnableSymbol,
150            "SELECTED_TEXT" => Self::SelectedText,
151            "ROW" => Self::Row,
152            "COLUMN" => Self::Column,
153            _ => {
154                if let Some(custom_name) =
155                    without_prefix.strip_prefix(ZED_CUSTOM_VARIABLE_NAME_PREFIX)
156                {
157                    Self::Custom(Cow::Owned(custom_name.to_owned()))
158                } else {
159                    return Err(());
160                }
161            }
162        };
163        Ok(value)
164    }
165}
166
167/// A prefix that all [`VariableName`] variants are prefixed with when used in environment variables and similar template contexts.
168pub const ZED_VARIABLE_NAME_PREFIX: &str = "ZED_";
169const ZED_CUSTOM_VARIABLE_NAME_PREFIX: &str = "CUSTOM_";
170
171impl std::fmt::Display for VariableName {
172    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
173        match self {
174            Self::File => write!(f, "{ZED_VARIABLE_NAME_PREFIX}FILE"),
175            Self::Filename => write!(f, "{ZED_VARIABLE_NAME_PREFIX}FILENAME"),
176            Self::RelativeFile => write!(f, "{ZED_VARIABLE_NAME_PREFIX}RELATIVE_FILE"),
177            Self::Dirname => write!(f, "{ZED_VARIABLE_NAME_PREFIX}DIRNAME"),
178            Self::Stem => write!(f, "{ZED_VARIABLE_NAME_PREFIX}STEM"),
179            Self::WorktreeRoot => write!(f, "{ZED_VARIABLE_NAME_PREFIX}WORKTREE_ROOT"),
180            Self::Symbol => write!(f, "{ZED_VARIABLE_NAME_PREFIX}SYMBOL"),
181            Self::Row => write!(f, "{ZED_VARIABLE_NAME_PREFIX}ROW"),
182            Self::Column => write!(f, "{ZED_VARIABLE_NAME_PREFIX}COLUMN"),
183            Self::SelectedText => write!(f, "{ZED_VARIABLE_NAME_PREFIX}SELECTED_TEXT"),
184            Self::RunnableSymbol => write!(f, "{ZED_VARIABLE_NAME_PREFIX}RUNNABLE_SYMBOL"),
185            Self::Custom(s) => write!(
186                f,
187                "{ZED_VARIABLE_NAME_PREFIX}{ZED_CUSTOM_VARIABLE_NAME_PREFIX}{s}"
188            ),
189        }
190    }
191}
192
193/// Container for predefined environment variables that describe state of Zed at the time the task was spawned.
194#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
195pub struct TaskVariables(HashMap<VariableName, String>);
196
197impl TaskVariables {
198    /// Inserts another variable into the container, overwriting the existing one if it already exists — in this case, the old value is returned.
199    pub fn insert(&mut self, variable: VariableName, value: String) -> Option<String> {
200        self.0.insert(variable, value)
201    }
202
203    /// Extends the container with another one, overwriting the existing variables on collision.
204    pub fn extend(&mut self, other: Self) {
205        self.0.extend(other.0);
206    }
207    /// Get the value associated with given variable name, if there is one.
208    pub fn get(&self, key: &VariableName) -> Option<&str> {
209        self.0.get(key).map(|s| s.as_str())
210    }
211    /// Clear out variables obtained from tree-sitter queries, which are prefixed with '_' character
212    pub fn sweep(&mut self) {
213        self.0.retain(|name, _| {
214            if let VariableName::Custom(name) = name {
215                !name.starts_with('_')
216            } else {
217                true
218            }
219        })
220    }
221}
222
223impl FromIterator<(VariableName, String)> for TaskVariables {
224    fn from_iter<T: IntoIterator<Item = (VariableName, String)>>(iter: T) -> Self {
225        Self(HashMap::from_iter(iter))
226    }
227}
228
229impl IntoIterator for TaskVariables {
230    type Item = (VariableName, String);
231
232    type IntoIter = hash_map::IntoIter<VariableName, String>;
233
234    fn into_iter(self) -> Self::IntoIter {
235        self.0.into_iter()
236    }
237}
238
239/// Keeps track of the file associated with a task and context of tasks execution (i.e. current file or current function).
240/// Keeps all Zed-related state inside, used to produce a resolved task out of its template.
241#[derive(Clone, Debug, Default, PartialEq, Eq)]
242pub struct TaskContext {
243    /// A path to a directory in which the task should be executed.
244    pub cwd: Option<PathBuf>,
245    /// Additional environment variables associated with a given task.
246    pub task_variables: TaskVariables,
247    /// Environment variables obtained when loading the project into Zed.
248    /// This is the environment one would get when `cd`ing in a terminal
249    /// into the project's root directory.
250    pub project_env: HashMap<String, String>,
251}
252
253/// This is a new type representing a 'tag' on a 'runnable symbol', typically a test of main() function, found via treesitter.
254#[derive(Clone, Debug)]
255pub struct RunnableTag(pub SharedString);
256
257/// Shell configuration to open the terminal with.
258#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
259#[serde(rename_all = "snake_case")]
260pub enum Shell {
261    /// Use the system's default terminal configuration in /etc/passwd
262    #[default]
263    System,
264    /// Use a specific program with no arguments.
265    Program(String),
266    /// Use a specific program with arguments.
267    WithArguments {
268        /// The program to run.
269        program: String,
270        /// The arguments to pass to the program.
271        args: Vec<String>,
272        /// An optional string to override the title of the terminal tab
273        title_override: Option<SharedString>,
274    },
275}