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