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