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