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                show_rerun: true,
259            }),
260        })
261    }
262}
263
264const MAX_DISPLAY_VARIABLE_LENGTH: usize = 15;
265
266fn truncate_variables(task_variables: &HashMap<String, &str>) -> HashMap<String, String> {
267    task_variables
268        .iter()
269        .map(|(key, value)| {
270            (
271                key.clone(),
272                truncate_and_remove_front(value, MAX_DISPLAY_VARIABLE_LENGTH),
273            )
274        })
275        .collect()
276}
277
278fn to_hex_hash(object: impl Serialize) -> anyhow::Result<String> {
279    let json = serde_json_lenient::to_string(&object).context("serializing the object")?;
280    let mut hasher = Sha256::new();
281    hasher.update(json.as_bytes());
282    Ok(hex::encode(hasher.finalize()))
283}
284
285fn substitute_all_template_variables_in_str<A: AsRef<str>>(
286    template_str: &str,
287    task_variables: &HashMap<String, A>,
288    variable_names: &HashMap<String, VariableName>,
289    substituted_variables: &mut HashSet<VariableName>,
290) -> Option<String> {
291    let substituted_string = shellexpand::env_with_context(template_str, |var| {
292        // 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.
293        let colon_position = var.find(':').unwrap_or(var.len());
294        let (variable_name, default) = var.split_at(colon_position);
295        if let Some(name) = task_variables.get(variable_name) {
296            if let Some(substituted_variable) = variable_names.get(variable_name) {
297                substituted_variables.insert(substituted_variable.clone());
298            }
299
300            let mut name = name.as_ref().to_owned();
301            // Got a task variable hit
302            if !default.is_empty() {
303                name.push_str(default);
304            }
305            return Ok(Some(name));
306        } else if variable_name.starts_with(ZED_VARIABLE_NAME_PREFIX) {
307            bail!("Unknown variable name: {variable_name}");
308        }
309        // This is an unknown variable.
310        // 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.
311        // If there's a default, we need to return the string verbatim as otherwise shellexpand will apply that default for us.
312        if !default.is_empty() {
313            return Ok(Some(format!("${{{var}}}")));
314        }
315        // Else we can just return None and that variable will be left as is.
316        Ok(None)
317    })
318    .ok()?;
319    Some(substituted_string.into_owned())
320}
321
322fn substitute_all_template_variables_in_vec(
323    template_strs: &[String],
324    task_variables: &HashMap<String, &str>,
325    variable_names: &HashMap<String, VariableName>,
326    substituted_variables: &mut HashSet<VariableName>,
327) -> Option<Vec<String>> {
328    let mut expanded = Vec::with_capacity(template_strs.len());
329    for variable in template_strs {
330        let new_value = substitute_all_template_variables_in_str(
331            variable,
332            task_variables,
333            variable_names,
334            substituted_variables,
335        )?;
336        expanded.push(new_value);
337    }
338    Some(expanded)
339}
340
341fn substitute_all_template_variables_in_map(
342    keys_and_values: &HashMap<String, String>,
343    task_variables: &HashMap<String, &str>,
344    variable_names: &HashMap<String, VariableName>,
345    substituted_variables: &mut HashSet<VariableName>,
346) -> Option<HashMap<String, String>> {
347    let mut new_map: HashMap<String, String> = Default::default();
348    for (key, value) in keys_and_values {
349        let new_value = substitute_all_template_variables_in_str(
350            value,
351            task_variables,
352            variable_names,
353            substituted_variables,
354        )?;
355        let new_key = substitute_all_template_variables_in_str(
356            key,
357            task_variables,
358            variable_names,
359            substituted_variables,
360        )?;
361        new_map.insert(new_key, new_value);
362    }
363    Some(new_map)
364}
365
366#[cfg(test)]
367mod tests {
368    use std::{borrow::Cow, path::Path};
369
370    use crate::{TaskVariables, VariableName};
371
372    use super::*;
373
374    const TEST_ID_BASE: &str = "test_base";
375
376    #[test]
377    fn test_resolving_templates_with_blank_command_and_label() {
378        let task_with_all_properties = TaskTemplate {
379            label: "test_label".to_string(),
380            command: "test_command".to_string(),
381            args: vec!["test_arg".to_string()],
382            env: HashMap::from_iter([("test_env_key".to_string(), "test_env_var".to_string())]),
383            ..TaskTemplate::default()
384        };
385
386        for task_with_blank_property in &[
387            TaskTemplate {
388                label: "".to_string(),
389                ..task_with_all_properties.clone()
390            },
391            TaskTemplate {
392                command: "".to_string(),
393                ..task_with_all_properties.clone()
394            },
395            TaskTemplate {
396                label: "".to_string(),
397                command: "".to_string(),
398                ..task_with_all_properties.clone()
399            },
400        ] {
401            assert_eq!(
402                task_with_blank_property.resolve_task(TEST_ID_BASE, &TaskContext::default()),
403                None,
404                "should not resolve task with blank label and/or command: {task_with_blank_property:?}"
405            );
406        }
407    }
408
409    #[test]
410    fn test_template_cwd_resolution() {
411        let task_without_cwd = TaskTemplate {
412            cwd: None,
413            label: "test task".to_string(),
414            command: "echo 4".to_string(),
415            ..TaskTemplate::default()
416        };
417
418        let resolved_task = |task_template: &TaskTemplate, task_cx| {
419            let resolved_task = task_template
420                .resolve_task(TEST_ID_BASE, task_cx)
421                .unwrap_or_else(|| panic!("failed to resolve task {task_without_cwd:?}"));
422            assert_substituted_variables(&resolved_task, Vec::new());
423            resolved_task
424                .resolved
425                .clone()
426                .unwrap_or_else(|| {
427                    panic!("failed to get resolve data for resolved task. Template: {task_without_cwd:?} Resolved: {resolved_task:?}")
428                })
429        };
430
431        let cx = TaskContext {
432            cwd: None,
433            task_variables: TaskVariables::default(),
434            project_env: HashMap::default(),
435        };
436        assert_eq!(
437            resolved_task(&task_without_cwd, &cx).cwd,
438            None,
439            "When neither task nor task context have cwd, it should be None"
440        );
441
442        let context_cwd = Path::new("a").join("b").join("c");
443        let cx = TaskContext {
444            cwd: Some(context_cwd.clone()),
445            task_variables: TaskVariables::default(),
446            project_env: HashMap::default(),
447        };
448        assert_eq!(
449            resolved_task(&task_without_cwd, &cx).cwd,
450            Some(context_cwd.clone()),
451            "TaskContext's cwd should be taken on resolve if task's cwd is None"
452        );
453
454        let task_cwd = Path::new("d").join("e").join("f");
455        let mut task_with_cwd = task_without_cwd.clone();
456        task_with_cwd.cwd = Some(task_cwd.display().to_string());
457        let task_with_cwd = task_with_cwd;
458
459        let cx = TaskContext {
460            cwd: None,
461            task_variables: TaskVariables::default(),
462            project_env: HashMap::default(),
463        };
464        assert_eq!(
465            resolved_task(&task_with_cwd, &cx).cwd,
466            Some(task_cwd.clone()),
467            "TaskTemplate's cwd should be taken on resolve if TaskContext's cwd is None"
468        );
469
470        let cx = TaskContext {
471            cwd: Some(context_cwd.clone()),
472            task_variables: TaskVariables::default(),
473            project_env: HashMap::default(),
474        };
475        assert_eq!(
476            resolved_task(&task_with_cwd, &cx).cwd,
477            Some(task_cwd),
478            "TaskTemplate's cwd should be taken on resolve if TaskContext's cwd is not None"
479        );
480    }
481
482    #[test]
483    fn test_template_variables_resolution() {
484        let custom_variable_1 = VariableName::Custom(Cow::Borrowed("custom_variable_1"));
485        let custom_variable_2 = VariableName::Custom(Cow::Borrowed("custom_variable_2"));
486        let long_value = "01".repeat(MAX_DISPLAY_VARIABLE_LENGTH * 2);
487        let all_variables = [
488            (VariableName::Row, "1234".to_string()),
489            (VariableName::Column, "5678".to_string()),
490            (VariableName::File, "test_file".to_string()),
491            (VariableName::SelectedText, "test_selected_text".to_string()),
492            (VariableName::Symbol, long_value.clone()),
493            (VariableName::WorktreeRoot, "/test_root/".to_string()),
494            (
495                custom_variable_1.clone(),
496                "test_custom_variable_1".to_string(),
497            ),
498            (
499                custom_variable_2.clone(),
500                "test_custom_variable_2".to_string(),
501            ),
502        ];
503
504        let task_with_all_variables = TaskTemplate {
505            label: format!(
506                "test label for {} and {}",
507                VariableName::Row.template_value(),
508                VariableName::Symbol.template_value(),
509            ),
510            command: format!(
511                "echo {} {}",
512                VariableName::File.template_value(),
513                VariableName::Symbol.template_value(),
514            ),
515            args: vec![
516                format!("arg1 {}", VariableName::SelectedText.template_value()),
517                format!("arg2 {}", VariableName::Column.template_value()),
518                format!("arg3 {}", VariableName::Symbol.template_value()),
519            ],
520            env: HashMap::from_iter([
521                ("test_env_key".to_string(), "test_env_var".to_string()),
522                (
523                    "env_key_1".to_string(),
524                    VariableName::WorktreeRoot.template_value(),
525                ),
526                (
527                    "env_key_2".to_string(),
528                    format!(
529                        "env_var_2 {} {}",
530                        custom_variable_1.template_value(),
531                        custom_variable_2.template_value()
532                    ),
533                ),
534                (
535                    "env_key_3".to_string(),
536                    format!("env_var_3 {}", VariableName::Symbol.template_value()),
537                ),
538            ]),
539            ..TaskTemplate::default()
540        };
541
542        let mut first_resolved_id = None;
543        for i in 0..15 {
544            let resolved_task = task_with_all_variables.resolve_task(
545                TEST_ID_BASE,
546                &TaskContext {
547                    cwd: None,
548                    task_variables: TaskVariables::from_iter(all_variables.clone()),
549                    project_env: HashMap::default(),
550                },
551            ).unwrap_or_else(|| panic!("Should successfully resolve task {task_with_all_variables:?} with variables {all_variables:?}"));
552
553            match &first_resolved_id {
554                None => first_resolved_id = Some(resolved_task.id.clone()),
555                Some(first_id) => assert_eq!(
556                    &resolved_task.id, first_id,
557                    "Step {i}, for the same task template and context, there should be the same resolved task id"
558                ),
559            }
560
561            assert_eq!(
562                resolved_task.original_task, task_with_all_variables,
563                "Resolved task should store its template without changes"
564            );
565            assert_eq!(
566                resolved_task.resolved_label,
567                format!("test label for 1234 and {long_value}"),
568                "Resolved task label should be substituted with variables and those should not be shortened"
569            );
570            assert_substituted_variables(
571                &resolved_task,
572                all_variables.iter().map(|(name, _)| name.clone()).collect(),
573            );
574
575            let spawn_in_terminal = resolved_task
576                .resolved
577                .as_ref()
578                .expect("should have resolved a spawn in terminal task");
579            assert_eq!(
580                spawn_in_terminal.label,
581                format!(
582                    "test label for 1234 and …{}",
583                    &long_value[long_value.len() - MAX_DISPLAY_VARIABLE_LENGTH..]
584                ),
585                "Human-readable label should have long substitutions trimmed"
586            );
587            assert_eq!(
588                spawn_in_terminal.command,
589                format!("echo test_file {long_value}"),
590                "Command should be substituted with variables and those should not be shortened"
591            );
592            assert_eq!(
593                spawn_in_terminal.args,
594                &[
595                    "arg1 $ZED_SELECTED_TEXT",
596                    "arg2 $ZED_COLUMN",
597                    "arg3 $ZED_SYMBOL",
598                ],
599                "Args should not be substituted with variables"
600            );
601            assert_eq!(
602                spawn_in_terminal.command_label,
603                format!("{} arg1 test_selected_text arg2 5678 arg3 {long_value}", spawn_in_terminal.command),
604                "Command label args should be substituted with variables and those should not be shortened"
605            );
606
607            assert_eq!(
608                spawn_in_terminal
609                    .env
610                    .get("test_env_key")
611                    .map(|s| s.as_str()),
612                Some("test_env_var")
613            );
614            assert_eq!(
615                spawn_in_terminal.env.get("env_key_1").map(|s| s.as_str()),
616                Some("/test_root/")
617            );
618            assert_eq!(
619                spawn_in_terminal.env.get("env_key_2").map(|s| s.as_str()),
620                Some("env_var_2 test_custom_variable_1 test_custom_variable_2")
621            );
622            assert_eq!(
623                spawn_in_terminal.env.get("env_key_3"),
624                Some(&format!("env_var_3 {long_value}")),
625                "Env vars should be substituted with variables and those should not be shortened"
626            );
627        }
628
629        for i in 0..all_variables.len() {
630            let mut not_all_variables = all_variables.to_vec();
631            let removed_variable = not_all_variables.remove(i);
632            let resolved_task_attempt = task_with_all_variables.resolve_task(
633                TEST_ID_BASE,
634                &TaskContext {
635                    cwd: None,
636                    task_variables: TaskVariables::from_iter(not_all_variables),
637                    project_env: HashMap::default(),
638                },
639            );
640            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})");
641        }
642    }
643
644    #[test]
645    fn test_can_resolve_free_variables() {
646        let task = TaskTemplate {
647            label: "My task".into(),
648            command: "echo".into(),
649            args: vec!["$PATH".into()],
650            ..TaskTemplate::default()
651        };
652        let resolved_task = task
653            .resolve_task(TEST_ID_BASE, &TaskContext::default())
654            .unwrap();
655        assert_substituted_variables(&resolved_task, Vec::new());
656        let resolved = resolved_task.resolved.unwrap();
657        assert_eq!(resolved.label, task.label);
658        assert_eq!(resolved.command, task.command);
659        assert_eq!(resolved.args, task.args);
660    }
661
662    #[test]
663    fn test_errors_on_missing_zed_variable() {
664        let task = TaskTemplate {
665            label: "My task".into(),
666            command: "echo".into(),
667            args: vec!["$ZED_VARIABLE".into()],
668            ..TaskTemplate::default()
669        };
670        assert!(task
671            .resolve_task(TEST_ID_BASE, &TaskContext::default())
672            .is_none());
673    }
674
675    #[test]
676    fn test_symbol_dependent_tasks() {
677        let task_with_all_properties = TaskTemplate {
678            label: "test_label".to_string(),
679            command: "test_command".to_string(),
680            args: vec!["test_arg".to_string()],
681            env: HashMap::from_iter([("test_env_key".to_string(), "test_env_var".to_string())]),
682            ..TaskTemplate::default()
683        };
684        let cx = TaskContext {
685            cwd: None,
686            task_variables: TaskVariables::from_iter(Some((
687                VariableName::Symbol,
688                "test_symbol".to_string(),
689            ))),
690            project_env: HashMap::default(),
691        };
692
693        for (i, symbol_dependent_task) in [
694            TaskTemplate {
695                label: format!("test_label_{}", VariableName::Symbol.template_value()),
696                ..task_with_all_properties.clone()
697            },
698            TaskTemplate {
699                command: format!("test_command_{}", VariableName::Symbol.template_value()),
700                ..task_with_all_properties.clone()
701            },
702            TaskTemplate {
703                args: vec![format!(
704                    "test_arg_{}",
705                    VariableName::Symbol.template_value()
706                )],
707                ..task_with_all_properties.clone()
708            },
709            TaskTemplate {
710                env: HashMap::from_iter([(
711                    "test_env_key".to_string(),
712                    format!("test_env_var_{}", VariableName::Symbol.template_value()),
713                )]),
714                ..task_with_all_properties.clone()
715            },
716        ]
717        .into_iter()
718        .enumerate()
719        {
720            let resolved = symbol_dependent_task
721                .resolve_task(TEST_ID_BASE, &cx)
722                .unwrap_or_else(|| panic!("Failed to resolve task {symbol_dependent_task:?}"));
723            assert_eq!(
724                resolved.substituted_variables,
725                HashSet::from_iter(Some(VariableName::Symbol)),
726                "(index {i}) Expected the task to depend on symbol task variable: {resolved:?}"
727            )
728        }
729    }
730
731    #[track_caller]
732    fn assert_substituted_variables(resolved_task: &ResolvedTask, mut expected: Vec<VariableName>) {
733        let mut resolved_variables = resolved_task
734            .substituted_variables
735            .iter()
736            .cloned()
737            .collect::<Vec<_>>();
738        resolved_variables.sort_by_key(|var| var.to_string());
739        expected.sort_by_key(|var| var.to_string());
740        assert_eq!(resolved_variables, expected)
741    }
742
743    #[test]
744    fn substitute_funky_labels() {
745        let faulty_go_test = TaskTemplate {
746            label: format!(
747                "go test {}/{}",
748                VariableName::Symbol.template_value(),
749                VariableName::Symbol.template_value(),
750            ),
751            command: "go".into(),
752            args: vec![format!(
753                "^{}$/^{}$",
754                VariableName::Symbol.template_value(),
755                VariableName::Symbol.template_value()
756            )],
757            ..TaskTemplate::default()
758        };
759        let mut context = TaskContext::default();
760        context
761            .task_variables
762            .insert(VariableName::Symbol, "my-symbol".to_string());
763        assert!(faulty_go_test.resolve_task("base", &context).is_some());
764    }
765
766    #[test]
767    fn test_project_env() {
768        let all_variables = [
769            (VariableName::Row, "1234".to_string()),
770            (VariableName::Column, "5678".to_string()),
771            (VariableName::File, "test_file".to_string()),
772            (VariableName::Symbol, "my symbol".to_string()),
773        ];
774
775        let template = TaskTemplate {
776            label: "my task".to_string(),
777            command: format!(
778                "echo {} {}",
779                VariableName::File.template_value(),
780                VariableName::Symbol.template_value(),
781            ),
782            args: vec![],
783            env: HashMap::from_iter([
784                (
785                    "TASK_ENV_VAR1".to_string(),
786                    "TASK_ENV_VAR1_VALUE".to_string(),
787                ),
788                (
789                    "TASK_ENV_VAR2".to_string(),
790                    format!(
791                        "env_var_2 {} {}",
792                        VariableName::Row.template_value(),
793                        VariableName::Column.template_value()
794                    ),
795                ),
796                (
797                    "PROJECT_ENV_WILL_BE_OVERWRITTEN".to_string(),
798                    "overwritten".to_string(),
799                ),
800            ]),
801            ..TaskTemplate::default()
802        };
803
804        let project_env = HashMap::from_iter([
805            (
806                "PROJECT_ENV_VAR1".to_string(),
807                "PROJECT_ENV_VAR1_VALUE".to_string(),
808            ),
809            (
810                "PROJECT_ENV_WILL_BE_OVERWRITTEN".to_string(),
811                "PROJECT_ENV_WILL_BE_OVERWRITTEN_VALUE".to_string(),
812            ),
813        ]);
814
815        let context = TaskContext {
816            cwd: None,
817            task_variables: TaskVariables::from_iter(all_variables.clone()),
818            project_env,
819        };
820
821        let resolved = template
822            .resolve_task(TEST_ID_BASE, &context)
823            .unwrap()
824            .resolved
825            .unwrap();
826
827        assert_eq!(resolved.env["TASK_ENV_VAR1"], "TASK_ENV_VAR1_VALUE");
828        assert_eq!(resolved.env["TASK_ENV_VAR2"], "env_var_2 1234 5678");
829        assert_eq!(resolved.env["PROJECT_ENV_VAR1"], "PROJECT_ENV_VAR1_VALUE");
830        assert_eq!(
831            resolved.env["PROJECT_ENV_WILL_BE_OVERWRITTEN"],
832            "overwritten"
833        );
834    }
835}