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}
139
140impl FromStr for VariableName {
141 type Err = ();
142
143 fn from_str(s: &str) -> Result<Self, Self::Err> {
144 let without_prefix = s.strip_prefix(ZED_VARIABLE_NAME_PREFIX).ok_or(())?;
145 let value = match without_prefix {
146 "FILE" => Self::File,
147 "FILENAME" => Self::Filename,
148 "RELATIVE_FILE" => Self::RelativeFile,
149 "DIRNAME" => Self::Dirname,
150 "STEM" => Self::Stem,
151 "WORKTREE_ROOT" => Self::WorktreeRoot,
152 "SYMBOL" => Self::Symbol,
153 "RUNNABLE_SYMBOL" => Self::RunnableSymbol,
154 "SELECTED_TEXT" => Self::SelectedText,
155 "ROW" => Self::Row,
156 "COLUMN" => Self::Column,
157 _ => {
158 if let Some(custom_name) =
159 without_prefix.strip_prefix(ZED_CUSTOM_VARIABLE_NAME_PREFIX)
160 {
161 Self::Custom(Cow::Owned(custom_name.to_owned()))
162 } else {
163 return Err(());
164 }
165 }
166 };
167 Ok(value)
168 }
169}
170
171/// A prefix that all [`VariableName`] variants are prefixed with when used in environment variables and similar template contexts.
172pub const ZED_VARIABLE_NAME_PREFIX: &str = "ZED_";
173const ZED_CUSTOM_VARIABLE_NAME_PREFIX: &str = "CUSTOM_";
174
175impl std::fmt::Display for VariableName {
176 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
177 match self {
178 Self::File => write!(f, "{ZED_VARIABLE_NAME_PREFIX}FILE"),
179 Self::Filename => write!(f, "{ZED_VARIABLE_NAME_PREFIX}FILENAME"),
180 Self::RelativeFile => write!(f, "{ZED_VARIABLE_NAME_PREFIX}RELATIVE_FILE"),
181 Self::Dirname => write!(f, "{ZED_VARIABLE_NAME_PREFIX}DIRNAME"),
182 Self::Stem => write!(f, "{ZED_VARIABLE_NAME_PREFIX}STEM"),
183 Self::WorktreeRoot => write!(f, "{ZED_VARIABLE_NAME_PREFIX}WORKTREE_ROOT"),
184 Self::Symbol => write!(f, "{ZED_VARIABLE_NAME_PREFIX}SYMBOL"),
185 Self::Row => write!(f, "{ZED_VARIABLE_NAME_PREFIX}ROW"),
186 Self::Column => write!(f, "{ZED_VARIABLE_NAME_PREFIX}COLUMN"),
187 Self::SelectedText => write!(f, "{ZED_VARIABLE_NAME_PREFIX}SELECTED_TEXT"),
188 Self::RunnableSymbol => write!(f, "{ZED_VARIABLE_NAME_PREFIX}RUNNABLE_SYMBOL"),
189 Self::Custom(s) => write!(
190 f,
191 "{ZED_VARIABLE_NAME_PREFIX}{ZED_CUSTOM_VARIABLE_NAME_PREFIX}{s}"
192 ),
193 }
194 }
195}
196
197/// Container for predefined environment variables that describe state of Zed at the time the task was spawned.
198#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
199pub struct TaskVariables(HashMap<VariableName, String>);
200
201impl TaskVariables {
202 /// Inserts another variable into the container, overwriting the existing one if it already exists — in this case, the old value is returned.
203 pub fn insert(&mut self, variable: VariableName, value: String) -> Option<String> {
204 self.0.insert(variable, value)
205 }
206
207 /// Extends the container with another one, overwriting the existing variables on collision.
208 pub fn extend(&mut self, other: Self) {
209 self.0.extend(other.0);
210 }
211 /// Get the value associated with given variable name, if there is one.
212 pub fn get(&self, key: &VariableName) -> Option<&str> {
213 self.0.get(key).map(|s| s.as_str())
214 }
215 /// Clear out variables obtained from tree-sitter queries, which are prefixed with '_' character
216 pub fn sweep(&mut self) {
217 self.0.retain(|name, _| {
218 if let VariableName::Custom(name) = name {
219 !name.starts_with('_')
220 } else {
221 true
222 }
223 })
224 }
225}
226
227impl FromIterator<(VariableName, String)> for TaskVariables {
228 fn from_iter<T: IntoIterator<Item = (VariableName, String)>>(iter: T) -> Self {
229 Self(HashMap::from_iter(iter))
230 }
231}
232
233impl IntoIterator for TaskVariables {
234 type Item = (VariableName, String);
235
236 type IntoIter = hash_map::IntoIter<VariableName, String>;
237
238 fn into_iter(self) -> Self::IntoIter {
239 self.0.into_iter()
240 }
241}
242
243/// Keeps track of the file associated with a task and context of tasks execution (i.e. current file or current function).
244/// Keeps all Zed-related state inside, used to produce a resolved task out of its template.
245#[derive(Clone, Debug, Default, PartialEq, Eq)]
246pub struct TaskContext {
247 /// A path to a directory in which the task should be executed.
248 pub cwd: Option<PathBuf>,
249 /// Additional environment variables associated with a given task.
250 pub task_variables: TaskVariables,
251 /// Environment variables obtained when loading the project into Zed.
252 /// This is the environment one would get when `cd`ing in a terminal
253 /// into the project's root directory.
254 pub project_env: HashMap<String, String>,
255}
256
257/// This is a new type representing a 'tag' on a 'runnable symbol', typically a test of main() function, found via treesitter.
258#[derive(Clone, Debug)]
259pub struct RunnableTag(pub SharedString);
260
261/// Shell configuration to open the terminal with.
262#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
263#[serde(rename_all = "snake_case")]
264pub enum Shell {
265 /// Use the system's default terminal configuration in /etc/passwd
266 #[default]
267 System,
268 /// Use a specific program with no arguments.
269 Program(String),
270 /// Use a specific program with arguments.
271 WithArguments {
272 /// The program to run.
273 program: String,
274 /// The arguments to pass to the program.
275 args: Vec<String>,
276 /// An optional string to override the title of the terminal tab
277 title_override: Option<SharedString>,
278 },
279}