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    /// Whether to show the task summary line in the task output (sucess/failure).
 55    pub show_summary: bool,
 56    /// Whether to show the command line in the task output.
 57    pub show_command: bool,
 58}
 59
 60/// A final form of the [`TaskTemplate`], that got resolved with a particualar [`TaskContext`] and now is ready to spawn the actual task.
 61#[derive(Clone, Debug, PartialEq, Eq)]
 62pub struct ResolvedTask {
 63    /// A way to distinguish tasks produced by the same template, but different contexts.
 64    /// NOTE: Resolved tasks may have the same labels, commands and do the same things,
 65    /// but still may have different ids if the context was different during the resolution.
 66    /// Since the template has `env` field, for a generic task that may be a bash command,
 67    /// so it's impossible to determine the id equality without more context in a generic case.
 68    pub id: TaskId,
 69    /// A template the task got resolved from.
 70    original_task: TaskTemplate,
 71    /// Full, unshortened label of the task after all resolutions are made.
 72    pub resolved_label: String,
 73    /// Variables that were substituted during the task template resolution.
 74    substituted_variables: HashSet<VariableName>,
 75    /// Further actions that need to take place after the resolved task is spawned,
 76    /// with all task variables resolved.
 77    pub resolved: Option<SpawnInTerminal>,
 78}
 79
 80impl ResolvedTask {
 81    /// A task template before the resolution.
 82    pub fn original_task(&self) -> &TaskTemplate {
 83        &self.original_task
 84    }
 85
 86    /// Variables that were substituted during the task template resolution.
 87    pub fn substituted_variables(&self) -> &HashSet<VariableName> {
 88        &self.substituted_variables
 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/// Name of the variable must be a valid shell variable identifier, which generally means that it is
102/// a word  consisting only  of alphanumeric characters and underscores,
103/// and beginning with an alphabetic character or an  underscore.
104#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
105pub enum VariableName {
106    /// An absolute path of the currently opened file.
107    File,
108    /// A path of the currently opened file (relative to worktree root).
109    RelativeFile,
110    /// The currently opened filename.
111    Filename,
112    /// The path to a parent directory of a currently opened file.
113    Dirname,
114    /// Stem (filename without extension) of the currently opened file.
115    Stem,
116    /// An absolute path of the currently opened worktree, that contains the file.
117    WorktreeRoot,
118    /// A symbol text, that contains latest cursor/selection position.
119    Symbol,
120    /// A row with the latest cursor/selection position.
121    Row,
122    /// A column with the latest cursor/selection position.
123    Column,
124    /// Text from the latest selection.
125    SelectedText,
126    /// The symbol selected by the symbol tagging system, specifically the @run capture in a runnables.scm
127    RunnableSymbol,
128    /// Custom variable, provided by the plugin or other external source.
129    /// Will be printed with `CUSTOM_` prefix to avoid potential conflicts with other variables.
130    Custom(Cow<'static, str>),
131}
132
133impl VariableName {
134    /// Generates a `$VARIABLE`-like string value to be used in templates.
135    pub fn template_value(&self) -> String {
136        format!("${self}")
137    }
138    /// Generates a `"$VARIABLE"`-like string, to be used instead of `Self::template_value` when expanded value could contain spaces or special characters.
139    pub fn template_value_with_whitespace(&self) -> String {
140        format!("\"${self}\"")
141    }
142}
143
144impl FromStr for VariableName {
145    type Err = ();
146
147    fn from_str(s: &str) -> Result<Self, Self::Err> {
148        let without_prefix = s.strip_prefix(ZED_VARIABLE_NAME_PREFIX).ok_or(())?;
149        let value = match without_prefix {
150            "FILE" => Self::File,
151            "FILENAME" => Self::Filename,
152            "RELATIVE_FILE" => Self::RelativeFile,
153            "DIRNAME" => Self::Dirname,
154            "STEM" => Self::Stem,
155            "WORKTREE_ROOT" => Self::WorktreeRoot,
156            "SYMBOL" => Self::Symbol,
157            "RUNNABLE_SYMBOL" => Self::RunnableSymbol,
158            "SELECTED_TEXT" => Self::SelectedText,
159            "ROW" => Self::Row,
160            "COLUMN" => Self::Column,
161            _ => {
162                if let Some(custom_name) =
163                    without_prefix.strip_prefix(ZED_CUSTOM_VARIABLE_NAME_PREFIX)
164                {
165                    Self::Custom(Cow::Owned(custom_name.to_owned()))
166                } else {
167                    return Err(());
168                }
169            }
170        };
171        Ok(value)
172    }
173}
174
175/// A prefix that all [`VariableName`] variants are prefixed with when used in environment variables and similar template contexts.
176pub const ZED_VARIABLE_NAME_PREFIX: &str = "ZED_";
177const ZED_CUSTOM_VARIABLE_NAME_PREFIX: &str = "CUSTOM_";
178
179impl std::fmt::Display for VariableName {
180    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
181        match self {
182            Self::File => write!(f, "{ZED_VARIABLE_NAME_PREFIX}FILE"),
183            Self::Filename => write!(f, "{ZED_VARIABLE_NAME_PREFIX}FILENAME"),
184            Self::RelativeFile => write!(f, "{ZED_VARIABLE_NAME_PREFIX}RELATIVE_FILE"),
185            Self::Dirname => write!(f, "{ZED_VARIABLE_NAME_PREFIX}DIRNAME"),
186            Self::Stem => write!(f, "{ZED_VARIABLE_NAME_PREFIX}STEM"),
187            Self::WorktreeRoot => write!(f, "{ZED_VARIABLE_NAME_PREFIX}WORKTREE_ROOT"),
188            Self::Symbol => write!(f, "{ZED_VARIABLE_NAME_PREFIX}SYMBOL"),
189            Self::Row => write!(f, "{ZED_VARIABLE_NAME_PREFIX}ROW"),
190            Self::Column => write!(f, "{ZED_VARIABLE_NAME_PREFIX}COLUMN"),
191            Self::SelectedText => write!(f, "{ZED_VARIABLE_NAME_PREFIX}SELECTED_TEXT"),
192            Self::RunnableSymbol => write!(f, "{ZED_VARIABLE_NAME_PREFIX}RUNNABLE_SYMBOL"),
193            Self::Custom(s) => write!(
194                f,
195                "{ZED_VARIABLE_NAME_PREFIX}{ZED_CUSTOM_VARIABLE_NAME_PREFIX}{s}"
196            ),
197        }
198    }
199}
200
201/// Container for predefined environment variables that describe state of Zed at the time the task was spawned.
202#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
203pub struct TaskVariables(HashMap<VariableName, String>);
204
205impl TaskVariables {
206    /// Inserts another variable into the container, overwriting the existing one if it already exists — in this case, the old value is returned.
207    pub fn insert(&mut self, variable: VariableName, value: String) -> Option<String> {
208        self.0.insert(variable, value)
209    }
210
211    /// Extends the container with another one, overwriting the existing variables on collision.
212    pub fn extend(&mut self, other: Self) {
213        self.0.extend(other.0);
214    }
215    /// Get the value associated with given variable name, if there is one.
216    pub fn get(&self, key: &VariableName) -> Option<&str> {
217        self.0.get(key).map(|s| s.as_str())
218    }
219    /// Clear out variables obtained from tree-sitter queries, which are prefixed with '_' character
220    pub fn sweep(&mut self) {
221        self.0.retain(|name, _| {
222            if let VariableName::Custom(name) = name {
223                !name.starts_with('_')
224            } else {
225                true
226            }
227        })
228    }
229}
230
231impl FromIterator<(VariableName, String)> for TaskVariables {
232    fn from_iter<T: IntoIterator<Item = (VariableName, String)>>(iter: T) -> Self {
233        Self(HashMap::from_iter(iter))
234    }
235}
236
237impl IntoIterator for TaskVariables {
238    type Item = (VariableName, String);
239
240    type IntoIter = hash_map::IntoIter<VariableName, String>;
241
242    fn into_iter(self) -> Self::IntoIter {
243        self.0.into_iter()
244    }
245}
246
247/// Keeps track of the file associated with a task and context of tasks execution (i.e. current file or current function).
248/// Keeps all Zed-related state inside, used to produce a resolved task out of its template.
249#[derive(Clone, Debug, Default, PartialEq, Eq)]
250pub struct TaskContext {
251    /// A path to a directory in which the task should be executed.
252    pub cwd: Option<PathBuf>,
253    /// Additional environment variables associated with a given task.
254    pub task_variables: TaskVariables,
255    /// Environment variables obtained when loading the project into Zed.
256    /// This is the environment one would get when `cd`ing in a terminal
257    /// into the project's root directory.
258    pub project_env: HashMap<String, String>,
259}
260
261/// This is a new type representing a 'tag' on a 'runnable symbol', typically a test of main() function, found via treesitter.
262#[derive(Clone, Debug)]
263pub struct RunnableTag(pub SharedString);
264
265/// Shell configuration to open the terminal with.
266#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
267#[serde(rename_all = "snake_case")]
268pub enum Shell {
269    /// Use the system's default terminal configuration in /etc/passwd
270    #[default]
271    System,
272    /// Use a specific program with no arguments.
273    Program(String),
274    /// Use a specific program with arguments.
275    WithArguments {
276        /// The program to run.
277        program: String,
278        /// The arguments to pass to the program.
279        args: Vec<String>,
280        /// An optional string to override the title of the terminal tab
281        title_override: Option<SharedString>,
282    },
283}