task_template.rs

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