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