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            "WORKTREE_ROOT" => Self::WorktreeRoot,
144            "SYMBOL" => Self::Symbol,
145            "SELECTED_TEXT" => Self::SelectedText,
146            "ROW" => Self::Row,
147            "COLUMN" => Self::Column,
148            _ => {
149                if let Some(custom_name) =
150                    without_prefix.strip_prefix(ZED_CUSTOM_VARIABLE_NAME_PREFIX)
151                {
152                    Self::Custom(Cow::Owned(custom_name.to_owned()))
153                } else {
154                    return Err(());
155                }
156            }
157        };
158        Ok(value)
159    }
160}
161
162/// A prefix that all [`VariableName`] variants are prefixed with when used in environment variables and similar template contexts.
163pub const ZED_VARIABLE_NAME_PREFIX: &str = "ZED_";
164const ZED_CUSTOM_VARIABLE_NAME_PREFIX: &str = "CUSTOM_";
165
166impl std::fmt::Display for VariableName {
167    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
168        match self {
169            Self::File => write!(f, "{ZED_VARIABLE_NAME_PREFIX}FILE"),
170            Self::Filename => write!(f, "{ZED_VARIABLE_NAME_PREFIX}FILENAME"),
171            Self::RelativeFile => write!(f, "{ZED_VARIABLE_NAME_PREFIX}RELATIVE_FILE"),
172            Self::Dirname => write!(f, "{ZED_VARIABLE_NAME_PREFIX}DIRNAME"),
173            Self::Stem => write!(f, "{ZED_VARIABLE_NAME_PREFIX}STEM"),
174            Self::WorktreeRoot => write!(f, "{ZED_VARIABLE_NAME_PREFIX}WORKTREE_ROOT"),
175            Self::Symbol => write!(f, "{ZED_VARIABLE_NAME_PREFIX}SYMBOL"),
176            Self::Row => write!(f, "{ZED_VARIABLE_NAME_PREFIX}ROW"),
177            Self::Column => write!(f, "{ZED_VARIABLE_NAME_PREFIX}COLUMN"),
178            Self::SelectedText => write!(f, "{ZED_VARIABLE_NAME_PREFIX}SELECTED_TEXT"),
179            Self::RunnableSymbol => write!(f, "{ZED_VARIABLE_NAME_PREFIX}RUNNABLE_SYMBOL"),
180            Self::Custom(s) => write!(
181                f,
182                "{ZED_VARIABLE_NAME_PREFIX}{ZED_CUSTOM_VARIABLE_NAME_PREFIX}{s}"
183            ),
184        }
185    }
186}
187
188/// Container for predefined environment variables that describe state of Zed at the time the task was spawned.
189#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
190pub struct TaskVariables(HashMap<VariableName, String>);
191
192impl TaskVariables {
193    /// Inserts another variable into the container, overwriting the existing one if it already exists — in this case, the old value is returned.
194    pub fn insert(&mut self, variable: VariableName, value: String) -> Option<String> {
195        self.0.insert(variable, value)
196    }
197
198    /// Extends the container with another one, overwriting the existing variables on collision.
199    pub fn extend(&mut self, other: Self) {
200        self.0.extend(other.0);
201    }
202    /// Get the value associated with given variable name, if there is one.
203    pub fn get(&self, key: &VariableName) -> Option<&str> {
204        self.0.get(key).map(|s| s.as_str())
205    }
206    /// Clear out variables obtained from tree-sitter queries, which are prefixed with '_' character
207    pub fn sweep(&mut self) {
208        self.0.retain(|name, _| {
209            if let VariableName::Custom(name) = name {
210                !name.starts_with('_')
211            } else {
212                true
213            }
214        })
215    }
216}
217
218impl FromIterator<(VariableName, String)> for TaskVariables {
219    fn from_iter<T: IntoIterator<Item = (VariableName, String)>>(iter: T) -> Self {
220        Self(HashMap::from_iter(iter))
221    }
222}
223
224impl IntoIterator for TaskVariables {
225    type Item = (VariableName, String);
226
227    type IntoIter = hash_map::IntoIter<VariableName, String>;
228
229    fn into_iter(self) -> Self::IntoIter {
230        self.0.into_iter()
231    }
232}
233
234/// Keeps track of the file associated with a task and context of tasks execution (i.e. current file or current function).
235/// Keeps all Zed-related state inside, used to produce a resolved task out of its template.
236#[derive(Clone, Debug, Default, PartialEq, Eq)]
237pub struct TaskContext {
238    /// A path to a directory in which the task should be executed.
239    pub cwd: Option<PathBuf>,
240    /// Additional environment variables associated with a given task.
241    pub task_variables: TaskVariables,
242    /// Environment variables obtained when loading the project into Zed.
243    /// This is the environment one would get when `cd`ing in a terminal
244    /// into the project's root directory.
245    pub project_env: HashMap<String, String>,
246}
247
248/// This is a new type representing a 'tag' on a 'runnable symbol', typically a test of main() function, found via treesitter.
249#[derive(Clone, Debug)]
250pub struct RunnableTag(pub SharedString);
251
252/// Shell configuration to open the terminal with.
253#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
254#[serde(rename_all = "snake_case")]
255pub enum Shell {
256    /// Use the system's default terminal configuration in /etc/passwd
257    #[default]
258    System,
259    /// Use a specific program with no arguments.
260    Program(String),
261    /// Use a specific program with arguments.
262    WithArguments {
263        /// The program to run.
264        program: String,
265        /// The arguments to pass to the program.
266        args: Vec<String>,
267    },
268}