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