task_template.rs

  1use anyhow::{Context, bail};
  2use collections::{HashMap, HashSet};
  3use schemars::{JsonSchema, r#gen::SchemaSettings};
  4use serde::{Deserialize, Serialize};
  5use sha2::{Digest, Sha256};
  6use std::path::PathBuf;
  7use util::serde::default_true;
  8use util::{ResultExt, truncate_and_remove_front};
  9
 10use crate::{
 11    AttachConfig, ResolvedTask, RevealTarget, Shell, SpawnInTerminal, TCPHost, TaskContext, TaskId,
 12    VariableName, ZED_VARIABLE_NAME_PREFIX,
 13    serde_helpers::{non_empty_string_vec, non_empty_string_vec_json_schema},
 14};
 15
 16/// A template definition of a Zed task to run.
 17/// May use the [`VariableName`] to get the corresponding substitutions into its fields.
 18///
 19/// Template itself is not ready to spawn a task, it needs to be resolved with a [`TaskContext`] first, that
 20/// contains all relevant Zed state in task variables.
 21/// A single template may produce different tasks (or none) for different contexts.
 22#[derive(Clone, Default, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
 23#[serde(rename_all = "snake_case")]
 24pub struct TaskTemplate {
 25    /// Human readable name of the task to display in the UI.
 26    pub label: String,
 27    /// Executable command to spawn.
 28    pub command: String,
 29    /// Arguments to the command.
 30    #[serde(default)]
 31    pub args: Vec<String>,
 32    /// Env overrides for the command, will be appended to the terminal's environment from the settings.
 33    #[serde(default)]
 34    pub env: HashMap<String, String>,
 35    /// Current working directory to spawn the command into, defaults to current project root.
 36    #[serde(default)]
 37    pub cwd: Option<String>,
 38    /// Whether to use a new terminal tab or reuse the existing one to spawn the process.
 39    #[serde(default)]
 40    pub use_new_terminal: bool,
 41    /// Whether to allow multiple instances of the same task to be run, or rather wait for the existing ones to finish.
 42    #[serde(default)]
 43    pub allow_concurrent_runs: bool,
 44    /// What to do with the terminal pane and tab, after the command was started:
 45    /// * `always` — always show the task's pane, and focus the corresponding tab in it (default)
 46    // * `no_focus` — always show the task's pane, add the task's tab in it, but don't focus it
 47    // * `never` — do not alter focus, but still add/reuse the task's tab in its pane
 48    #[serde(default)]
 49    pub reveal: RevealStrategy,
 50    /// Where to place the task's terminal item after starting the task.
 51    /// * `dock` — in the terminal dock, "regular" terminal items' place (default).
 52    /// * `center` — in the central pane group, "main" editor area.
 53    #[serde(default)]
 54    pub reveal_target: RevealTarget,
 55    /// What to do with the terminal pane and tab, after the command had finished:
 56    /// * `never` — do nothing when the command finishes (default)
 57    /// * `always` — always hide the terminal tab, hide the pane also if it was the last tab in it
 58    /// * `on_success` — hide the terminal tab on task success only, otherwise behaves similar to `always`.
 59    #[serde(default)]
 60    pub hide: HideStrategy,
 61    /// If this task should start a debugger or not
 62    #[serde(default, skip)]
 63    pub task_type: TaskType,
 64    /// Represents the tags which this template attaches to.
 65    /// Adding this removes this task from other UI and gives you ability to run it by tag.
 66    #[serde(default, deserialize_with = "non_empty_string_vec")]
 67    #[schemars(schema_with = "non_empty_string_vec_json_schema")]
 68    pub tags: Vec<String>,
 69    /// Which shell to use when spawning the task.
 70    #[serde(default)]
 71    pub shell: Shell,
 72    /// Whether to show the task line in the task output.
 73    #[serde(default = "default_true")]
 74    pub show_summary: bool,
 75    /// Whether to show the command line in the task output.
 76    #[serde(default = "default_true")]
 77    pub show_command: bool,
 78}
 79
 80#[derive(Deserialize, Eq, PartialEq, Clone, Debug)]
 81/// Use to represent debug request type
 82pub enum DebugArgsRequest {
 83    /// launch (program, cwd) are stored in TaskTemplate as (command, cwd)
 84    Launch,
 85    /// Attach
 86    Attach(AttachConfig),
 87}
 88
 89#[derive(Deserialize, Eq, PartialEq, Clone, Debug)]
 90/// This represents the arguments for the debug task.
 91pub struct DebugArgs {
 92    /// The launch type
 93    pub request: DebugArgsRequest,
 94    /// Adapter choice
 95    pub adapter: String,
 96    /// TCP connection to make with debug adapter
 97    pub tcp_connection: Option<TCPHost>,
 98    /// Args to send to debug adapter
 99    pub initialize_args: Option<serde_json::value::Value>,
100    /// the locator to use
101    pub locator: Option<String>,
102    /// Whether to tell the debug adapter to stop on entry
103    pub stop_on_entry: Option<bool>,
104}
105
106/// Represents the type of task that is being ran
107#[derive(Default, Eq, PartialEq, Clone, Debug)]
108#[allow(clippy::large_enum_variant)]
109pub enum TaskType {
110    /// Act like a typically task that runs commands
111    #[default]
112    Script,
113    /// This task starts the debugger for a language
114    Debug(DebugArgs),
115}
116
117#[derive(Clone, Debug, PartialEq, Eq)]
118/// The type of task modal to spawn
119pub enum TaskModal {
120    /// Show regular tasks
121    ScriptModal,
122    /// Show debug tasks
123    DebugModal,
124}
125
126/// What to do with the terminal pane and tab, after the command was started.
127#[derive(Default, Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
128#[serde(rename_all = "snake_case")]
129pub enum RevealStrategy {
130    /// Always show the task's pane, and focus the corresponding tab in it.
131    #[default]
132    Always,
133    /// Always show the task's pane, add the task's tab in it, but don't focus it.
134    NoFocus,
135    /// Do not alter focus, but still add/reuse the task's tab in its pane.
136    Never,
137}
138
139/// What to do with the terminal pane and tab, after the command has finished.
140#[derive(Default, Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
141#[serde(rename_all = "snake_case")]
142pub enum HideStrategy {
143    /// Do nothing when the command finishes.
144    #[default]
145    Never,
146    /// Always hide the terminal tab, hide the pane also if it was the last tab in it.
147    Always,
148    /// Hide the terminal tab on task success only, otherwise behaves similar to `Always`.
149    OnSuccess,
150}
151
152/// A group of Tasks defined in a JSON file.
153#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
154pub struct TaskTemplates(pub Vec<TaskTemplate>);
155
156impl TaskTemplates {
157    /// Generates JSON schema of Tasks JSON template format.
158    pub fn generate_json_schema() -> serde_json_lenient::Value {
159        let schema = SchemaSettings::draft07()
160            .with(|settings| settings.option_add_null_type = false)
161            .into_generator()
162            .into_root_schema_for::<Self>();
163
164        serde_json_lenient::to_value(schema).unwrap()
165    }
166}
167
168impl TaskTemplate {
169    /// Replaces all `VariableName` task variables in the task template string fields.
170    /// If any replacement fails or the new string substitutions still have [`ZED_VARIABLE_NAME_PREFIX`],
171    /// `None` is returned.
172    ///
173    /// Every [`ResolvedTask`] gets a [`TaskId`], based on the `id_base` (to avoid collision with various task sources),
174    /// and hashes of its template and [`TaskContext`], see [`ResolvedTask`] fields' documentation for more details.
175    pub fn resolve_task(&self, id_base: &str, cx: &TaskContext) -> Option<ResolvedTask> {
176        if self.label.trim().is_empty()
177            || (self.command.trim().is_empty() && matches!(self.task_type, TaskType::Script))
178        {
179            return None;
180        }
181
182        let mut variable_names = HashMap::default();
183        let mut substituted_variables = HashSet::default();
184        let task_variables = cx
185            .task_variables
186            .0
187            .iter()
188            .map(|(key, value)| {
189                let key_string = key.to_string();
190                if !variable_names.contains_key(&key_string) {
191                    variable_names.insert(key_string.clone(), key.clone());
192                }
193                (key_string, value.as_str())
194            })
195            .collect::<HashMap<_, _>>();
196        let truncated_variables = truncate_variables(&task_variables);
197        let cwd = match self.cwd.as_deref() {
198            Some(cwd) => {
199                let substituted_cwd = substitute_all_template_variables_in_str(
200                    cwd,
201                    &task_variables,
202                    &variable_names,
203                    &mut substituted_variables,
204                )?;
205                Some(PathBuf::from(substituted_cwd))
206            }
207            None => None,
208        }
209        .or(cx.cwd.clone());
210        let full_label = substitute_all_template_variables_in_str(
211            &self.label,
212            &task_variables,
213            &variable_names,
214            &mut substituted_variables,
215        )?;
216
217        // Arbitrarily picked threshold below which we don't truncate any variables.
218        const TRUNCATION_THRESHOLD: usize = 64;
219
220        let human_readable_label = if full_label.len() > TRUNCATION_THRESHOLD {
221            substitute_all_template_variables_in_str(
222                &self.label,
223                &truncated_variables,
224                &variable_names,
225                &mut substituted_variables,
226            )?
227        } else {
228            full_label.clone()
229        }
230        .lines()
231        .fold(String::new(), |mut string, line| {
232            if string.is_empty() {
233                string.push_str(line);
234            } else {
235                string.push_str("\\n");
236                string.push_str(line);
237            }
238            string
239        });
240
241        let command = substitute_all_template_variables_in_str(
242            &self.command,
243            &task_variables,
244            &variable_names,
245            &mut substituted_variables,
246        )?;
247        let args_with_substitutions = substitute_all_template_variables_in_vec(
248            &self.args,
249            &task_variables,
250            &variable_names,
251            &mut substituted_variables,
252        )?;
253
254        let task_hash = to_hex_hash(self)
255            .context("hashing task template")
256            .log_err()?;
257        let variables_hash = to_hex_hash(&task_variables)
258            .context("hashing task variables")
259            .log_err()?;
260        let id = TaskId(format!("{id_base}_{task_hash}_{variables_hash}"));
261
262        let env = {
263            // Start with the project environment as the base.
264            let mut env = cx.project_env.clone();
265
266            // Extend that environment with what's defined in the TaskTemplate
267            env.extend(self.env.clone());
268
269            // Then we replace all task variables that could be set in environment variables
270            let mut env = substitute_all_template_variables_in_map(
271                &env,
272                &task_variables,
273                &variable_names,
274                &mut substituted_variables,
275            )?;
276
277            // Last step: set the task variables as environment variables too
278            env.extend(task_variables.into_iter().map(|(k, v)| (k, v.to_owned())));
279            env
280        };
281
282        Some(ResolvedTask {
283            id: id.clone(),
284            substituted_variables,
285            original_task: self.clone(),
286            resolved_label: full_label.clone(),
287            resolved: Some(SpawnInTerminal {
288                id,
289                cwd,
290                full_label,
291                label: human_readable_label,
292                command_label: args_with_substitutions.iter().fold(
293                    command.clone(),
294                    |mut command_label, arg| {
295                        command_label.push(' ');
296                        command_label.push_str(arg);
297                        command_label
298                    },
299                ),
300                command,
301                args: self.args.clone(),
302                env,
303                use_new_terminal: self.use_new_terminal,
304                allow_concurrent_runs: self.allow_concurrent_runs,
305                reveal: self.reveal,
306                reveal_target: self.reveal_target,
307                hide: self.hide,
308                shell: self.shell.clone(),
309                show_summary: self.show_summary,
310                show_command: self.show_command,
311                show_rerun: true,
312            }),
313        })
314    }
315}
316
317const MAX_DISPLAY_VARIABLE_LENGTH: usize = 15;
318
319fn truncate_variables(task_variables: &HashMap<String, &str>) -> HashMap<String, String> {
320    task_variables
321        .iter()
322        .map(|(key, value)| {
323            (
324                key.clone(),
325                truncate_and_remove_front(value, MAX_DISPLAY_VARIABLE_LENGTH),
326            )
327        })
328        .collect()
329}
330
331fn to_hex_hash(object: impl Serialize) -> anyhow::Result<String> {
332    let json = serde_json_lenient::to_string(&object).context("serializing the object")?;
333    let mut hasher = Sha256::new();
334    hasher.update(json.as_bytes());
335    Ok(hex::encode(hasher.finalize()))
336}
337
338fn substitute_all_template_variables_in_str<A: AsRef<str>>(
339    template_str: &str,
340    task_variables: &HashMap<String, A>,
341    variable_names: &HashMap<String, VariableName>,
342    substituted_variables: &mut HashSet<VariableName>,
343) -> Option<String> {
344    let substituted_string = shellexpand::env_with_context(template_str, |var| {
345        // 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.
346        let colon_position = var.find(':').unwrap_or(var.len());
347        let (variable_name, default) = var.split_at(colon_position);
348        if let Some(name) = task_variables.get(variable_name) {
349            if let Some(substituted_variable) = variable_names.get(variable_name) {
350                substituted_variables.insert(substituted_variable.clone());
351            }
352
353            let mut name = name.as_ref().to_owned();
354            // Got a task variable hit
355            if !default.is_empty() {
356                name.push_str(default);
357            }
358            return Ok(Some(name));
359        } else if variable_name.starts_with(ZED_VARIABLE_NAME_PREFIX) {
360            bail!("Unknown variable name: {variable_name}");
361        }
362        // This is an unknown variable.
363        // 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.
364        // If there's a default, we need to return the string verbatim as otherwise shellexpand will apply that default for us.
365        if !default.is_empty() {
366            return Ok(Some(format!("${{{var}}}")));
367        }
368        // Else we can just return None and that variable will be left as is.
369        Ok(None)
370    })
371    .ok()?;
372    Some(substituted_string.into_owned())
373}
374
375fn substitute_all_template_variables_in_vec(
376    template_strs: &[String],
377    task_variables: &HashMap<String, &str>,
378    variable_names: &HashMap<String, VariableName>,
379    substituted_variables: &mut HashSet<VariableName>,
380) -> Option<Vec<String>> {
381    let mut expanded = Vec::with_capacity(template_strs.len());
382    for variable in template_strs {
383        let new_value = substitute_all_template_variables_in_str(
384            variable,
385            task_variables,
386            variable_names,
387            substituted_variables,
388        )?;
389        expanded.push(new_value);
390    }
391    Some(expanded)
392}
393
394fn substitute_all_template_variables_in_map(
395    keys_and_values: &HashMap<String, String>,
396    task_variables: &HashMap<String, &str>,
397    variable_names: &HashMap<String, VariableName>,
398    substituted_variables: &mut HashSet<VariableName>,
399) -> Option<HashMap<String, String>> {
400    let mut new_map: HashMap<String, String> = Default::default();
401    for (key, value) in keys_and_values {
402        let new_value = substitute_all_template_variables_in_str(
403            value,
404            task_variables,
405            variable_names,
406            substituted_variables,
407        )?;
408        let new_key = substitute_all_template_variables_in_str(
409            key,
410            task_variables,
411            variable_names,
412            substituted_variables,
413        )?;
414        new_map.insert(new_key, new_value);
415    }
416    Some(new_map)
417}
418
419#[cfg(test)]
420mod tests {
421    use std::{borrow::Cow, path::Path};
422
423    use crate::{TaskVariables, VariableName};
424
425    use super::*;
426
427    const TEST_ID_BASE: &str = "test_base";
428
429    #[test]
430    fn test_resolving_templates_with_blank_command_and_label() {
431        let task_with_all_properties = TaskTemplate {
432            label: "test_label".to_string(),
433            command: "test_command".to_string(),
434            args: vec!["test_arg".to_string()],
435            env: HashMap::from_iter([("test_env_key".to_string(), "test_env_var".to_string())]),
436            ..TaskTemplate::default()
437        };
438
439        for task_with_blank_property in &[
440            TaskTemplate {
441                label: "".to_string(),
442                ..task_with_all_properties.clone()
443            },
444            TaskTemplate {
445                command: "".to_string(),
446                ..task_with_all_properties.clone()
447            },
448            TaskTemplate {
449                label: "".to_string(),
450                command: "".to_string(),
451                ..task_with_all_properties.clone()
452            },
453        ] {
454            assert_eq!(
455                task_with_blank_property.resolve_task(TEST_ID_BASE, &TaskContext::default()),
456                None,
457                "should not resolve task with blank label and/or command: {task_with_blank_property:?}"
458            );
459        }
460    }
461
462    #[test]
463    fn test_template_cwd_resolution() {
464        let task_without_cwd = TaskTemplate {
465            cwd: None,
466            label: "test task".to_string(),
467            command: "echo 4".to_string(),
468            ..TaskTemplate::default()
469        };
470
471        let resolved_task = |task_template: &TaskTemplate, task_cx| {
472            let resolved_task = task_template
473                .resolve_task(TEST_ID_BASE, task_cx)
474                .unwrap_or_else(|| panic!("failed to resolve task {task_without_cwd:?}"));
475            assert_substituted_variables(&resolved_task, Vec::new());
476            resolved_task
477                .resolved
478                .clone()
479                .unwrap_or_else(|| {
480                    panic!("failed to get resolve data for resolved task. Template: {task_without_cwd:?} Resolved: {resolved_task:?}")
481                })
482        };
483
484        let cx = TaskContext {
485            cwd: None,
486            task_variables: TaskVariables::default(),
487            project_env: HashMap::default(),
488        };
489        assert_eq!(
490            resolved_task(&task_without_cwd, &cx).cwd,
491            None,
492            "When neither task nor task context have cwd, it should be None"
493        );
494
495        let context_cwd = Path::new("a").join("b").join("c");
496        let cx = TaskContext {
497            cwd: Some(context_cwd.clone()),
498            task_variables: TaskVariables::default(),
499            project_env: HashMap::default(),
500        };
501        assert_eq!(
502            resolved_task(&task_without_cwd, &cx).cwd,
503            Some(context_cwd.clone()),
504            "TaskContext's cwd should be taken on resolve if task's cwd is None"
505        );
506
507        let task_cwd = Path::new("d").join("e").join("f");
508        let mut task_with_cwd = task_without_cwd.clone();
509        task_with_cwd.cwd = Some(task_cwd.display().to_string());
510        let task_with_cwd = task_with_cwd;
511
512        let cx = TaskContext {
513            cwd: None,
514            task_variables: TaskVariables::default(),
515            project_env: HashMap::default(),
516        };
517        assert_eq!(
518            resolved_task(&task_with_cwd, &cx).cwd,
519            Some(task_cwd.clone()),
520            "TaskTemplate's cwd should be taken on resolve if TaskContext's cwd is None"
521        );
522
523        let cx = TaskContext {
524            cwd: Some(context_cwd.clone()),
525            task_variables: TaskVariables::default(),
526            project_env: HashMap::default(),
527        };
528        assert_eq!(
529            resolved_task(&task_with_cwd, &cx).cwd,
530            Some(task_cwd),
531            "TaskTemplate's cwd should be taken on resolve if TaskContext's cwd is not None"
532        );
533    }
534
535    #[test]
536    fn test_template_variables_resolution() {
537        let custom_variable_1 = VariableName::Custom(Cow::Borrowed("custom_variable_1"));
538        let custom_variable_2 = VariableName::Custom(Cow::Borrowed("custom_variable_2"));
539        let long_value = "01".repeat(MAX_DISPLAY_VARIABLE_LENGTH * 2);
540        let all_variables = [
541            (VariableName::Row, "1234".to_string()),
542            (VariableName::Column, "5678".to_string()),
543            (VariableName::File, "test_file".to_string()),
544            (VariableName::SelectedText, "test_selected_text".to_string()),
545            (VariableName::Symbol, long_value.clone()),
546            (VariableName::WorktreeRoot, "/test_root/".to_string()),
547            (
548                custom_variable_1.clone(),
549                "test_custom_variable_1".to_string(),
550            ),
551            (
552                custom_variable_2.clone(),
553                "test_custom_variable_2".to_string(),
554            ),
555        ];
556
557        let task_with_all_variables = TaskTemplate {
558            label: format!(
559                "test label for {} and {}",
560                VariableName::Row.template_value(),
561                VariableName::Symbol.template_value(),
562            ),
563            command: format!(
564                "echo {} {}",
565                VariableName::File.template_value(),
566                VariableName::Symbol.template_value(),
567            ),
568            args: vec![
569                format!("arg1 {}", VariableName::SelectedText.template_value()),
570                format!("arg2 {}", VariableName::Column.template_value()),
571                format!("arg3 {}", VariableName::Symbol.template_value()),
572            ],
573            env: HashMap::from_iter([
574                ("test_env_key".to_string(), "test_env_var".to_string()),
575                (
576                    "env_key_1".to_string(),
577                    VariableName::WorktreeRoot.template_value(),
578                ),
579                (
580                    "env_key_2".to_string(),
581                    format!(
582                        "env_var_2 {} {}",
583                        custom_variable_1.template_value(),
584                        custom_variable_2.template_value()
585                    ),
586                ),
587                (
588                    "env_key_3".to_string(),
589                    format!("env_var_3 {}", VariableName::Symbol.template_value()),
590                ),
591            ]),
592            ..TaskTemplate::default()
593        };
594
595        let mut first_resolved_id = None;
596        for i in 0..15 {
597            let resolved_task = task_with_all_variables.resolve_task(
598                TEST_ID_BASE,
599                &TaskContext {
600                    cwd: None,
601                    task_variables: TaskVariables::from_iter(all_variables.clone()),
602                    project_env: HashMap::default(),
603                },
604            ).unwrap_or_else(|| panic!("Should successfully resolve task {task_with_all_variables:?} with variables {all_variables:?}"));
605
606            match &first_resolved_id {
607                None => first_resolved_id = Some(resolved_task.id.clone()),
608                Some(first_id) => assert_eq!(
609                    &resolved_task.id, first_id,
610                    "Step {i}, for the same task template and context, there should be the same resolved task id"
611                ),
612            }
613
614            assert_eq!(
615                resolved_task.original_task, task_with_all_variables,
616                "Resolved task should store its template without changes"
617            );
618            assert_eq!(
619                resolved_task.resolved_label,
620                format!("test label for 1234 and {long_value}"),
621                "Resolved task label should be substituted with variables and those should not be shortened"
622            );
623            assert_substituted_variables(
624                &resolved_task,
625                all_variables.iter().map(|(name, _)| name.clone()).collect(),
626            );
627
628            let spawn_in_terminal = resolved_task
629                .resolved
630                .as_ref()
631                .expect("should have resolved a spawn in terminal task");
632            assert_eq!(
633                spawn_in_terminal.label,
634                format!(
635                    "test label for 1234 and …{}",
636                    &long_value[long_value.len() - MAX_DISPLAY_VARIABLE_LENGTH..]
637                ),
638                "Human-readable label should have long substitutions trimmed"
639            );
640            assert_eq!(
641                spawn_in_terminal.command,
642                format!("echo test_file {long_value}"),
643                "Command should be substituted with variables and those should not be shortened"
644            );
645            assert_eq!(
646                spawn_in_terminal.args,
647                &[
648                    "arg1 $ZED_SELECTED_TEXT",
649                    "arg2 $ZED_COLUMN",
650                    "arg3 $ZED_SYMBOL",
651                ],
652                "Args should not be substituted with variables"
653            );
654            assert_eq!(
655                spawn_in_terminal.command_label,
656                format!(
657                    "{} arg1 test_selected_text arg2 5678 arg3 {long_value}",
658                    spawn_in_terminal.command
659                ),
660                "Command label args should be substituted with variables and those should not be shortened"
661            );
662
663            assert_eq!(
664                spawn_in_terminal
665                    .env
666                    .get("test_env_key")
667                    .map(|s| s.as_str()),
668                Some("test_env_var")
669            );
670            assert_eq!(
671                spawn_in_terminal.env.get("env_key_1").map(|s| s.as_str()),
672                Some("/test_root/")
673            );
674            assert_eq!(
675                spawn_in_terminal.env.get("env_key_2").map(|s| s.as_str()),
676                Some("env_var_2 test_custom_variable_1 test_custom_variable_2")
677            );
678            assert_eq!(
679                spawn_in_terminal.env.get("env_key_3"),
680                Some(&format!("env_var_3 {long_value}")),
681                "Env vars should be substituted with variables and those should not be shortened"
682            );
683        }
684
685        for i in 0..all_variables.len() {
686            let mut not_all_variables = all_variables.to_vec();
687            let removed_variable = not_all_variables.remove(i);
688            let resolved_task_attempt = task_with_all_variables.resolve_task(
689                TEST_ID_BASE,
690                &TaskContext {
691                    cwd: None,
692                    task_variables: TaskVariables::from_iter(not_all_variables),
693                    project_env: HashMap::default(),
694                },
695            );
696            assert_eq!(
697                resolved_task_attempt, None,
698                "If any of the Zed task variables is not substituted, the task should not be resolved, but got some resolution without the variable {removed_variable:?} (index {i})"
699            );
700        }
701    }
702
703    #[test]
704    fn test_can_resolve_free_variables() {
705        let task = TaskTemplate {
706            label: "My task".into(),
707            command: "echo".into(),
708            args: vec!["$PATH".into()],
709            ..TaskTemplate::default()
710        };
711        let resolved_task = task
712            .resolve_task(TEST_ID_BASE, &TaskContext::default())
713            .unwrap();
714        assert_substituted_variables(&resolved_task, Vec::new());
715        let resolved = resolved_task.resolved.unwrap();
716        assert_eq!(resolved.label, task.label);
717        assert_eq!(resolved.command, task.command);
718        assert_eq!(resolved.args, task.args);
719    }
720
721    #[test]
722    fn test_errors_on_missing_zed_variable() {
723        let task = TaskTemplate {
724            label: "My task".into(),
725            command: "echo".into(),
726            args: vec!["$ZED_VARIABLE".into()],
727            ..TaskTemplate::default()
728        };
729        assert!(
730            task.resolve_task(TEST_ID_BASE, &TaskContext::default())
731                .is_none()
732        );
733    }
734
735    #[test]
736    fn test_symbol_dependent_tasks() {
737        let task_with_all_properties = TaskTemplate {
738            label: "test_label".to_string(),
739            command: "test_command".to_string(),
740            args: vec!["test_arg".to_string()],
741            env: HashMap::from_iter([("test_env_key".to_string(), "test_env_var".to_string())]),
742            ..TaskTemplate::default()
743        };
744        let cx = TaskContext {
745            cwd: None,
746            task_variables: TaskVariables::from_iter(Some((
747                VariableName::Symbol,
748                "test_symbol".to_string(),
749            ))),
750            project_env: HashMap::default(),
751        };
752
753        for (i, symbol_dependent_task) in [
754            TaskTemplate {
755                label: format!("test_label_{}", VariableName::Symbol.template_value()),
756                ..task_with_all_properties.clone()
757            },
758            TaskTemplate {
759                command: format!("test_command_{}", VariableName::Symbol.template_value()),
760                ..task_with_all_properties.clone()
761            },
762            TaskTemplate {
763                args: vec![format!(
764                    "test_arg_{}",
765                    VariableName::Symbol.template_value()
766                )],
767                ..task_with_all_properties.clone()
768            },
769            TaskTemplate {
770                env: HashMap::from_iter([(
771                    "test_env_key".to_string(),
772                    format!("test_env_var_{}", VariableName::Symbol.template_value()),
773                )]),
774                ..task_with_all_properties.clone()
775            },
776        ]
777        .into_iter()
778        .enumerate()
779        {
780            let resolved = symbol_dependent_task
781                .resolve_task(TEST_ID_BASE, &cx)
782                .unwrap_or_else(|| panic!("Failed to resolve task {symbol_dependent_task:?}"));
783            assert_eq!(
784                resolved.substituted_variables,
785                HashSet::from_iter(Some(VariableName::Symbol)),
786                "(index {i}) Expected the task to depend on symbol task variable: {resolved:?}"
787            )
788        }
789    }
790
791    #[track_caller]
792    fn assert_substituted_variables(resolved_task: &ResolvedTask, mut expected: Vec<VariableName>) {
793        let mut resolved_variables = resolved_task
794            .substituted_variables
795            .iter()
796            .cloned()
797            .collect::<Vec<_>>();
798        resolved_variables.sort_by_key(|var| var.to_string());
799        expected.sort_by_key(|var| var.to_string());
800        assert_eq!(resolved_variables, expected)
801    }
802
803    #[test]
804    fn substitute_funky_labels() {
805        let faulty_go_test = TaskTemplate {
806            label: format!(
807                "go test {}/{}",
808                VariableName::Symbol.template_value(),
809                VariableName::Symbol.template_value(),
810            ),
811            command: "go".into(),
812            args: vec![format!(
813                "^{}$/^{}$",
814                VariableName::Symbol.template_value(),
815                VariableName::Symbol.template_value()
816            )],
817            ..TaskTemplate::default()
818        };
819        let mut context = TaskContext::default();
820        context
821            .task_variables
822            .insert(VariableName::Symbol, "my-symbol".to_string());
823        assert!(faulty_go_test.resolve_task("base", &context).is_some());
824    }
825
826    #[test]
827    fn test_project_env() {
828        let all_variables = [
829            (VariableName::Row, "1234".to_string()),
830            (VariableName::Column, "5678".to_string()),
831            (VariableName::File, "test_file".to_string()),
832            (VariableName::Symbol, "my symbol".to_string()),
833        ];
834
835        let template = TaskTemplate {
836            label: "my task".to_string(),
837            command: format!(
838                "echo {} {}",
839                VariableName::File.template_value(),
840                VariableName::Symbol.template_value(),
841            ),
842            args: vec![],
843            env: HashMap::from_iter([
844                (
845                    "TASK_ENV_VAR1".to_string(),
846                    "TASK_ENV_VAR1_VALUE".to_string(),
847                ),
848                (
849                    "TASK_ENV_VAR2".to_string(),
850                    format!(
851                        "env_var_2 {} {}",
852                        VariableName::Row.template_value(),
853                        VariableName::Column.template_value()
854                    ),
855                ),
856                (
857                    "PROJECT_ENV_WILL_BE_OVERWRITTEN".to_string(),
858                    "overwritten".to_string(),
859                ),
860            ]),
861            ..TaskTemplate::default()
862        };
863
864        let project_env = HashMap::from_iter([
865            (
866                "PROJECT_ENV_VAR1".to_string(),
867                "PROJECT_ENV_VAR1_VALUE".to_string(),
868            ),
869            (
870                "PROJECT_ENV_WILL_BE_OVERWRITTEN".to_string(),
871                "PROJECT_ENV_WILL_BE_OVERWRITTEN_VALUE".to_string(),
872            ),
873        ]);
874
875        let context = TaskContext {
876            cwd: None,
877            task_variables: TaskVariables::from_iter(all_variables.clone()),
878            project_env,
879        };
880
881        let resolved = template
882            .resolve_task(TEST_ID_BASE, &context)
883            .unwrap()
884            .resolved
885            .unwrap();
886
887        assert_eq!(resolved.env["TASK_ENV_VAR1"], "TASK_ENV_VAR1_VALUE");
888        assert_eq!(resolved.env["TASK_ENV_VAR2"], "env_var_2 1234 5678");
889        assert_eq!(resolved.env["PROJECT_ENV_VAR1"], "PROJECT_ENV_VAR1_VALUE");
890        assert_eq!(
891            resolved.env["PROJECT_ENV_WILL_BE_OVERWRITTEN"],
892            "overwritten"
893        );
894    }
895}