task.rs

  1//! Baseline interface of Tasks in Zed: all tasks in Zed are intended to use those for implementing their own logic.
  2
  3mod debug_format;
  4mod serde_helpers;
  5mod shell_builder;
  6pub mod static_source;
  7mod task_template;
  8mod vscode_debug_format;
  9mod vscode_format;
 10
 11use collections::{HashMap, HashSet, hash_map};
 12use gpui::SharedString;
 13use schemars::JsonSchema;
 14use serde::{Deserialize, Serialize};
 15use std::borrow::Cow;
 16use std::path::PathBuf;
 17use std::str::FromStr;
 18
 19pub use debug_format::{
 20    AttachRequest, BuildTaskDefinition, DebugRequest, DebugScenario, DebugTaskFile, LaunchRequest,
 21    Request, TcpArgumentsTemplate, ZedDebugConfig,
 22};
 23pub use shell_builder::{DEFAULT_REMOTE_SHELL, ShellBuilder};
 24pub use task_template::{
 25    DebugArgsRequest, HideStrategy, RevealStrategy, TaskTemplate, TaskTemplates,
 26    substitute_variables_in_map, substitute_variables_in_str,
 27};
 28pub use vscode_debug_format::VsCodeDebugTaskFile;
 29pub use vscode_format::VsCodeTaskFile;
 30pub use zed_actions::RevealTarget;
 31
 32/// Task identifier, unique within the application.
 33/// Based on it, task reruns and terminal tabs are managed.
 34#[derive(Default, Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Deserialize)]
 35pub struct TaskId(pub String);
 36
 37/// Contains all information needed by Zed to spawn a new terminal tab for the given task.
 38#[derive(Default, Debug, Clone, PartialEq, Eq)]
 39pub struct SpawnInTerminal {
 40    /// Id of the task to use when determining task tab affinity.
 41    pub id: TaskId,
 42    /// Full unshortened form of `label` field.
 43    pub full_label: String,
 44    /// Human readable name of the terminal tab.
 45    pub label: String,
 46    /// Executable command to spawn.
 47    pub command: Option<String>,
 48    /// Arguments to the command, potentially unsubstituted,
 49    /// to let the shell that spawns the command to do the substitution, if needed.
 50    pub args: Vec<String>,
 51    /// A human-readable label, containing command and all of its arguments, joined and substituted.
 52    pub command_label: String,
 53    /// Current working directory to spawn the command into.
 54    pub cwd: Option<PathBuf>,
 55    /// Env overrides for the command, will be appended to the terminal's environment from the settings.
 56    pub env: HashMap<String, String>,
 57    /// Whether to use a new terminal tab or reuse the existing one to spawn the process.
 58    pub use_new_terminal: bool,
 59    /// Whether to allow multiple instances of the same task to be run, or rather wait for the existing ones to finish.
 60    pub allow_concurrent_runs: bool,
 61    /// What to do with the terminal pane and tab, after the command was started.
 62    pub reveal: RevealStrategy,
 63    /// Where to show tasks' terminal output.
 64    pub reveal_target: RevealTarget,
 65    /// What to do with the terminal pane and tab, after the command had finished.
 66    pub hide: HideStrategy,
 67    /// Which shell to use when spawning the task.
 68    pub shell: Shell,
 69    /// Whether to show the task summary line in the task output (sucess/failure).
 70    pub show_summary: bool,
 71    /// Whether to show the command line in the task output.
 72    pub show_command: bool,
 73    /// Whether to show the rerun button in the terminal tab.
 74    pub show_rerun: bool,
 75}
 76
 77impl SpawnInTerminal {
 78    pub fn to_proto(&self) -> proto::SpawnInTerminal {
 79        proto::SpawnInTerminal {
 80            label: self.label.clone(),
 81            command: self.command.clone(),
 82            args: self.args.clone(),
 83            env: self
 84                .env
 85                .iter()
 86                .map(|(k, v)| (k.clone(), v.clone()))
 87                .collect(),
 88            cwd: self
 89                .cwd
 90                .clone()
 91                .map(|cwd| cwd.to_string_lossy().into_owned()),
 92        }
 93    }
 94
 95    pub fn from_proto(proto: proto::SpawnInTerminal) -> Self {
 96        Self {
 97            label: proto.label.clone(),
 98            command: proto.command.clone(),
 99            args: proto.args.clone(),
100            env: proto.env.into_iter().collect(),
101            cwd: proto.cwd.map(PathBuf::from).clone(),
102            ..Default::default()
103        }
104    }
105}
106
107/// A final form of the [`TaskTemplate`], that got resolved with a particular [`TaskContext`] and now is ready to spawn the actual task.
108#[derive(Clone, Debug, PartialEq, Eq)]
109pub struct ResolvedTask {
110    /// A way to distinguish tasks produced by the same template, but different contexts.
111    /// NOTE: Resolved tasks may have the same labels, commands and do the same things,
112    /// but still may have different ids if the context was different during the resolution.
113    /// Since the template has `env` field, for a generic task that may be a bash command,
114    /// so it's impossible to determine the id equality without more context in a generic case.
115    pub id: TaskId,
116    /// A template the task got resolved from.
117    original_task: TaskTemplate,
118    /// Full, unshortened label of the task after all resolutions are made.
119    pub resolved_label: String,
120    /// Variables that were substituted during the task template resolution.
121    substituted_variables: HashSet<VariableName>,
122    /// Further actions that need to take place after the resolved task is spawned,
123    /// with all task variables resolved.
124    pub resolved: SpawnInTerminal,
125}
126
127impl ResolvedTask {
128    /// A task template before the resolution.
129    pub fn original_task(&self) -> &TaskTemplate {
130        &self.original_task
131    }
132
133    /// Variables that were substituted during the task template resolution.
134    pub fn substituted_variables(&self) -> &HashSet<VariableName> {
135        &self.substituted_variables
136    }
137
138    /// A human-readable label to display in the UI.
139    pub fn display_label(&self) -> &str {
140        self.resolved.label.as_str()
141    }
142}
143
144/// Variables, available for use in [`TaskContext`] when a Zed's [`TaskTemplate`] gets resolved into a [`ResolvedTask`].
145/// Name of the variable must be a valid shell variable identifier, which generally means that it is
146/// a word  consisting only  of alphanumeric characters and underscores,
147/// and beginning with an alphabetic character or an  underscore.
148#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
149pub enum VariableName {
150    /// An absolute path of the currently opened file.
151    File,
152    /// A path of the currently opened file (relative to worktree root).
153    RelativeFile,
154    /// A path of the currently opened file's directory (relative to worktree root).
155    RelativeDir,
156    /// The currently opened filename.
157    Filename,
158    /// The path to a parent directory of a currently opened file.
159    Dirname,
160    /// Stem (filename without extension) of the currently opened file.
161    Stem,
162    /// An absolute path of the currently opened worktree, that contains the file.
163    WorktreeRoot,
164    /// A symbol text, that contains latest cursor/selection position.
165    Symbol,
166    /// A row with the latest cursor/selection position.
167    Row,
168    /// A column with the latest cursor/selection position.
169    Column,
170    /// Text from the latest selection.
171    SelectedText,
172    /// The symbol selected by the symbol tagging system, specifically the @run capture in a runnables.scm
173    RunnableSymbol,
174    /// Custom variable, provided by the plugin or other external source.
175    /// Will be printed with `CUSTOM_` prefix to avoid potential conflicts with other variables.
176    Custom(Cow<'static, str>),
177}
178
179impl VariableName {
180    /// Generates a `$VARIABLE`-like string value to be used in templates.
181    pub fn template_value(&self) -> String {
182        format!("${self}")
183    }
184    /// Generates a `"$VARIABLE"`-like string, to be used instead of `Self::template_value` when expanded value could contain spaces or special characters.
185    pub fn template_value_with_whitespace(&self) -> String {
186        format!("\"${self}\"")
187    }
188}
189
190impl FromStr for VariableName {
191    type Err = ();
192
193    fn from_str(s: &str) -> Result<Self, Self::Err> {
194        let without_prefix = s.strip_prefix(ZED_VARIABLE_NAME_PREFIX).ok_or(())?;
195        let value = match without_prefix {
196            "FILE" => Self::File,
197            "FILENAME" => Self::Filename,
198            "RELATIVE_FILE" => Self::RelativeFile,
199            "RELATIVE_DIR" => Self::RelativeDir,
200            "DIRNAME" => Self::Dirname,
201            "STEM" => Self::Stem,
202            "WORKTREE_ROOT" => Self::WorktreeRoot,
203            "SYMBOL" => Self::Symbol,
204            "RUNNABLE_SYMBOL" => Self::RunnableSymbol,
205            "SELECTED_TEXT" => Self::SelectedText,
206            "ROW" => Self::Row,
207            "COLUMN" => Self::Column,
208            _ => {
209                if let Some(custom_name) =
210                    without_prefix.strip_prefix(ZED_CUSTOM_VARIABLE_NAME_PREFIX)
211                {
212                    Self::Custom(Cow::Owned(custom_name.to_owned()))
213                } else {
214                    return Err(());
215                }
216            }
217        };
218        Ok(value)
219    }
220}
221
222/// A prefix that all [`VariableName`] variants are prefixed with when used in environment variables and similar template contexts.
223pub const ZED_VARIABLE_NAME_PREFIX: &str = "ZED_";
224const ZED_CUSTOM_VARIABLE_NAME_PREFIX: &str = "CUSTOM_";
225
226impl std::fmt::Display for VariableName {
227    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
228        match self {
229            Self::File => write!(f, "{ZED_VARIABLE_NAME_PREFIX}FILE"),
230            Self::Filename => write!(f, "{ZED_VARIABLE_NAME_PREFIX}FILENAME"),
231            Self::RelativeFile => write!(f, "{ZED_VARIABLE_NAME_PREFIX}RELATIVE_FILE"),
232            Self::RelativeDir => write!(f, "{ZED_VARIABLE_NAME_PREFIX}RELATIVE_DIR"),
233            Self::Dirname => write!(f, "{ZED_VARIABLE_NAME_PREFIX}DIRNAME"),
234            Self::Stem => write!(f, "{ZED_VARIABLE_NAME_PREFIX}STEM"),
235            Self::WorktreeRoot => write!(f, "{ZED_VARIABLE_NAME_PREFIX}WORKTREE_ROOT"),
236            Self::Symbol => write!(f, "{ZED_VARIABLE_NAME_PREFIX}SYMBOL"),
237            Self::Row => write!(f, "{ZED_VARIABLE_NAME_PREFIX}ROW"),
238            Self::Column => write!(f, "{ZED_VARIABLE_NAME_PREFIX}COLUMN"),
239            Self::SelectedText => write!(f, "{ZED_VARIABLE_NAME_PREFIX}SELECTED_TEXT"),
240            Self::RunnableSymbol => write!(f, "{ZED_VARIABLE_NAME_PREFIX}RUNNABLE_SYMBOL"),
241            Self::Custom(s) => write!(
242                f,
243                "{ZED_VARIABLE_NAME_PREFIX}{ZED_CUSTOM_VARIABLE_NAME_PREFIX}{s}"
244            ),
245        }
246    }
247}
248
249/// Container for predefined environment variables that describe state of Zed at the time the task was spawned.
250#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
251pub struct TaskVariables(HashMap<VariableName, String>);
252
253impl TaskVariables {
254    /// Inserts another variable into the container, overwriting the existing one if it already exists — in this case, the old value is returned.
255    pub fn insert(&mut self, variable: VariableName, value: String) -> Option<String> {
256        self.0.insert(variable, value)
257    }
258
259    /// Extends the container with another one, overwriting the existing variables on collision.
260    pub fn extend(&mut self, other: Self) {
261        self.0.extend(other.0);
262    }
263    /// Get the value associated with given variable name, if there is one.
264    pub fn get(&self, key: &VariableName) -> Option<&str> {
265        self.0.get(key).map(|s| s.as_str())
266    }
267    /// Clear out variables obtained from tree-sitter queries, which are prefixed with '_' character
268    pub fn sweep(&mut self) {
269        self.0.retain(|name, _| {
270            if let VariableName::Custom(name) = name {
271                !name.starts_with('_')
272            } else {
273                true
274            }
275        })
276    }
277
278    pub fn iter(&self) -> impl Iterator<Item = (&VariableName, &String)> {
279        self.0.iter()
280    }
281}
282
283impl FromIterator<(VariableName, String)> for TaskVariables {
284    fn from_iter<T: IntoIterator<Item = (VariableName, String)>>(iter: T) -> Self {
285        Self(HashMap::from_iter(iter))
286    }
287}
288
289impl IntoIterator for TaskVariables {
290    type Item = (VariableName, String);
291
292    type IntoIter = hash_map::IntoIter<VariableName, String>;
293
294    fn into_iter(self) -> Self::IntoIter {
295        self.0.into_iter()
296    }
297}
298
299/// Keeps track of the file associated with a task and context of tasks execution (i.e. current file or current function).
300/// Keeps all Zed-related state inside, used to produce a resolved task out of its template.
301#[derive(Clone, Debug, Default, PartialEq, Eq)]
302pub struct TaskContext {
303    /// A path to a directory in which the task should be executed.
304    pub cwd: Option<PathBuf>,
305    /// Additional environment variables associated with a given task.
306    pub task_variables: TaskVariables,
307    /// Environment variables obtained when loading the project into Zed.
308    /// This is the environment one would get when `cd`ing in a terminal
309    /// into the project's root directory.
310    pub project_env: HashMap<String, String>,
311}
312
313/// This is a new type representing a 'tag' on a 'runnable symbol', typically a test of main() function, found via treesitter.
314#[derive(Clone, Debug)]
315pub struct RunnableTag(pub SharedString);
316
317/// Shell configuration to open the terminal with.
318#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
319#[serde(rename_all = "snake_case")]
320pub enum Shell {
321    /// Use the system's default terminal configuration in /etc/passwd
322    #[default]
323    System,
324    /// Use a specific program with no arguments.
325    Program(String),
326    /// Use a specific program with arguments.
327    WithArguments {
328        /// The program to run.
329        program: String,
330        /// The arguments to pass to the program.
331        args: Vec<String>,
332        /// An optional string to override the title of the terminal tab
333        title_override: Option<SharedString>,
334    },
335}
336
337pub type VsCodeEnvVariable = String;
338pub type ZedEnvVariable = String;
339
340pub struct EnvVariableReplacer {
341    variables: HashMap<VsCodeEnvVariable, ZedEnvVariable>,
342}
343
344impl EnvVariableReplacer {
345    pub fn new(variables: HashMap<VsCodeEnvVariable, ZedEnvVariable>) -> Self {
346        Self { variables }
347    }
348
349    pub fn replace_value(&self, input: serde_json::Value) -> serde_json::Value {
350        match input {
351            serde_json::Value::String(s) => serde_json::Value::String(self.replace(&s)),
352            serde_json::Value::Array(arr) => {
353                serde_json::Value::Array(arr.into_iter().map(|v| self.replace_value(v)).collect())
354            }
355            serde_json::Value::Object(obj) => serde_json::Value::Object(
356                obj.into_iter()
357                    .map(|(k, v)| (self.replace(&k), self.replace_value(v)))
358                    .collect(),
359            ),
360            _ => input,
361        }
362    }
363    // Replaces occurrences of VsCode-specific environment variables with Zed equivalents.
364    pub fn replace(&self, input: &str) -> String {
365        shellexpand::env_with_context_no_errors(&input, |var: &str| {
366            // Colons denote a default value in case the variable is not set. We want to preserve that default, as otherwise shellexpand will substitute it for us.
367            let colon_position = var.find(':').unwrap_or(var.len());
368            let (left, right) = var.split_at(colon_position);
369            if left == "env" && !right.is_empty() {
370                let variable_name = &right[1..];
371                return Some(format!("${{{variable_name}}}"));
372            }
373            let (variable_name, default) = (left, right);
374            let append_previous_default = |ret: &mut String| {
375                if !default.is_empty() {
376                    ret.push_str(default);
377                }
378            };
379            if let Some(substitution) = self.variables.get(variable_name) {
380                // Got a VSCode->Zed hit, perform a substitution
381                let mut name = format!("${{{substitution}");
382                append_previous_default(&mut name);
383                name.push('}');
384                return Some(name);
385            }
386            // This is an unknown variable.
387            // We should not error out, as they may come from user environment (e.g. $PATH). That means that the variable substitution might not be perfect.
388            // If there's a default, we need to return the string verbatim as otherwise shellexpand will apply that default for us.
389            if !default.is_empty() {
390                return Some(format!("${{{var}}}"));
391            }
392            // Else we can just return None and that variable will be left as is.
393            None
394        })
395        .into_owned()
396    }
397}