lib.rs

  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;
  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 adapter_schema::{AdapterSchema, AdapterSchemas};
 20pub use debug_format::{
 21    AttachRequest, BuildTaskDefinition, DebugRequest, DebugScenario, DebugTaskFile, LaunchRequest,
 22    Request, TcpArgumentsTemplate, ZedDebugConfig,
 23};
 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: 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
337#[cfg(target_os = "windows")]
338#[derive(Debug, Clone, Copy, PartialEq, Eq)]
339enum WindowsShellType {
340    Powershell,
341    Cmd,
342    Other,
343}
344
345/// ShellBuilder is used to turn a user-requested task into a
346/// program that can be executed by the shell.
347pub struct ShellBuilder {
348    program: String,
349    args: Vec<String>,
350    interactive: bool,
351}
352
353pub static DEFAULT_REMOTE_SHELL: &str = "\"${SHELL:-sh}\"";
354
355impl ShellBuilder {
356    /// Create a new ShellBuilder as configured.
357    pub fn new(is_local: bool, shell: &Shell) -> Self {
358        let (program, args) = match shell {
359            Shell::System => {
360                if is_local {
361                    (Self::system_shell(), Vec::new())
362                } else {
363                    (DEFAULT_REMOTE_SHELL.to_string(), Vec::new())
364                }
365            }
366            Shell::Program(shell) => (shell.clone(), Vec::new()),
367            Shell::WithArguments { program, args, .. } => (program.clone(), args.clone()),
368        };
369        Self {
370            program,
371            args,
372            interactive: true,
373        }
374    }
375    pub fn non_interactive(mut self) -> Self {
376        self.interactive = false;
377        self
378    }
379}
380
381#[cfg(not(target_os = "windows"))]
382impl ShellBuilder {
383    /// Returns the label to show in the terminal tab
384    pub fn command_label(&self, command_label: &str) -> String {
385        let interactivity = self.interactive.then_some("-i ").unwrap_or_default();
386        format!("{} {interactivity}-c '{}'", self.program, command_label)
387    }
388
389    /// Returns the program and arguments to run this task in a shell.
390    pub fn build(mut self, task_command: String, task_args: &Vec<String>) -> (String, Vec<String>) {
391        let combined_command = task_args
392            .into_iter()
393            .fold(task_command, |mut command, arg| {
394                command.push(' ');
395                command.push_str(&arg);
396                command
397            });
398        self.args.extend(
399            self.interactive
400                .then(|| "-i".to_owned())
401                .into_iter()
402                .chain(["-c".to_owned(), combined_command]),
403        );
404
405        (self.program, self.args)
406    }
407
408    fn system_shell() -> String {
409        std::env::var("SHELL").unwrap_or("/bin/sh".to_string())
410    }
411}
412
413#[cfg(target_os = "windows")]
414impl ShellBuilder {
415    /// Returns the label to show in the terminal tab
416    pub fn command_label(&self, command_label: &str) -> String {
417        match self.windows_shell_type() {
418            WindowsShellType::Powershell => {
419                format!("{} -C '{}'", self.program, command_label)
420            }
421            WindowsShellType::Cmd => {
422                format!("{} /C '{}'", self.program, command_label)
423            }
424            WindowsShellType::Other => {
425                format!("{} -i -c '{}'", self.program, command_label)
426            }
427        }
428    }
429
430    /// Returns the program and arguments to run this task in a shell.
431    pub fn build(mut self, task_command: String, task_args: &Vec<String>) -> (String, Vec<String>) {
432        let combined_command = task_args
433            .into_iter()
434            .fold(task_command, |mut command, arg| {
435                command.push(' ');
436                command.push_str(&self.to_windows_shell_variable(arg.to_string()));
437                command
438            });
439
440        match self.windows_shell_type() {
441            WindowsShellType::Powershell => self.args.extend(["-C".to_owned(), combined_command]),
442            WindowsShellType::Cmd => self.args.extend(["/C".to_owned(), combined_command]),
443            WindowsShellType::Other => {
444                self.args
445                    .extend(["-i".to_owned(), "-c".to_owned(), combined_command])
446            }
447        }
448
449        (self.program, self.args)
450    }
451    fn windows_shell_type(&self) -> WindowsShellType {
452        if self.program == "powershell"
453            || self.program.ends_with("powershell.exe")
454            || self.program == "pwsh"
455            || self.program.ends_with("pwsh.exe")
456        {
457            WindowsShellType::Powershell
458        } else if self.program == "cmd" || self.program.ends_with("cmd.exe") {
459            WindowsShellType::Cmd
460        } else {
461            // Someother shell detected, the user might install and use a
462            // unix-like shell.
463            WindowsShellType::Other
464        }
465    }
466
467    // `alacritty_terminal` uses this as default on Windows. See:
468    // https://github.com/alacritty/alacritty/blob/0d4ab7bca43213d96ddfe40048fc0f922543c6f8/alacritty_terminal/src/tty/windows/mod.rs#L130
469    // We could use `util::get_windows_system_shell()` here, but we are running tasks here, so leave it to `powershell.exe`
470    // should be okay.
471    fn system_shell() -> String {
472        "powershell.exe".to_string()
473    }
474
475    fn to_windows_shell_variable(&self, input: String) -> String {
476        match self.windows_shell_type() {
477            WindowsShellType::Powershell => Self::to_powershell_variable(input),
478            WindowsShellType::Cmd => Self::to_cmd_variable(input),
479            WindowsShellType::Other => input,
480        }
481    }
482
483    fn to_cmd_variable(input: String) -> String {
484        if let Some(var_str) = input.strip_prefix("${") {
485            if var_str.find(':').is_none() {
486                // If the input starts with "${", remove the trailing "}"
487                format!("%{}%", &var_str[..var_str.len() - 1])
488            } else {
489                // `${SOME_VAR:-SOME_DEFAULT}`, we currently do not handle this situation,
490                // which will result in the task failing to run in such cases.
491                input
492            }
493        } else if let Some(var_str) = input.strip_prefix('$') {
494            // If the input starts with "$", directly append to "$env:"
495            format!("%{}%", var_str)
496        } else {
497            // If no prefix is found, return the input as is
498            input
499        }
500    }
501
502    fn to_powershell_variable(input: String) -> String {
503        if let Some(var_str) = input.strip_prefix("${") {
504            if var_str.find(':').is_none() {
505                // If the input starts with "${", remove the trailing "}"
506                format!("$env:{}", &var_str[..var_str.len() - 1])
507            } else {
508                // `${SOME_VAR:-SOME_DEFAULT}`, we currently do not handle this situation,
509                // which will result in the task failing to run in such cases.
510                input
511            }
512        } else if let Some(var_str) = input.strip_prefix('$') {
513            // If the input starts with "$", directly append to "$env:"
514            format!("$env:{}", var_str)
515        } else {
516            // If no prefix is found, return the input as is
517            input
518        }
519    }
520}
521
522type VsCodeEnvVariable = String;
523type ZedEnvVariable = String;
524
525struct EnvVariableReplacer {
526    variables: HashMap<VsCodeEnvVariable, ZedEnvVariable>,
527}
528
529impl EnvVariableReplacer {
530    fn new(variables: HashMap<VsCodeEnvVariable, ZedEnvVariable>) -> Self {
531        Self { variables }
532    }
533    // Replaces occurrences of VsCode-specific environment variables with Zed equivalents.
534    fn replace(&self, input: &str) -> String {
535        shellexpand::env_with_context_no_errors(&input, |var: &str| {
536            // 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.
537            let colon_position = var.find(':').unwrap_or(var.len());
538            let (left, right) = var.split_at(colon_position);
539            if left == "env" && !right.is_empty() {
540                let variable_name = &right[1..];
541                return Some(format!("${{{variable_name}}}"));
542            }
543            let (variable_name, default) = (left, right);
544            let append_previous_default = |ret: &mut String| {
545                if !default.is_empty() {
546                    ret.push_str(default);
547                }
548            };
549            if let Some(substitution) = self.variables.get(variable_name) {
550                // Got a VSCode->Zed hit, perform a substitution
551                let mut name = format!("${{{substitution}");
552                append_previous_default(&mut name);
553                name.push('}');
554                return Some(name);
555            }
556            // This is an unknown variable.
557            // 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.
558            // If there's a default, we need to return the string verbatim as otherwise shellexpand will apply that default for us.
559            if !default.is_empty() {
560                return Some(format!("${{{var}}}"));
561            }
562            // Else we can just return None and that variable will be left as is.
563            None
564        })
565        .into_owned()
566    }
567}