task_template.rs

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