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