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