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