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