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