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