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::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)]
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#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
125pub enum VariableName {
126 /// An absolute path of the currently opened file.
127 File,
128 /// A path of the currently opened file (relative to worktree root).
129 RelativeFile,
130 /// The currently opened filename.
131 Filename,
132 /// The path to a parent directory of a currently opened file.
133 Dirname,
134 /// Stem (filename without extension) of the currently opened file.
135 Stem,
136 /// An absolute path of the currently opened worktree, that contains the file.
137 WorktreeRoot,
138 /// A symbol text, that contains latest cursor/selection position.
139 Symbol,
140 /// A row with the latest cursor/selection position.
141 Row,
142 /// A column with the latest cursor/selection position.
143 Column,
144 /// Text from the latest selection.
145 SelectedText,
146 /// The symbol selected by the symbol tagging system, specifically the @run capture in a runnables.scm
147 RunnableSymbol,
148 /// Custom variable, provided by the plugin or other external source.
149 /// Will be printed with `ZED_` prefix to avoid potential conflicts with other variables.
150 Custom(Cow<'static, str>),
151}
152
153impl VariableName {
154 /// Generates a `$VARIABLE`-like string value to be used in templates.
155 /// Custom variables are wrapped in `${}` to avoid substitution issues with whitespaces.
156 pub fn template_value(&self) -> String {
157 if matches!(self, Self::Custom(_)) {
158 format!("${{{self}}}")
159 } else {
160 format!("${self}")
161 }
162 }
163}
164
165impl FromStr for VariableName {
166 type Err = ();
167
168 fn from_str(s: &str) -> Result<Self, Self::Err> {
169 let without_prefix = s.strip_prefix(ZED_VARIABLE_NAME_PREFIX).ok_or(())?;
170 let value = match without_prefix {
171 "FILE" => Self::File,
172 "WORKTREE_ROOT" => Self::WorktreeRoot,
173 "SYMBOL" => Self::Symbol,
174 "SELECTED_TEXT" => Self::SelectedText,
175 "ROW" => Self::Row,
176 "COLUMN" => Self::Column,
177 _ => {
178 if let Some(custom_name) =
179 without_prefix.strip_prefix(ZED_CUSTOM_VARIABLE_NAME_PREFIX)
180 {
181 Self::Custom(Cow::Owned(custom_name.to_owned()))
182 } else {
183 return Err(());
184 }
185 }
186 };
187 Ok(value)
188 }
189}
190
191/// A prefix that all [`VariableName`] variants are prefixed with when used in environment variables and similar template contexts.
192pub const ZED_VARIABLE_NAME_PREFIX: &str = "ZED_";
193const ZED_CUSTOM_VARIABLE_NAME_PREFIX: &str = "CUSTOM_";
194
195impl std::fmt::Display for VariableName {
196 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
197 match self {
198 Self::File => write!(f, "{ZED_VARIABLE_NAME_PREFIX}FILE"),
199 Self::Filename => write!(f, "{ZED_VARIABLE_NAME_PREFIX}FILENAME"),
200 Self::RelativeFile => write!(f, "{ZED_VARIABLE_NAME_PREFIX}RELATIVE_FILE"),
201 Self::Dirname => write!(f, "{ZED_VARIABLE_NAME_PREFIX}DIRNAME"),
202 Self::Stem => write!(f, "{ZED_VARIABLE_NAME_PREFIX}STEM"),
203 Self::WorktreeRoot => write!(f, "{ZED_VARIABLE_NAME_PREFIX}WORKTREE_ROOT"),
204 Self::Symbol => write!(f, "{ZED_VARIABLE_NAME_PREFIX}SYMBOL"),
205 Self::Row => write!(f, "{ZED_VARIABLE_NAME_PREFIX}ROW"),
206 Self::Column => write!(f, "{ZED_VARIABLE_NAME_PREFIX}COLUMN"),
207 Self::SelectedText => write!(f, "{ZED_VARIABLE_NAME_PREFIX}SELECTED_TEXT"),
208 Self::RunnableSymbol => write!(f, "{ZED_VARIABLE_NAME_PREFIX}RUNNABLE_SYMBOL"),
209 Self::Custom(s) => write!(
210 f,
211 "{ZED_VARIABLE_NAME_PREFIX}{ZED_CUSTOM_VARIABLE_NAME_PREFIX}{s}"
212 ),
213 }
214 }
215}
216
217/// Container for predefined environment variables that describe state of Zed at the time the task was spawned.
218#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
219pub struct TaskVariables(HashMap<VariableName, String>);
220
221impl TaskVariables {
222 /// Inserts another variable into the container, overwriting the existing one if it already exists — in this case, the old value is returned.
223 pub fn insert(&mut self, variable: VariableName, value: String) -> Option<String> {
224 self.0.insert(variable, value)
225 }
226
227 /// Extends the container with another one, overwriting the existing variables on collision.
228 pub fn extend(&mut self, other: Self) {
229 self.0.extend(other.0);
230 }
231 /// Get the value associated with given variable name, if there is one.
232 pub fn get(&self, key: &VariableName) -> Option<&str> {
233 self.0.get(key).map(|s| s.as_str())
234 }
235 /// Clear out variables obtained from tree-sitter queries, which are prefixed with '_' character
236 pub fn sweep(&mut self) {
237 self.0.retain(|name, _| {
238 if let VariableName::Custom(name) = name {
239 !name.starts_with('_')
240 } else {
241 true
242 }
243 })
244 }
245}
246
247impl FromIterator<(VariableName, String)> for TaskVariables {
248 fn from_iter<T: IntoIterator<Item = (VariableName, String)>>(iter: T) -> Self {
249 Self(HashMap::from_iter(iter))
250 }
251}
252
253impl IntoIterator for TaskVariables {
254 type Item = (VariableName, String);
255
256 type IntoIter = hash_map::IntoIter<VariableName, String>;
257
258 fn into_iter(self) -> Self::IntoIter {
259 self.0.into_iter()
260 }
261}
262
263/// Keeps track of the file associated with a task and context of tasks execution (i.e. current file or current function).
264/// Keeps all Zed-related state inside, used to produce a resolved task out of its template.
265#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
266pub struct TaskContext {
267 /// A path to a directory in which the task should be executed.
268 pub cwd: Option<PathBuf>,
269 /// Additional environment variables associated with a given task.
270 pub task_variables: TaskVariables,
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);